首页 > 解决方案 > 如何在没有身份验证的情况下允许 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-bootspring-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();

推荐阅读