Angular 6 不会向 http 请求添加 X-XSRF-TOKEN 标头 [英] Angular 6 does not add X-XSRF-TOKEN header to http request
问题描述
我已阅读
我的 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.http
是 HttpClient
的一个实例):
this.http.post('api/login', {'_username': 用户名, '_pass': 密码}).subscribe(/* 处理程序在这里 */);
发布请求从不发送 X-XSRF-TOKEN 标头.为什么?
问题再次在于 Angular 的文档很差.
事实是,Angular 会添加X-XSRF-TOKEN
标头仅当 XSRF-TOKEN
cookie 是在服务器端生成的有以下选项:
- Path =
/
- httpOnly =
false
(这非常重要,并且完全未记录)
此外,Angular 应用程序和被调用的 URL 必须位于同一台服务器上.
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屋!