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

时间:2017-11-15 10:25:32

标签: angular http cookies oauth-2.0 cors

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

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

我尝试使用BrowserXhr How to send "Cookie" in request header for all the requests in Angular2?,但它不起作用,它也被弃用了afaik。

我也尝试了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);
  }
}

2 个答案:

答案 0 :(得分:36)

您可以使用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 {}

Source and full explanation

答案 1 :(得分:2)

另一种可能更简单的方法是创建自己的 ApiService 。它将使用注入的HttpClient。所有XHR请求都将直接使用ApiService而不是HttpClient。

这是一个示例实现:

https://github.com/gothinkster/angular-realworld-example-app/blob/63f5cd879b5e1519abfb8307727c37ff7b890d92/src/app/core/services/api.service.ts

我修改过的一些代码:

@Injectable()
export class ApiService {

  private httpOptions = {
    headers: new HttpHeaders({ 'Content-Type': 'application/json' }),
    withCredentials: true // to allow cookies to go from "https://localhost:4567" to "http://localhost:5678"
  };

  constructor(
    private http: HttpClient
  ) { }

  private formatErrors(error: any) {
    return throwError(error.error);
  }

  get(path: string, params: HttpParams = new HttpParams()): Observable<any> {
    return this.http.get(`${environment.api_url}${path}`, { params })
      .pipe(catchError(this.formatErrors));
  }

  put(path: string, body: Object = {}): Observable<any> {
    return this.http.put(
      `${environment.api_url}${path}`,
      JSON.stringify(body),
      this.httpOptions
    ).pipe(catchError(this.formatErrors));
  }

  post(path: string, body: Object = {}): Observable<any> {
    return this.http.post(
      `${environment.api_url}${path}`,
      JSON.stringify(body),
      this.httpOptions
    ).pipe(catchError(this.formatErrors));
  }