spring 在Sping Boot 3.x中使用cutom AuthorizationManager允许URL路径

cs7cruho  于 2023-11-16  发布在  Spring
关注(0)|答案(1)|浏览(124)

我使用Sping Boot 3.0.6运行了以下安全配置:

@Configuration
@EnableWebSecurity
@Slf4j
public class SecurityConfig {

  private final JwtIssuerAuthenticationManagerResolver authenticationManagerResolver;
  private final OpaAuthorizationManager opaAuthorizationManager;

  @Autowired
  public SecurityConfig(@Value("${com.example.security.oauth2.resourceserver.jwt.issuer}") String[] issuer,
                        OpaAuthorizationManager opaAuthorizationManager) {
    this.authenticationManagerResolver = new JwtIssuerAuthenticationManagerResolver(issuer);
    this.opaAuthorizationManager = opaAuthorizationManager;
  }

  @Bean
  public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http
        .authorizeHttpRequests((requests) -> requests
            .requestMatchers(new AntPathRequestMatcher("/health")).permitAll()
            .requestMatchers(new AntPathRequestMatcher("/openapi/openapi.yml")).permitAll()
            .anyRequest().access(this.opaAuthorizationManager))
        .oauth2ResourceServer(oauth2 -> oauth2.authenticationManagerResolver(authenticationManagerResolver));
    return http.build();
  }
}

字符串
对于受限路径,一切正常。
但是,对于我配置为允许的路径,我得到了HTTP 401状态代码。(我所期望的)。相反,在调试时,我看到DefaultBearerTokenResolver抛出了一个OAuth2AuthenticationException。这导致尝试呈现/error路径,这是AuthorizationManager不允许的。因此;则返回HTTP 401。
在这种情况下,如何配置Spring Security,以便能够在没有JWT和授权的情况下调用允许的路径?

u5rb5r59

u5rb5r591#

我这样使用requestMatchers:

.requestMatchers("/enable").permitAll()

字符串

相关问题