Angular 4 - setting withCredentials on every request - cors cookie

28,448

You can use an 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);
    }
}

Next you have to provide it:

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

Source and full explanation

Share:
28,448
exilonX
Author by

exilonX

Updated on October 16, 2020

Comments

  • exilonX
    exilonX over 3 years

    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.

    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.

    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.

    I also tried RequestOptions but it didn't work.

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

    Later Edit:

    @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);
      }
    }
    
  • Quentin
    Quentin over 6 years
    Please avoid link only answers. Answers that are "barely more than a link to an external site” may be deleted.
  • Venomy
    Venomy over 6 years
    @Quentin Apologies, I updated my answer with code examples.
  • Thomas Wana
    Thomas Wana over 6 years
    Note that this only works if you're doing requests with @angular/common/http, not with @angular/http.
  • MGDavies
    MGDavies about 6 years
    This only appears to work for get requests, any advice on post and put?
  • Venomy
    Venomy about 6 years
    @MGDavies The HttpInterceptor is not limited to GET requests and should also work for POST and PUT.
  • Phil
    Phil almost 6 years
    @ThomasWana Do you know how I could add that functionality with @angular/http?