Angular 4 - 在每个请求中设置withCredentials - cors cookie [英] Angular 4 - setting withCredentials on every request - cors cookie

查看:4177
本文介绍了Angular 4 - 在每个请求中设置withCredentials - cors cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

My angular client is separated from the backend and I have enabled cors on the backend, everything works fine except the fact that my authentication fails because the cookie is not added to requests.

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

After searching online I found that I should set {withCredentials : true} on every http request. I managed to do it on a single request and it works, but not on all the requests.

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

I tried using BrowserXhr How to send "Cookie" in request header for all the requests in Angular2? but it doesn't work and it's also deprecated afaik.

我也尝试了RequestOptions但它没有用。

I also tried RequestOptions but it didn't work.

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

What can I do to set {withCredentials: true} on every http request?

稍后编辑:

@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);
  }
}


推荐答案

你可以使用 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);
    }
}

接下来你必须提供它:

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

来源和完整说明

这篇关于Angular 4 - 在每个请求中设置withCredentials - cors cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆