由于我已经将Spring版本更新为2.6.7,因此我得到的日志显示,不再推荐使用我定义不安全路由的方式。
日志消息:
You are asking Spring Security to ignore Ant [pattern='/actuator/**']. This is not recommended -- please use permitAll via HttpSecurity#authorizeHttpRequests instead.
我描述Security必须忽略这些模式的配置方式是通过定义WebSecurityConfiguration和忽略这些路由来完成的。在本例中发生的情况是,跳过整个安全链,并写入上面提到的日志。对我来说没关系,但春天不行;)
@Configuration
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
public void configure(WebSecurity web) throws Exception {
web.ignoring()
.antMatchers(
"/actuator/**"
);
}
}
当将这些路由定义为日志中提到的httpSecurity的一部分时。出现的问题是,过期/无效令牌也会导致错误(401未经授权),也会导致/actuator/health
等不安全路由的错误。
@Configuration
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
@Getter
private String[] unsecuredPathList;
@PostConstruct
public void postConstruct() {
this.unsecuredPathList = new String[] {
"/actuator/**"};
}
@Bean
public JwtTokenStore jwtTokenStore() {
return new JwtTokenStore(new CustomJwtAccessTokenConverter(true));
}
@Override
public void configure(ResourceServerSecurityConfigurer resourceServer) throws Exception {
resourceServer.tokenStore(jwtTokenStore());
resourceServer.tokenExtractor(new SessionCookieTokenExtractor());
}
@Override
public void configure(HttpSecurity http) throws Exception {
http
.anonymous()
.authorities("ANONYMOUS")
.and()
.authorizeRequests()
.antMatchers(unsecuredPathList)
.permitAll()
.and()
.authorizeRequests()
.anyRequest()
.authenticated();
}
}
我想达到的目标是:对于不安全的资源,令牌不会被评估/结果被忽略,并且没有401-未经授权的错误。
在httpSecurity有什么我能做的吗?或者,是否还有其他建议的方法来达到这个目标?
提前谢谢你的帮助。
发布于 2022-08-11 14:13:17
HttpSecurity
类中有一组方法,它允许您只对特定路径应用已定义的安全规则,从而为不同的urls创建具有不同规则的不同安全筛选器链。
例如,您可以排除如下一些urls:
// convert your String array into a List of RequestMatcher
List<RequestMatcher> excludedPathMatchers = Arrays.stream(unsecuredPathList)
.map(AntPathRequestMatcher::new)
.collect(Collectors.toList());
// configure HttpSecurity to apply filter chain only on paths, that don't match any of the excluded paths
http.requestMatcher(new NegatedRequestMatcher(new OrRequestMatcher(excludedPathMatchers)));
如果只有一个不安全的端点,也可以编写类似的内容:
http.requestMatcher(new NegatedRequestMatcher(new AntPathRequestMatcher("/some_url/**")));
https://stackoverflow.com/questions/73316426
复制相似问题