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

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

问题描述

我正在使用Spring Security和Java配置

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

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

Note: CSRF protection is enabled by default with Java Configuration

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

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