我在spring boot starter security V3.0.0上有问题
对于这个配置:
@Bean
public SecurityFilterChain filterChain( final HttpSecurity http ) throws Exception {
http
.cors().and().csrf().disable()
.sessionManagement().sessionCreationPolicy( SessionCreationPolicy.STATELESS )
.and()
.anonymous()
.and()
.authorizeHttpRequests()
.requestMatchers( HttpMethod.OPTIONS ).permitAll()
.requestMatchers( "/system/**" ).hasRole( new SecurityRole( Role.ROLE_SYSTEM ).toString() )
.requestMatchers( "/admin/**" ).hasRole( new SecurityRole( Role.ROLE_AUTH_ADMIN ).toString() )
.requestMatchers( "/identity/**" ).hasRole( new SecurityRole( Role.ROLE_AUTH_IDENTITY ).toString() )
.requestMatchers( "/guest/**" ).permitAll()
.anyRequest().authenticated()
.and()
.oauth2ResourceServer( OAuth2ResourceServerConfigurer::jwt );
return http.build();
}
所有由"/guest/**"端点被转换为没有正文的HTTP 401。甚至当我用这个类发出HTTP 409时:
@ResponseStatus( code = HttpStatus.CONFLICT )
public class HttpConflictException extends RuntimeException {
public HttpConflictException( String message ) {
super( message );
}
}
重要:当没有抛出异常时,查询工作
如果这行
.requestMatchers( "/guest/**" ).permitAll()
被替换为
.requestMatchers( "/**" ).permitAll()
它的工作原理。但这个选择似乎太危险了。我是不是没理解什么?我在文档中没有看到任何可以帮助解决这个问题的内容。
依赖性:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-oauth2-resource-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-oauth2-jose</artifactId>
</dependency>
谢谢。
好了,我找到了一个似乎有效的解决方案。
添加这行可以解决这个问题:
.dispatcherTypeMatchers( DispatcherType.ERROR ).permitAll()
完整代码:
@Bean
public SecurityFilterChain filterChain( final HttpSecurity http ) throws Exception {
http
.cors().and().csrf().disable()
.sessionManagement().sessionCreationPolicy( SessionCreationPolicy.STATELESS )
.and()
.anonymous()
.and()
.authorizeHttpRequests()
.dispatcherTypeMatchers( DispatcherType.ERROR ).permitAll()
.requestMatchers( HttpMethod.OPTIONS ).permitAll()
.requestMatchers( "/guest/**" ).permitAll()
.requestMatchers( "/system/**" ).hasRole( new SecurityRole( Role.ROLE_SYSTEM ).toString() )
.requestMatchers( "/admin/**" ).hasRole( new SecurityRole( Role.ROLE_AUTH_ADMIN ).toString() )
.requestMatchers( "/identity/**" ).hasRole( new SecurityRole( Role.ROLE_AUTH_IDENTITY ).toString() )
.anyRequest().authenticated()
.and()
.oauth2ResourceServer( OAuth2ResourceServerConfigurer::jwt );
return http.build();
}
文档:https://docs.spring.io/spring-security/reference/servlet/authorization/authorize-http-requests.html