【问题标题】:Angular5 not setting X-XSRF-TOKEN headerAngular5 未设置 X-XSRF-TOKEN 标头
【发布时间】:2018-09-06 03:09:48
【问题描述】:

我已经阅读了许多解决方案,但没有一个对我有用。

这个 github 问题本质上是我的问题 (https://github.com/angular/angular/issues/20511)

我正在使用 Angular 5.2.5、Chrome 版本 65.0.3325.146、Spring boot 1.5.4。

在我的登录表单上,我首先发送 GET 请求以获取 XSRF cookie。然后我发送一个带有登录信息的帖子

Send GET request that returns Set-Cookie header

Send POST request and get 403

使用 CSRF 配置的 Spring Boot 应用

        http
            .csrf()
            .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());

我正在使用 Angular webpack 代理,因此 URL 是相对的,并使用 withCredentials 选项发送请求。

我也尝试按照 Github 问题中的建议编写自己的拦截器,但是在尝试获取令牌时我得到了 null let token = this.tokenExtractor.getToken() as string; 我在 Postman 中检查了 cookie 的 httpOnly 标志设置为 false

【问题讨论】:

    标签: angular cookies angular5 csrf-protection


    【解决方案1】:

    我遇到同样的问题已经有一段时间了。我刚刚用一点技巧修复了它

        // function to get cookie by name
        getCookie(cname) {
                var name = cname + "=";
                var decodedCookie = decodeURIComponent(document.cookie);
                var ca = decodedCookie.split(';');
                for (var i = 0; i < ca.length; i++) {
                    var c = ca[i];
                    while (c.charAt(0) == ' ') {
                        c = c.substring(1);
                    }
                    if (c.indexOf(name) == 0) {
                        return c.substring(name.length, c.length);
                    }
                }
                return "";
            }
    
    getItemsFromServer(){
    
        let httpOptions={
                    headers: new HttpHeaders({
                        'Content-Type': 'application/json',
                        'X-XSRF-TOKEN': this.getCookie("XSRF-TOKEN")
                    }),
                    withCredentials: true
                };
    
        this.httpClient.get(url, httpOptions)
        .subscribe(response=>{
        // more code here
        }
        );
    }
    

    【讨论】:

      猜你喜欢
      • 2021-02-17
      • 2020-03-30
      • 1970-01-01
      • 2013-08-22
      • 2023-03-30
      • 2017-05-14
      • 1970-01-01
      • 2015-09-13
      • 2019-06-01
      相关资源
      最近更新 更多