mhshams
mhshams

Reputation: 16972

SpringSecurity - RequestHeaderRequestMatcher

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?

Upvotes: 2

Views: 2132

Answers (2)

fateddy
fateddy

Reputation: 7157

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"));
    }
}

Upvotes: 1

mrtasln
mrtasln

Reputation: 614

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

Upvotes: 0

Related Questions