简体   繁体   English

POST请求中的CSRF令牌无效

[英]Invalid CSRF Token in POST request

Overview 总览
I am going to use API Gateway as the authentication which based on Spring security. 我将使用API​​网关作为基于Spring安全性的身份验证。 I've just been following the steps in the https://spring.io/guides/tutorials/spring-security-and-angular-js/ link to create a project based on "pairs-double" module of its corresponding github project of https://github.com/spring-guides/tut-spring-security-and-angular-js.git . 我一直在按照https://spring.io/guides/tutorials/spring-security-and-angular-js/链接中的步骤创建一个基于其对应github项目的“ pairs-double”模块的项目https://github.com/spring-guides/tut-spring-security-and-angular-js.git

Problem 问题
The issue is the fact that when any POST request is submitted to the server the "Invalid CSRF Token" exception is thrown. 问题在于,当任何POST请求提交到服务器时,都会引发“无效的CSRF令牌”异常。 An example of the thrown exception is as follows: 引发异常的示例如下:

{
  "timestamp": 1461714933215,
  "status": 403,
  "error": "Forbidden",
  "message": "Invalid CSRF Token '1cdc44ad-43cb-44e6-b903-bec24fe903fd' was found on the request parameter '_csrf' or header 'X-XSRF-TOKEN'.",
  "path": "/ui/test"
}

I checked an rechecked the issue but to no avail. 我检查了一个重新检查的问题,但无济于事。 I tested this scenario with postman and set the 'X-XSRF-TOKEN' as the header of the POST request but nothing happened. 我用邮递员测试了这种情况,并将“ X-XSRF-TOKEN”设置为POST请求的标头,但没有任何反应。


So, as I am beginner in using Spring security approaches, I would appreciate it if anyone could suggest me a solution. 因此,作为使用Spring安全性方法的初学者,如果有人可以向我建议解决方案,我将不胜感激。

Looking at the security configuration of that project, you will notice that a XSRF-TOKEN cookie is being added in each request using a filter . 查看该项目的安全性配置,您会注意到,正在使用filter在每个请求中添加XSRF-TOKEN cookie。 So what you have to do is take the value of that cookie and store it in X-XSRF-TOKEN header. 因此,您要做的就是获取该Cookie的值并将其存储在X-XSRF-TOKEN标头中。 I've made a test project with similar security configuration to test out this case, the complete code looks like this: 我已经制作了一个具有类似安全性配置的测试项目来测试这种情况,完整的代码如下所示:

@RestController
@SpringBootApplication
public class TestApplication extends WebSecurityConfigurerAdapter {

    public static void main(String[] args) {
        SpringApplication.run(TestApplication.class, args);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
            .antMatchers("/**")  // Disable authentication for all requests.
            .permitAll()
            .and()
            .csrf().csrfTokenRepository(csrfTokenRepository())
            .and()
            .addFilterAfter(csrfHeaderFilter(), SessionManagementFilter.class); // Register csrf filter.
    }

    private Filter csrfHeaderFilter() {
        return new OncePerRequestFilter() {

            @Override
            protected void doFilterInternal(HttpServletRequest request,
                                            HttpServletResponse response,
                                            FilterChain filterChain) throws ServletException, IOException {

                CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
                if (csrf != null) {
                    Cookie cookie = WebUtils.getCookie(request, "XSRF-TOKEN");
                    String token = csrf.getToken();
                    if (cookie == null || token != null
                            && !token.equals(cookie.getValue())) {

                        // Token is being added to the XSRF-TOKEN cookie.
                        cookie = new Cookie("XSRF-TOKEN", token);
                        cookie.setPath("/");
                        response.addCookie(cookie);
                    }
                }
                filterChain.doFilter(request, response);
            }
        };
    }

    private CsrfTokenRepository csrfTokenRepository() {
        HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
        repository.setHeaderName("X-XSRF-TOKEN");
        return repository;
    }

    @RequestMapping(value = "/test", method = RequestMethod.GET)
    public String testGet() {
        return "hello";
    }

    @RequestMapping(value = "/test", method = RequestMethod.POST)
    public String testPost() {
        return "works!";
    }
}

To test this out with postman do the following: 要使用邮递员对此进行测试,请执行以下操作:

  • Enable interceptor to start capturing cookies. 启用拦截器以开始捕获cookie。
  • Perform a GET /test request and open the cookies tab. 执行GET /test请求并打开cookie选项卡。 There you should notice a cookie with a name XSRF-TOKEN . 在那里,您应该注意到一个名为XSRF-TOKEN的cookie。
  • Take the value of that cookie and put it in X-XSRF-TOKEN header and perform a POST /test request. 获取该cookie的值,并将其放在X-XSRF-TOKEN标头中,并执行POST /test请求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 symfony2 csrf令牌对ajax请求无效 - symfony2 csrf token invalid on ajax request Angular JS在POST请求中验证CSRF令牌 - Angular JS Verify CSRF Token in POST Request HTTP状态403 - 在请求参数上找到无效的CSRF令牌“null” - HTTP Status 403 - Invalid CSRF Token 'null' was found on the request parameter 如何使用Django和AngularJS创建POST请求(包括CSRF令牌) - How to create a POST request (including CSRF token) using Django and AngularJS AngularJS + Spring Security-如何在POST请求中设置CSRF令牌? - AngularJS + Spring Security - How do I set CSRF token in a POST request? 如何使用需要csrf令牌的angular.js和drywall(用户管理系统)创建发布请求? - How to create post request using angular.js and drywall (user management system) which needs csrf token? 找不到AngularJS HTTP POST预期的CSRF令牌 - AngularJS HTTP POST Expected CSRF token not found Laravel CSRF令牌与Ajax GET请求不匹配 - Laravel csrf token mismatch for ajax GET Request HTTP状态403 - 在请求参数'_csrf'或标题'X-CSRF-TOKEN'上找到无效的CSRF令牌'9ee6949c-c5dc-4d4b-9d55-46b75abc2994' - HTTP Status 403 - Invalid CSRF Token '9ee6949c-c5dc-4d4b-9d55-46b75abc2994' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN' 如何使用 _csrf 在 angularjs 中发送 POST 请求? - How send POST request in angularjs with _csrf?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM