3

I have an authentication interceptor, however, I want this interceptor to filter requests and not be applied when users access components like confirm account password etc which do not need user authentication. Any example on how to go about it? Here is the logic for auth interceptor:

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    // Get the auth token from the service.
    let authToken = this.authService.getToken();
    let authHeader = 'Bearer ' + authToken;

    //For requests that are retried, we always want a fresh copy, else the request will have headers added multiple times.
    //So Clone the request before adding the new header. 
    //NOTE: the cache and pragma are required for IE that will otherwise cache all get 200 requests.
    const authReq = request.clone({
      setHeaders: {
        Authorization: authHeader,
        'Cache-Control': 'no-cache',
        'Pragma': 'no-cache'
      }
    });
    // Pass on the cloned request instead of the original request.
    return next.handle(authReq);
}
miiiii
  • 1,580
  • 1
  • 16
  • 29
smons
  • 65
  • 1
  • 6

1 Answers1

3

For this case, the URL of your request is helpful.

Assume, your authentication urls are like auth/login or auth/refreshToken, and your resource api urls be like, api/users, api/users/123, api/addUser, then you can put a if condition to check what the request is for.

Example of url matching:-

 if (request.url.match(/api\//)) { // api call
    console.log('api call detected.');
    let authToken = this.authService.getToken();
    let authHeader = 'Bearer ' + authToken;
    const authReq = request.clone({
    setHeaders: {
       Authorization: authHeader,
       'Cache-Control': 'no-cache',
       'Pragma': 'no-cache'
     }
    });
    return next.handle(authReq);
 }
 else{ // auth call - you can put esle if conditions if you have more such pattern
 console.log('auth call detected.');
    return next.handle(request);
 }     

Now authentication headers will only be added to your api-call (I meant the resource api-call), and other calls will not modified.

NB: I've been in backend technology like Java, DBs, etc.. for longer time and now learning angular for the first time, so answered like a mod :P, but the idea was from my last Java project. Hope it helps..!! :)

miiiii
  • 1,580
  • 1
  • 16
  • 29