1

I would like to configure my webapp, to reject all requests that don't have proper "Content-Type". for example: any content-type other than "application/json" should be rejected.

Currently I am doing it by a custom filter, but I would like to know how it can be done by "RequestHeaderRequestMatcher" in security config directly?

Lets' take the following example security config:

EnableWebSecurity
class SecurityConfig : WebSecurityConfigurerAdapter() {

    override fun configure(http: HttpSecurity) {
        http.authorizeRequests()
                .requestMatchers(matcher)
                .denyAll()
                .antMatchers("/css/**", "/index")
                .permitAll()
                .antMatchers("/user/**")
                .hasRole("USER")

        http.formLogin()
                .loginPage("/login")
                .failureUrl("/login-error")
    }
}

How should I add the new request matcher to check all requests for valid content type?

mhshams
  • 16,384
  • 17
  • 55
  • 65

2 Answers2

1

One could use the RequestHeaderRequestMatcher to verify that a request contains a certain header. Furthermore a more precise test could be made to test against a certain value as well.

In the following case all requests must contain an Accept-Header having the value application/json. Otherwise an HTTP-Status 406 is returned.

@Configuration
class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.requestMatcher(new RequestHeaderRequestMatcher("Accept", "application/json"));
    }
}
fateddy
  • 6,887
  • 3
  • 22
  • 26
0

You can look into this document CORS and this answer can help you https://stackoverflow.com/a/43559288/5429215

mrtasln
  • 574
  • 1
  • 5
  • 18
  • 1
    Not quite relevant. The question is about header (content-type) values, not the allowed headers. – mhshams Oct 02 '17 at 15:48