Angular 6 不向 http 请求添加 X-XSRF-TOKEN 标头

2024-04-15

我读了the docs https://angular.io/guide/http#security-xsrf-protection以及有关 SO 的所有相关问题,但 Angular CSRF 机制仍然对我不起作用:我无论如何都无法发出自动附加 X-XSRF-TOKEN 标头的 POST 请求。

我有一个带有登录表单的 Angular 6 应用程序。

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

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

// 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.http是一个实例HttpClient):

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

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


问题再次出在 Angular 糟糕的文档上。

事实上,Angular 会添加X-XSRF-TOKEN header only if the XSRF-TOKENcookie 是在服务器端生成的,具有以下选项:

  • Path = /
  • 仅http =false(这一点非常重要,并且充分无证的)

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

Refer 这个 Angular Github 问题 https://github.com/angular/angular/issues/20511

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Angular 6 不向 http 请求添加 X-XSRF-TOKEN 标头 的相关文章

随机推荐