【发布时间】:2022-08-12 00:02:04
【问题描述】:
这是我迁移前的工作安全配置:
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring()
.antMatchers(\"/auth/**\")
.antMatchers(\"/swagger-ui/**\")
.antMatchers(\"/swagger-ui.html\")
.antMatchers(\"/swagger-resources/**\")
.antMatchers(\"/v2/api-docs/**\")
.antMatchers(\"/v3/api-docs/**\");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter();
jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(grantedPortalRoleConverter);
http
.csrf().disable()
.cors()
.and()
.exceptionHandling()
.authenticationEntryPoint(new AuthenticationFallbackEntryPoint())
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests(authorize -> authorize.anyRequest().authenticated())
.oauth2ResourceServer()
.jwt().jwtAuthenticationConverter(jwtAuthenticationConverter);
}
这是我迁移后的安全链配置:
@Bean
@Order(1)
public SecurityFilterChain ignorePathsSecurityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(authorize -> authorize
.antMatchers(
\"/auth/**\",
\"/swagger-ui/**\",
\"/swagger-ui.html\",
\"/swagger-resources/**\",
\"/v3/api-docs/**\")
.permitAll());
return http.build();
}
@Bean
@Order(2)
public SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http, GrantedPortalRoleConverter grantedPortalRoleConverter) throws Exception {
JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter();
jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(grantedPortalRoleConverter);
http
.csrf().disable()
.cors(Customizer.withDefaults())
.exceptionHandling(configurer -> configurer.authenticationEntryPoint(new AuthenticationFallbackEntryPoint()))
.sessionManagement(configurer -> configurer.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(authorize -> authorize.anyRequest().authenticated())
.oauth2ResourceServer(configurer -> configurer.jwt().jwtAuthenticationConverter(jwtAuthenticationConverter));
return http.build();
}
使用原始配置,当我调用随机不存在的路径时:
@Test
void should_not_authenticate_or_return_not_found() throws Exception {
logger.info(\"should_not_authenticate_or_return_not_found\");
mvc.perform(get(\"/toto/tata\"))
.andExpect(status().isUnauthorized());
}
我得到:
15:44:00.230 [main] DEBUG o.s.s.w.a.i.FilterSecurityInterceptor - Failed to authorize filter invocation [GET /toto/tata] with attributes [authenticated]
使用新的 conf,我只是得到 HTTP 404,请问我在这里缺少什么?我看不到任何差异,调试日志也没有显示太多。
这是使用非工作 conf 丢失的第一行日志:
16:24:58.651 [main] DEBUG o.s.s.w.a.e.ExpressionBasedFilterInvocationSecurityMetadataSource - Adding web access control expression [authenticated] for any request
但是在两个日志中,我都可以看到(因为有 2 个安全链,所以新 conf 有 2 行):
o.s.s.web.DefaultSecurityFilterChain - Will secure any request with (...)