Spring endpoint prevent default accept header */*

Viewed 16

I'm creating an endpoint where I want to force the user to set the Accept http header:

@GetMapping("/")
public void get(@RequestHeader(HttpHeaders.ACCEPT) MediaType accept) {
    //accept == MediaType.ALL
}

Problem: localhost:8080/ without any Accept header results in Accept=*/* on Spring side.

Question: how can I tell Spring to not use the */* all by default, and reject requests directly without that header?

1 Answers
  • What you want (force the user to set the Accept http header),
  • What you catch (without any Accept header results in Accept=*/* at back-end),
  • What you ask (how can I tell Spring to not use the */* all by default, and reject requests directly without that header)

Answer:

You use Spring Security config. No out-of-the-box setting https://docs.spring.io/spring-boot/docs/current/reference/html/application-properties.html#appendix.application-properties.security

Write custom filter check header, implement GenericFilterBean.

public class CustomAuthenticationFilter extends GenericFilterBean {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        // Get header and validate from request object.
        filterChain.doFilter(request, response);
    }
}

Hook the filter into your security configuration

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
            // other security config
            .addFilterBefore(new CustomAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
}
Related