2
votes

I'm working on an angular 6 app where I want to add an jwt-token to the authorize-header of every request. For this scenario I want to use an interceptor.

The code looks like this:

import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { Observable } from "rxjs";

@Injectable()
export class AuthInterceptor implements HttpInterceptor {

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    let sessionId = localStorage.getItem('sessionId');
    if (sessionId) {
      request = request.clone({
        setHeaders: {
          Authorization: `Bearer ${sessionId}`
        }
      });

      console.log("With AuthHeader");
    }

    return next.handle(request);
  }
}

Here is my code for sending the request:

  httpQuery(ressource): Observable<T[]> {
    var absoluteUrl = this.getAbsoluteUrl(ressource);
    console.log("Sending");
    return this.httpClient
      .get<T[]>(absoluteUrl);
  }

However I face the following problem: The interceptor gets fired, but AFTER the request is sent. I can see this in developer console where the log-message from the http-method comes right before the log-message from the interceptor: enter image description here

As you can see, this leeds to a 401 response from the server which expects the authorization-header.

I read a ton of tutorials and stackoverflow-questions about interceptor, but I can't see my mistake.

Maybe some of guys have a hint for me?

Thank you and best regards, Alex

3
Please check your network tab for the request where the Authorization header is added or not. - Sheik Althaf
I did and it is not sent (with different browsers). Interesting side note: fiddler doesn't notice this particular request at all. Every request I make is captured by fiddler, but this one request which results in a 401-response not. Only Wireshark captures this request and the response. And in Wireshark there is no authorization-header as well. - Alex
I have the same issue did you figure this out? - aycanadal
Yes it's working for a while. Thing is, I have no idea what I changed to make it work. The actual code looks very similar to what I posted. Here are some suggestions: make sure, that there is no asynchronous task to fetch the token or something, which finishes when the request is already sent. Second approach, play around with cloning the request object. In newer angular versions the headers-collection is immutable which is tricky to handle. log your request object to the console to make sure that the header is set. - Alex

3 Answers

0
votes

What you are showing is just fine

console.log("Sending"); //here you print to the cosole
return this.httpClient // here you actually MAKE http call.
  .get<T[]>(absoluteUrl);

So your interceptor is called DURING request execution and BEFORE actual XHR request is made.

0
votes

Please try like this one

const headers = request.headers.append('Authorization', `Bearer ${sessionId}`);
const d = request.clone({ headers: headers });

return next.handle(request);
0
votes

I had the same issue.

The interceptor was added to the providers of the CoreModule. When I added it to the providers of the FeatureModule that did the call, it worked as expected.

This is not very convenient of course but works for me at this point because I only have one FeatureModule :)