0

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

  • Any routes starting with private should be authenticated via Spring Boot oauth2ResourceServer
  • All other routes should be freely accessible

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:

  • org.springframework.boot:spring-boot-starter-oauth2-resource-server:2.6.2
  • org.springframework.boot:spring-boot-starter-security:2.6.2
  • org.springframework.boot:spring-boot-starter-web:2.6.2

Any ideas?

Willem van der Veen
  • 33,665
  • 16
  • 190
  • 155

1 Answers1

1

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}}
Willem van der Veen
  • 33,665
  • 16
  • 190
  • 155