'Token undefined in interceptor
I have been having a problem with using JWT for authenticating users and allowing access to certain areas of a site I'm working on.
Confirming the user exists in the database works fine and I can create tokens on the backend with no problems but when I try to use the token in my interceptor it doesn't work. This is my login function.
getToken() {
// get token returns undefined
return this.token;
}
userLogin(email: string, password: string) {
const authData: AuthData = { email: email, password: password };
this.http.post<{ token: string }>('http://localhost:3000/api/auth/login', authData).subscribe((response) => {
const token = response.token;
this.token = token;
});
The token is declared as a private variable which is why I have the gettoken function which I use in the intercepter below.
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { UserAuthService } from './auth.service';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(private authService: UserAuthService) {}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
console.log('auth-interceptor.ts intercept() Token = ', this.authService.getToken());
const authToken = this.authService.getToken();
const authRequest = req.clone({
headers: req.headers.set('Authorization', authToken)
});
return next.handle(authRequest);
}
}
any help with this would be greatly appreciated, thanks.
Solution 1:[1]
You need to provide your interceptor in your module:
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: MyInterceptor, multi: true }
]
Solution 2:[2]
As mentioned in a comment, you should make sure to have @Injectable({providedIn: 'root'}) in your service otherwise the Service might not be a Singleton and you will have multiple instances of the class. This could explain why the token is missing.
also a trick to see what is happening, change the code like this:
private _token: string;
get token(): string {
console.log('getting token: ', this._token);
return this._token;
}
set token(token: string) {
console.log('setting token: ', token);
this._token = token;
}
you can then simply do this.token = token; and const authToken = this.authService.token; and you should see the logs.
also add a console.log() in the service constructor in order so see if you have multiple instances of the same service.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Pieterjan |
| Solution 2 | Zerotwelve |
