1
Hello! Time to "pick up" the token on Httpinterceptor is coming as null.
follow code d Interceptor:
import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import { Observable } from 'rxjs';
import { AuthService } from '../Services/auth.service';
@Injectable()
export class TokenInterceptor implements HttpInterceptor {
intercept(request: HttpRequest<any>, newRequest: HttpHandler): Observable<HttpEvent<any>> {
// add authorization header to request
//Get Token data from local storage
let tokenInfo = JSON.parse(localStorage.getItem('TokenInfo'));
console.log(tokenInfo);
if (tokenInfo && tokenInfo.token) {
request = request.clone({
setHeaders: {
Authorization: `Bearer ${tokenInfo.token}`,
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
}
});
}
return newRequest.handle(request);
console.log(request);
}
}
Authservice:
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { BehaviorSubject, Observable, config } from 'rxjs';
import { map } from 'rxjs/operators';
import { messages } from 'app/pages/extra-components/chat/messages';
import { NbLogoutComponent } from 'app/auth';
import { AppConfig } from 'app/pages/shared/app.config';
import { headersToString } from 'selenium-webdriver/http';
@Injectable({ providedIn: 'root' })
export class AuthService {
private headers = new HttpHeaders();
constructor(private http: HttpClient, private config: AppConfig) {
}
login(login: User) {
return this.http.post<any>(`${this.config.apiUrl}/login/`, login, {headers: this.headers , responseType:'text' as 'json'})
.pipe(map(user => {
// armazenar detalhes do usuário e token JWT no armazenamento
//local para manter o usuário conectado entre as atualizações de página
localStorage.setItem('TokenInfo', JSON.stringify(user));
console.log(user);
return user;
}));
}
getToken(){
return localStorage.getItem('TokenInfo');
}
logout() {
localStorage.removeItem('TokenInfo')
}
}
export class User {
id: number;
email: string;
password: string;
token: string;
}
I don’t understand why the Interceptor isn’t picking up the token. Could you help me? API is in Asp.net core 2.1(Jwt Bearer)