piotrek
piotrek

Reputation: 14550

Unable to add custom config for spring security with oauth2

I have a spring boot app that works correctly with oauth2 (as a resource server). There is no custom configure(HttpSecurity http) method. Only

spring-boot-starter-security
spring-security-oauth2
spring-security-jwt

are added to pom.

Now i want to add endpoints that should be unprotected. So (following many SO responses) i started with adding:

@Configuration
public class Security extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
    }
}

and then i got:

Cannot apply org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer@6513fd22 to already built object

Full error:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'springSecurityFilterChain' defined in class path resource [org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is java.lang.IllegalStateException: Cannot apply org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer@6513fd22 to already built object

So how should i configure my security to add endpoints for anonymous access?

Upvotes: 0

Views: 1959

Answers (1)

lzagkaretos
lzagkaretos

Reputation: 2910

Error comes from empty body in configure() method.

You have to specify it explicitly. For instance (from a working application of us):

@Override
public void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
            .antMatchers("/unprotected/sample/find/**").permitAll()
            .antMatchers("/unprotected/another/register").permitAll()
            .anyRequest().authenticated().and()
            .csrf().disable();
}

Endpoints matching /unprotected/sample/find/** and /unprotected/sample/find/** are unprotected and everything else is protected.

Of course not protected endpoints should not have any @PreAuthorize() defined.

Upvotes: 1

Related Questions