Angular 6 不会向 http 请求添加 X-XSRF-TOKEN 标头 [英] Angular 6 does not add X-XSRF-TOKEN header to http request

查看:30
本文介绍了Angular 6 不会向 http 请求添加 X-XSRF-TOKEN 标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已阅读

我的 app.module.ts 包含正确的模块:

//其他导入...从@angular/common/http"导入 {HttpClientModule, HttpClientXsrfModule};//...@NgModule({声明: [//...],进口:[NgbModule.forRoot(),浏览器模块,//...HttpClient 模块,HttpClientXsrfModule.withOptions({cookieName: 'XSRF-TOKEN',headerName: 'X-CSRF-TOKEN'}),//其他进口],提供者:[],entryComponents:[警告对话框],引导程序:[AppComponent]})导出类 AppModule {}

然后,在服务的方法中,我发出以下 http 请求(this.httpHttpClient 的一个实例):

this.http.post('api/login', {'_username': 用户名, '_pass': 密码}).subscribe(/* 处理程序在这里 */);

发布请求从不发送 X-XSRF-TOKEN 标头.为什么?

解决方案

问题再次在于 Angular 的文档很差.

事实是,Angular 会添加X-XSRF-TOKEN 标头仅当 XSRF-TOKEN cookie 是在服务器端生成的有以下选项:

  • Path = /
  • httpOnly = false(这非常重要,并且完全未记录)

此外,Angular 应用程序和被调用的 URL 必须位于同一台服务器上.

参考:这个 Angular Github 问题

I've read the docs and all the related questions on SO, but still Angular's XSRF mechanism isn't working for me: in no way I can make a POST request with the X-XSRF-TOKEN header appended automatically.

I have an Angular 6 app with a login form.

It's part of a Symfony (PHP 7.1) website, and the Angular app page, when served from Symfony, sends the correct Cookie (XSRF-TOKEN):

My app.module.ts includes the right modules:

// other imports...
import {HttpClientModule, HttpClientXsrfModule} from "@angular/common/http";

// ...
@NgModule({
  declarations: [
    // ...
  ],
  imports: [
    NgbModule.forRoot(),
    BrowserModule,
    // ...
    HttpClientModule,
    HttpClientXsrfModule.withOptions({
      cookieName: 'XSRF-TOKEN',
      headerName: 'X-CSRF-TOKEN'
    }),
    // other imports
  ],
  providers: [],
  entryComponents: [WarningDialog],
  bootstrap: [AppComponent]
})
export class AppModule {
}

Then, inside a Service's method, I'm making the following http request (this.http is an instance of HttpClient):

this.http
    .post<any>('api/login', {'_username': username, '_pass': password})
    .subscribe(/* handler here */);

The post request never sends the X-XSRF-TOKEN header. Why?

解决方案

The problem once again is Angular's poor documentation.

The fact is, Angular will add the X-XSRF-TOKEN header only if the XSRF-TOKEN cookie was generated server-side with the following options:

  • Path = /
  • httpOnly = false (this is very important, and fully undocumented)

Besides, the Angular app and the URL being called must reside on the same server.

Reference: this Angular Github issue

这篇关于Angular 6 不会向 http 请求添加 X-XSRF-TOKEN 标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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