Search code examples
angularangular5angular-http-interceptors

Login not working after adding HTTP Interceptor - Angular 5


I have recently started working on a project someone else started, and I decided to implement HTTP Interceptor, but after I did it, I cannot log in anymore, like I am writing wrong username/pass (and I am not), but while I was logged in, everything worked fine. This is my code -

Interceptor:

@Injectable()
export class TokenInterceptor implements HttpInterceptor {
    constructor(public auth: AuthService) {}
    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        request = request.clone({
            setHeaders: {
                Authorization: `Bearer ${this.auth.getToken()}`
            }
        });
        return next.handle(request);
    }
}

Login:

// in http service
public postAuth(url: string,  body?: object): Observable<any> {
    return this.http.post(this.baseUrl + url, body)
    .pipe(
      catchError(error => new ErrorObservable(error))
    );
  }
// in auth service
login(email: string, password: string): void {
    const body = {username: email, password: password};

    this._http.postAuth('/auth/waplogin/', body)
    .map(res => {
      return {
        token: res.token,
        firstName: res.user.first_name,
        lastName: res.user.last_name,
        id: res.user.uuid
      }
    })
    .subscribe(
      loggedUserInfoToken => {
        sessionStorage.setItem('loggedUserInfoToken', JSON.stringify(loggedUserInfoToken));
        this.router.navigate(['/dashboard']);
      },
      err => {
        this.loginErr = err.statusText;
        this.checkError(this.loginErr);
      }
    );
  }

Not sure if it is linked, but this is when it stopped working, no errors in console though.

EDIT: Done it, just changed this part:

if (this.auth.isLoggedIn()) {
            request = request.clone({
                setHeaders: {
                    Authorization: `Token ${this.auth.getToken()}`
                }
            });
        }

didn't see this method existed in the code..


Solution

  • I believe this.auth.getToken() is fetching stored token from sessionStorage. If that is not the case then make sure that token is retrieved properly.

    Also, you can try ignoring the authentication request in the interceptor

    //Check for url. If it is login url then return    
    if (request.url.includes('/auth/waplogin/')) {
       return next.handle(request);
    }
    

    Updated Interceptor should be like this -

        @Injectable()
        export class TokenInterceptor implements HttpInterceptor {
            constructor(public auth: AuthService) {}
            intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    
                //Check for url. If it is login url then return    
                if (request.url.includes('/auth/waplogin/')) {
                   return next.handle(request);
                }
                request = request.clone({
                    setHeaders: {
                        Authorization: `Bearer ${this.auth.getToken()}`
                    }
                });
                return next.handle(request);
            }
        }