【发布时间】:2018-11-03 18:41:38
【问题描述】:
我已经阅读了the docs 以及关于 SO 的所有相关问题,但 Angular 的 XSRF 机制仍然对我不起作用:我无法发出自动附加 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 {
}
然后,在 Service 的方法中,我发出以下 http 请求(this.http 是 HttpClient 的一个实例):
this.http
.post<any>('api/login', {'_username': username, '_pass': password})
.subscribe(/* handler here */);
发布请求从不发送 X-XSRF-TOKEN 标头。为什么?
【问题讨论】:
-
我猜你可以编写自己的拦截器来处理这个问题。我知道有些用户在not using absolute URLs 时遇到过这个问题
-
谢谢,我考虑过了,但我以更简洁的方式解决了问题:请看我的回答。
-
您好 Stefan,您能帮我在 Angular 版本 6 中以 PHP 作为后端生成 XSRF 令牌值吗?我无法 var_dump XSRF 令牌,因为我无法生成令牌在 typeScript Click Here 我已经发布了这个问题!
-
@Nishanthॐ 请看看你的问题,我已经用代码示例添加了答案。
标签: angular typescript angular6 csrf x-xsrf-token