Angular 6 set withCredentials to true with every HttpClient call

Freddy Bonda picture Freddy Bonda · Oct 16, 2018 · Viewed 16k times · Source

If you want the credentials (cookie authentication token) to be passable through a call, you need to add { withCredentials: true } in your httpclient call. Something like this:

import { HttpClient  } from '@angular/common/http';
...
constructor(private httpclient: HttpClient) { }

this.httpclient.get(url, { withCredentials: true })

I would just like to know if there is a way to preset { withCredentials: true } with every single call. I don't want to have to add { withCredentials: true } every time I make a call.

Here is a related question, but I am not sure if this works with HttpClient?

Answer

Sachila Ranawaka picture Sachila Ranawaka · Oct 16, 2018

Create a HttpInterceptor:

@Injectable()
export class CustomInterceptor implements HttpInterceptor { 
    
    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 {}