简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM