spring - 如何巧妙地配置 Spring WebSecurity
问题描述
我目前正在使用 Spring Security 设置反向代理安全域,其想法是默认情况下在所有请求上都需要不记名令牌,除了一些例外,例如注册等。目前我的配置功能看起来像如下:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable().authorizeRequests()
.antMatchers(HttpMethod.POST, SIGN_UP_URL).permitAll()
.anyRequest().authenticated()
.and()
.addFilter(new JWTAuthenticationFilter(authenticationManager()))
.addFilter(new JWTAuthorizationFilter(authenticationManager()))
// this disables session creation on Spring Security
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
Ant 匹配器非常有用,但您必须单独传递所有 URL。有没有办法让我传入一个字符串数组,以便我可以将配置分开?
解决方案
http.cors().and().csrf().disable().authorizeRequests()
.antMatchers(HttpMethod.POST, SIGN_UP_URL).permitAll()
在上面的代码antMatchers
中也将接受字符串数组。下面是 spring security 中 anyMatcher 方法的实现4.2.3.RELEASE
。根据方法签名,您应该能够传递包含所需路径的字符串数组。
/**
* Maps a {@link List} of
* {@link org.springframework.security.web.util.matcher.AntPathRequestMatcher}
* instances that do not care which {@link HttpMethod} is used.
*
* @param antPatterns the ant patterns to create
* {@link org.springframework.security.web.util.matcher.AntPathRequestMatcher} from
*
* @return the object that is chained after creating the {@link RequestMatcher}
*/
public C antMatchers(String... antPatterns) {
return chainRequestMatchers(RequestMatchers.antMatchers(antPatterns));
}
如果您深入研究实现,spring 正在将此 args 转换为所有路径的 ArrayList。
此外,还有另一种方法。WebSecurityConfigurerAdapter
如果要扩展 spring 的类,要忽略不应由 spring security 保护的路径,请再次覆盖相同的方法。
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("path":);
}
我想这种方式很整洁。
推荐阅读
- testing - Rust 禁用特定目标的所有测试
- android - 开始活动而不在屏幕上闪烁/闪烁
- python - 聚合到多索引,同时将一些列名设置为行名并通过它们汇总列集
- frontend - 有没有办法创建别名/变量/命令以在赛普拉斯测试中重复静态代码块?
- parsing - 为什么TPTP(千题...)公式的解析树中有二进制公式(thf_binary_formula)?
- javascript - 将检查的项目详细信息推送到数组并使用 vuejs 基于检查/取消检查更新数组
- amazon-web-services - 无法增加 AWS Elastic Beanstalk 的超时时间
- json - Groovy JSON 转换为 CSV
- mysql - 如何计算已批准订单的美元金额占所下订单总美元金额的百分比?
- c++ - 带有常规 C++ 数组的迭代器或 std::iota?