如何在Angular2中的所有请求的请求标头中发送"Cookie"?

ad3*_*ad3 41 angular

实际上,我们的后端使用请求标头中的Cookie对请求进行身份验证.我知道如果我设置标题"Cookie",它将拒绝.那么,有没有办法将Cookie发送到后端?

Thi*_*ier 67

我想有一个阶段,你要求服务器验证你.在此之后(如果验证成功),服务器将在响应中返回cookie.浏览器将存储此cookie并为每次调用再次发送它.

也就是说,在跨域请求(CORS)的情况下,您需要将withCredentialsXHR设置true为使浏览器在您的请求中添加cookie.

要使用Angular2启用此功能,我们需要按BrowserXhr如下所述扩展类:

@Injectable()
export class CustomBrowserXhr extends BrowserXhr {
  constructor() {}
  build(): any {
    let xhr = super.build();
    xhr.withCredentials = true;
    return <any>(xhr);
  }
}
Run Code Online (Sandbox Code Playgroud)

BrowserXhr使用扩展覆盖提供者:

bootstrap(AppComponent, [
  HTTP_PROVIDERS,
  provide(BrowserXhr, { useClass: CustomBrowserXhr })
]);
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参阅此问题:

编辑(跟随凶手的评论)

从RC2,您可以withCredentials直接在请求配置中使用该属性,如下所述:

this.http.get('http://...', { withCredentials: true })
Run Code Online (Sandbox Code Playgroud)

编辑(在[maxou]评论之后)

请记住在每个请求中包含withCredentials:true .

  • 此功能现已添加到angular2.您现在可以简单地执行类似`http.get(url,{withCredentials:true})的操作,因此不再需要这种方便的解决方法(从2.0.0-rc4或更早版本开始). (19认同)
  • 在我看来,通过使用`withCredentials`,响应中的`Set-Cookie`将由客户端设置,但客户端仍然不在请求中发送`Cookie`(使用先前的请求设置) (5认同)
  • 这个@maxou有运气吗? (3认同)
  • @Kian在所有请求中使用`withCredentials` (3认同)
  • 你是对的.我加入了RC2.我相应地更新了答案.非常感谢你指出这一点;-) (2认同)

Jav*_*Net 17

在Angular5中你可以写一个Http拦截器:

auth.interceptor.ts

import { Observable } from 'rxjs/Observable';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Injectable } from '@angular/core';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  constructor() {}

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    request = request.clone({
      withCredentials: true
  });
  return next.handle(request);
  }
}
Run Code Online (Sandbox Code Playgroud)

并添加到app.module的providers数组中

app.module.ts

import { AuthInterceptor } from './services/auth.interceptor';
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { HttpClientModule } from '@angular/common/http';
imports: [
    BrowserModule,HttpClientModule,FormsModule
  ],

providers: [
    {
    provide: HTTP_INTERCEPTORS,
    useClass: AuthInterceptor,
    multi: true,
    }
]
Run Code Online (Sandbox Code Playgroud)

  • 使用 Flask 后端,我必须将以下 CORS 标头添加到响应中才能使其正常工作: `response.headers['Access-Control-Allow-Credentials'] = 'true'` (2认同)
  • 对于 .NET Core/.NET 5 后端,我必须将 `.AllowCredentials()` 添加到 Startup.cs 中的 CORS 配置中。该拦截器也适用于 Angular 11。我只需要将 Observable 导入更改为 `import { Observable } from 'rxjs';` (2认同)