Angular 6不会将X

编程入门 行业动态 更新时间:2024-10-12 01:29:35
本文介绍了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.http是HttpClient的实例):

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

本文发布于:2023-10-30 05:00:01,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1541835.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:会将   Angular

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!