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

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

问题描述

我已阅读文档以及关于SO的所有相关问题,但是Angular的XSRF机制仍然对我不起作用:我无法通过自动附加X-XSRF-TOKEN标头来发出POST请求.

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.

我有一个带有登录表单的Angular 6应用.

I have an Angular 6 app with a login form.

它是Symfony(PHP 7.1)网站的一部分,当从Symfony提供服务时,Angular应用程序页面将发送正确的Cookie(XSRF-TOKEN):

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):

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

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 {
}

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

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 */);

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

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

推荐答案

问题再次是Angular的文档不佳.

The problem once again is Angular's poor documentation.

事实是,只有在服务器端使用以下选项生成XSRF-TOKEN cookie时,Angular才会添加X-XSRF-TOKEN标头:

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:

  • 路径= /
  • httpOnly = false(这非常重要,并且完全未记录)
  • Path = /
  • httpOnly = false (this is very important, and fully undocumented)

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

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

参考:此Angular Github问题

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

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