spring-boot - 如何在没有身份验证的情况下允许 Spring Security 中的某些端点?
问题描述
我有 Spring Boot Rest API Web 应用程序,我在其中使用 Spring Security 让大多数端点需要身份验证。这是代码的一部分:
public class SecurityConfig extends WebSecurityConfigurerAdapter {
....
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.requestMatchers()
.antMatchers("/oauth/token")
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS).permitAll()
.anyRequest().authenticated();
}
有人可以解释以 http.csrf 开头的每一行的含义吗?
如何修改上面的代码,以便允许访问 enpoint /bars/pk 而无需身份验证,就像没有 Spring Security 一样?
解决方案
默认情况下,Spring Boot 激活对CSRF 攻击(跨站点请求伪造攻击)的保护。该攻击包括一个恶意站点,该站点利用已通过站点(例如银行)验证的用户来诱骗用户在该站点上执行操作(例如资金转移)。
针对攻击的保护包括 Spring Boot 应用程序在每个响应中发送一个令牌,并期望客户端在后续请求中发送该令牌。如果没有收到令牌,Spring Boot 会返回错误。
有时,您想禁用此行为(风险自负),因此您使用csrf.disable
. 如果您开发无状态 API,您可能会发现禁用 csrf 保护很方便,并且您无法将 POST 请求链接到任何先前的请求或会话。但同样,您需要考虑这一点并仔细推理。
请注意,CSRF 保护对 GET 请求没有影响。它只影响状态改变请求(例如 POST、DELETE)
为了允许您的 endoints 给任何人,而不需要任何身份验证,您需要使用
http.authorizeRequests().antMatchers("/**").permitAll();
编辑
要特别允许未经授权的请求/bars/pk
并保持其他元素不变,请按如下方式修改您的代码:
http.csrf().disable()
.requestMatchers()
.antMatchers("/oauth/token")
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS).permitAll()
.antMatchers("/bars/pk").permitAll()
.anyRequest().authenticated();
推荐阅读
- ios - 旋转景观 collectionView
- python - 尝试访问 Select Input Python Splinter 时元素不可见
- asp.net-mvc - 想要显示具有特定包含值的剑道列值
- haskell - Haskell Turtle 离开 Shell Monad
- oracle - Oracle:合并相当于插入所有?
- .net - 当本地帐户存在时,非域 cpu 上的 LogonUser Lib“advapi32.dll”奇怪吗?
- python - 将值插入数据框列
- javascript - 正则表达式以千、百万等添加逗号(但避免在小数点后添加它们)Javascript
- ruby-on-rails - (Rails 新手)rails 服务器错误:无法加载此类文件 -- bootsnap/setup (LoadError)
- powershell - Powershell GUI 文本框事件处理程序