Angular 4 - setting withCredentials for every request - cors cookie

My angular client is separate from the backend, and I enabled cors on the backend, everything works fine, except that my authentication failed because the cookie was not added to the requests.

After searching the Internet, I found that I had to set {withCredentials : true} for each HTTP request. I managed to do this on one request, and it works, but not on all requests.

I tried using BrowserXhr. How to send a β€œCookie” in the request header for all requests in Angular2? but it does not work and it is also deprecated by afaik.

I also tried RequestOptions, but that did not work.

What can I do to set {withCredentials: true} for 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); } } 
+5
source share
1 answer

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

Then you must provide it:

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

-

Full explanation for:

https://medium.com/@ryanchenkie_40935/angular-authentication-using-the-http-client-and-http-interceptors-2f9d1540eb8

+9
source

Source: https://habr.com/ru/post/1273393/


All Articles