Home > Blockchain >  Angular Interceptor returning 401 after Jwt token provided in header
Angular Interceptor returning 401 after Jwt token provided in header

Time:12-08

I'm working at Authorization with NestJS Angular. And I have a guard protecting the user. User information will only be visible when JWT is provided with headers. User logs In and JWT is generated,the Jwt is provided in the Authorization sectios as Bearer Token,and after that with a Get request user can see his details.This is working with Postman but not with Angular. At Angular side when user logs In the token is stored in localstorage.

Error

> user.service.ts:20 ERROR Error: Uncaught (in promise):
> HttpErrorResponse:
> {"headers":{"normalizedNames":{},"lazyUpdate":null},"status":401,"statusText":"Unauthorized","url":"http://localhost:3000/users/byId/63891e7e893aa91d5783fa69","ok":false,"name":"HttpErrorResponse","message":"Http
> failure response for
> http://localhost:3000/users/byId/63891e7e893aa91d5783fa69: 401
> Unauthorized","error":{"statusCode":401,"message":"Unauthorized"}}
>     at resolvePromise (zone.js:1211:31)
>     at zone.js:1118:17
>     at zone.js:1134:33
>     at asyncGeneratorStep (asyncToGenerator.js:6:1)
>     at _throw (asyncToGenerator.js:29:1)
>     at _ZoneDelegate.invoke (zone.js:372:26)
>     at Object.onInvoke (core.mjs:26231:33)
>     at _ZoneDelegate.invoke (zone.js:371:52)
>     at Zone.run (zone.js:134:43)
>     at zone.js:1275:36

Interceptor

intercept(
    req: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    let service = this.inject.get(AuthService);

    const token = localStorage.getItem('accesstoken');

    if (token) {
      console.log('Before', token);

      const authRequest = this.addTokenHeader(req, token);

      console.log('After', authRequest);

      return next.handle(authRequest).pipe(
        catchError((error: HttpErrorResponse) => {
          if (error.status === 401) {
            alert('401 Unathurized');
            this.route.navigate(['authentication/login']);
          }
          return throwError(error);
        })
      );
    } else {
      return next.handle(req);
    }
  }

addTokenHeader function in Interceptor

addTokenHeader(request: HttpRequest<any>, token: string | null) {
    return request.clone({
      headers: request.headers.set('Authorization', 'Bearer'   token!),
    });
  }

**To get User Details. I'm sending the id here ,that is stored in JWT after User Logs in **

 public async getUser(id: string): Promise<UserDto> {

    let res = this.http.get<UserDto>(`${this.url}/users/byId/${id}`);

    let data = await lastValueFrom(res);

    return data;
  }

Below you can see that token in local storage and sent with headers are the same

enter image description here

CodePudding user response:

The first thing I would try is to put a space between the string Bearer and the token itself:

request.headers.set('Authorization', 'Bearer '   token!)

Maybe the server is understanding that Bearer is part of the token the way you are sending

  • Related