claudem
claudem

Reputation: 93

How to intercept REQUEST correctly

I've set up an interceptor class to add jwt token to request headers but the requests are still without token.

I've set up the class and put a console.log before the call to request.clone to see if my token is really there. But it seems like it isn't passed to the request:

export class JwtInterceptor implements HttpInterceptor {
        constructor(private authenticationService: AuthenticationService) { }

        intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
                // add authorization header with jwt token if available
                let currentUser = this.authenticationService.currentUserValue;
                let currentToken = this.authenticationService.currentTokenValue;

                if (currentUser && currentToken) {
                    console.log(currentToken);

                    const cloned = request.clone({
                                setHeaders: {
                                        Authorization: `Bearer ${currentToken}`
                                }
                        });
                }

                return next.handle(request);
        }
}

console.log shows the token.

My service function:

export class UserService {
        constructor(private http: HttpClient) { }

        getAll() {
                return this.http.get<User[]>(`${environment.apiUrl}/users`);
        }
}

The request is made after success logging. I do a redirection to the home page and the ngInit call this method.

I expect to do the request with the token in the header but It's not passed through (sorry for my English).

Can someone help please?

Upvotes: 0

Views: 79

Answers (1)

Stavm
Stavm

Reputation: 8131

you create cloned and did nothing with it. return it.

intercept(request: HttpRequest<any>, next: HttpHandler) {
    // ... yada yada yada ...
      if ... {
        return request.clone({ setHeaders: { Authorization: `Bearer ${currentToken}` } });
      }
      return next.handle(request);   
}

Upvotes: 1

Related Questions