【问题标题】:How to provide the CSRF Token in single page application (spring security)?如何在单页应用(spring security)中提供 CSRF Token?
【发布时间】:2015-03-05 15:10:00
【问题描述】:

当我尝试使用 ajax 加载页面的一部分时,出现 403 错误

在请求参数“_csrf”或标头“X-CSRF-TOKEN”上发现无效的 CSRF 令牌“null”。

Spring Security 常见问题解答告诉我们

如果 HTTP POST 返回 HTTP 403 Forbidden,但适用于 HTTP GET 那么问题很可能与 CSRF 有关。要么提供 CSRF Token 或禁用 CSRF 保护(不推荐)。

那么,a 怎么做呢?

function getPage(url) {
    $.ajax({
        type: 'POST',
        url: url,
        data: {_csrf: "??"},
        success: function (data) {
            loadPage(url, data);
        }
    });
}

【问题讨论】:

    标签: spring spring-security csrf single-page-application


    【解决方案1】:

    在这里找到了我自己的问题的答案: http://spring.io/blog/2013/08/21/spring-security-3-2-0-rc1-highlights-csrf-protection/

    这个 - 到 html

    <meta name="_csrf" content="${_csrf.token}"/>
    <meta name="_csrf_header" content="${_csrf.headerName}"/>
    

    this - to js

    $(function () {
        var token = $("meta[name='_csrf']").attr("content");
        var header = $("meta[name='_csrf_header']").attr("content");
        $(document).ajaxSend(function(e, xhr, options) {
            xhr.setRequestHeader(header, token);
        });
    });
    

    【讨论】:

    • 我有一个场景,我不通过 Spring 提供单页应用程序。它由另一个 Web 服务器提供服务,它需要对我的 API 执行请求。
    【解决方案2】:

    您可以从存储在您客户端的 cookie 中获取令牌。为此,您必须使用类似 cookie-service 的东西: https://www.npmjs.com/package/angular2-cookie

    编写这样的函数来获取令牌:

    getCookie(){
        return this._cookieService.get("token-name");
    }
    

    最后将令牌添加到请求头中:

    doSomething(token){
        var json = JSON.stringify({});
        var headers = new Headers();
        headers.append('Content-Type','application/json');
         headers.append('token-name', token);
        return this._http.post('http://localhost:8080/doSomething', json, {
            headers: headers
        }).map(res => res.text()
        );
    }
    

    这解决了我的问题

    【讨论】:

      猜你喜欢
      • 2018-10-14
      • 2017-01-07
      • 1970-01-01
      • 2015-02-11
      • 2020-03-25
      • 2016-08-13
      • 2014-02-07
      • 2020-07-17
      • 2018-07-21
      相关资源
      最近更新 更多