无法使用 oauth2 为 spring 安全性添加自定义配置

Unable to add custom config for spring security with oauth2

我有一个 spring 引导应用程序可以与 oauth2(作为资源服务器)一起正常工作。没有自定义 configure(HttpSecurity http) 方法。只有

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

添加到 pom.

现在我想添加应该不受保护的端点。所以(在许多 SO 回复之后)我开始添加:

@Configuration
public class Security extends ResourceServerConfigurerAdapter {

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

然后我得到:

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

完整错误:

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

那么我应该如何配置我的安全性来为匿名访问添加端点?

错误来自 configure() 方法中的空主体。

您必须明确指定。例如(来自我们的工作应用程序):

@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();
}

匹配 /unprotected/sample/find/**/unprotected/sample/find/** 的端点未受保护,其他所有内容均受保护。

当然,不受保护的端点不应有任何 @PreAuthorize() 定义。