Angular 4 - 在每个请求中设置withCredentials - cors cookie

exi*_*onX 30 cookies http cors oauth-2.0 angular

我的角度客户端与后端分离,我在后端启用了cors,一切正常,但我的身份验证失败,因为cookie没有添加到请求中.

在线搜索后,我发现我应该设置{withCredentials : true}每个http请求.我设法在一个请求上执行它并且它可以工作,但不是在所有请求上.

我尝试使用BrowserXhr 如何在Angular2中的所有请求的请求标头中发送"Cookie"?但它不起作用,它也被弃用了.

我也尝试过RequestOptions但它没有用.

如何在每个http请求中设置{withCredentials:true}?

后来编辑:

@Injectable()
export class ConfigInterceptor implements HttpInterceptor {

  constructor(private csrfService: CSRFService) {

  }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    let token = this.csrfService.getCSRF() as string;
    const credentialsReq = req.clone({withCredentials : true, setHeaders: { "X-XSRF-TOKEN": token } });
    return next.handle(credentialsReq);
  }
}
Run Code Online (Sandbox Code Playgroud)

Ven*_*omy 37

你可以使用HttpInterceptor.

@Injectable()
export class CustomInterceptor 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)

接下来你必须提供它:

@NgModule({
  bootstrap: [AppComponent],
  imports: [...],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: CustomInterceptor ,
      multi: true
    }
  ]
})
export class AppModule {}
Run Code Online (Sandbox Code Playgroud)

来源和完整的解释

  • @Quentin道歉,我用代码示例更新了我的答案. (2认同)