java - 无法验证提供的 CSRF token ,因为在 Spring Security 中找不到您的 session

标签 java spring-security csrf spring-restcontroller

我正在使用 Spring Security 和 java 配置

@Override
protected void configure(HttpSecurity http) throws Exception { 
    http
    .authorizeRequests()
    .antMatchers("/api/*").hasRole("ADMIN")
    .and()
    .addFilterAfter(new CsrfTokenResponseHeaderBindingFilter(), CsrfFilter.class)
    .exceptionHandling()
    .authenticationEntryPoint(restAuthenticationEntryPoint)
    .and()
    .formLogin()
    .successHandler(authenticationSuccessHandler)
    .failureHandler(new SimpleUrlAuthenticationFailureHandler());

我正在使用 PostMan 测试我的 REST 服务。我成功获得了“csrf token”,并且可以在请求 header 中使用 X-CSRF-TOKEN 登录。但是登录后,当我点击发布请求时(我在请求 header 中包含了用于登录发布请求的相同 token )我收到以下错误消息:

HTTP 状态 403 - 无法验证提供的 CSRF token ,因为找不到您的 session 。

谁能指导我做错了什么。

最佳答案

根据spring.io:

When should you use CSRF protection? Our recommendation is to use CSRF protection for any request that could be processed by a browser by normal users. If you are only creating a service that is used by non-browser clients, you will likely want to disable CSRF protection.

所以要禁用它:

@Configuration
public class RestSecurityConfig extends WebSecurityConfigurerAdapter {
  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable();
  }
}

注意: CSRF 保护在 Java 配置中默认启用

关于java - 无法验证提供的 CSRF token ,因为在 Spring Security 中找不到您的 session ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38004035/

相关文章:

java - Spring安全无法找到登录url

security - CSRF保护:我们是否必须为每种表格生成 token ?

python - Django React axios 发布请求 : how to get csrftoken cookie?

java - 在java中将点转换为svg路径/文件

java - 尝试使用tools.jar-Gradle

Java 小程序未在浏览器中显示

apache - 如何防止跨站请求伪造攻击?

java - jpa和oracle客户端中相同的查询,不同的结果

java - 如何使用 Spring 安全性和 Restful Web 服务验证数据库中的凭据?

java - 使用 token 保护 REST api