Willem van der Veen
Willem van der Veen

Reputation: 36650

Configure antMatchers with oauth2ResourceServer

My goal is to configure Spring Security in the following manner:

I have tried the code below, but this gives me the issue that it also tries to validate other routes than private.

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and()
                .authorizeRequests()
                .antMatchers("/private/**").authenticated()
                .antMatchers("/**").permitAll()
                .and()
                .oauth2ResourceServer().jwt();

      }

}

My dependencies are:

Any ideas?

Upvotes: 0

Views: 1228

Answers (1)

Willem van der Veen
Willem van der Veen

Reputation: 36650

Turned out to be blocked by csrf protection which is on by default in spring security.

The following for me was working:

@Override
public void configure(HttpSecurity http) throws Exception {
    http
            .cors().and()
            .csrf().disable()
            .authorizeRequests()
            .mvcMatchers("/private/**").authenticated()
            .mvcMatchers("/**").permitAll()
            .and()
            .oauth2ResourceServer().jwt();
}

Note that for this to work you need to have the following specified in your application.properties.

spring.security.oauth2.resourceserver.jwt.jwk-set-uri

For example in the case of google oauth2 this is:

spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://www.googleapis.com/oauth2/v3/certs

This points to the JSON web key (JWK) which is used to verify your token. Your token should be send as an Authorization header in the following form to your spring server:

bearer {{your token here}}

Upvotes: 1

Related Questions