无法验证提供的 CSRF 令牌,因为在 Spring Security 中找不到您的会话 [英] Could not verify the provided CSRF token because your session was not found in spring security

查看:49
本文介绍了无法验证提供的 CSRF 令牌,因为在 Spring Security 中找不到您的会话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 spring security 和 java config

I am using spring security along with java config

@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 令牌",并且可以在请求标头中使用 X-CSRF-TOKEN 登录.但是登录后,当我点击发布请求(我在用于登录发布请求的请求标头中包含相同的令牌)时,我收到以下错误消息:

I am using PostMan for testing my REST services. I get 'csrf token' successfully and I am able to login by using X-CSRF-TOKEN in request header. But after login when i hit post request(I am including same token in request header that i used for login post request) I get the following error message:

HTTP 状态 403 - 无法验证提供的 CSRF 令牌,因为未找到您的会话.

谁能指导我我做错了什么.

Can any one guide me what I am doing wrong.

推荐答案

据spring.io:

According to spring.io:

什么时候应该使用 CSRF 保护?我们的建议是使用 CSRF保护可以由浏览器处理的任何请求普通用户.如果您只是创建一个由以下人员使用的服务非浏览器客户端,您可能需要禁用 CSRF 保护.

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();
  }
}

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

Note: CSRF protection is enabled by default with Java Configuration

这篇关于无法验证提供的 CSRF 令牌,因为在 Spring Security 中找不到您的会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆