Httpinterceptor null token (Angular 7)

Asked

Viewed 294 times

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;
}

inserir a descrição da imagem aqui

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)

2 answers

2

You need to change the content-type of the Interceptor as follows:

'Content-Type': 'application/json'

0

Refresh the chunk that adds the token in the header

Try Bearer ${tokenInfo} instead of Bearer ${tokenInfo.token}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.