5
respostas

Invalid Token Error / jwt-decode

Na Console:

AppComponent.html:1 ERROR InvalidTokenError {message: "Invalid token specified: Cannot read property 'replace' of undefined", ngDebugContext: DebugContext_, ngErrorLogger: ƒ}

AppComponent.html:1 ERROR CONTEXT DebugContext_ {view: {…}, nodeIndex: 1, nodeDef: {…}, elDef: {…}, elView: {…}}

No terminal:

ERROR in src/app/core/user/user.service.ts(27,22): error TS2304: Cannot find name 'jwtDecode'.

No código:

....
import * as jwtDecode from 'jwt-decode';
....
private decodeAndNotify(){
        const token = this.tokenService.getToken();
        const user = jwtDecode(token) as User;
        this.userSubject.next(user);
    }

Acredito que o erro esteja relacionado com a versão do jwt-decode que não é compatível com a versão do typescript. Porém eu já tentei fazer vários testes aqui para saber do que se trata, e ta complicado. Gostaria de saber o que vocês me recomendariam.

Fazer outro caminho alternativo para realizar a autenticação do token no código ou instalar alguma dependência no terminal para me dar suporte no trabalho?

5 respostas

Fala ai Arthur, tudo bem? Vamos lá:

AppComponent.html:1 ERROR InvalidTokenError {message: "Invalid token specified: Cannot read property 'replace' of undefined", ngDebugContext: DebugContext_, ngErrorLogger: ƒ}

AppComponent.html:1 ERROR CONTEXT DebugContext_ {view: {…}, nodeIndex: 1, nodeDef: {…}, elDef: {…}, elView: {…}}

Esse erro parece ser porque você tentou fazer replace de algo undefined em algum momento, talvez não possua o token (estou chutando).

ERROR in src/app/core/user/user.service.ts(27,22): error TS2304: Cannot find name 'jwtDecode'.

Olhando o seu código, parece ser ok o import da utilização do jwt-decode.

Você adicionou a verificação do hasToken antes de chamar a função decodeAndNotify

Consegue compartilhar o projeto? Assim eu consigo ver com mais calma e detalhes por aqui.

Pode compartilhar através do Github ou Google Drive (zipado).

Fico no aguardo.

Eu quero mandar google drive zipado, por onde te mando?

user.service.ts

import { Injectable } from '@angular/core';
import { TokenService } from '../token/token.service';
import { BehaviorSubject } from 'rxjs';
import { User } from './user';
import * as jwtDecode from 'jwt-decode';

@Injectable({providedIn:'root'})
export class UserService{

    private userSubject = new BehaviorSubject<User>(null);

    constructor(private tokenService: TokenService){ 
        this.tokenService.hasToken() && 
            this.decodeAndNotify(); 
    }

    setToken(token: string){
        this.tokenService.setToken(token);
        this.decodeAndNotify();
    }
    getUser(){
        return this.userSubject.asObservable();
    }

     private decodeAndNotify(){
        const token = this.tokenService.getToken();
        const user = jwtDecode(token) as User;
        this.userSubject.next(user);
    } 
    logout(){
        this.tokenService.removeToken();
        this.userSubject.next(null);
    } 
}

token.service.ts

import { Injectable } from '@angular/core';

const KEY = 'authToken';

@Injectable({ providedIn: 'root' })
export class TokenService {

    hasToken() {
        return !!this.getToken();
    }

    setToken(token) {
        window.localStorage.setItem(KEY, token);
    }

    getToken() {
        return window.localStorage.getItem(KEY);
    }

    removeToken() {
        window.localStorage.removeItem(KEY);
    }
}

Segue o link da pasta zipada: https://drive.google.com/drive/folders/1rDNj6AV295yRBw7udtHT8WYH27SuqhpI

estou com um problema parecido com o do Arthur. Quando comento a linha que utiliza o jwt_decode a aplicação volta a funcionar. Segue erro

ERROR Object { message: "Invalid token specified", ngDebugContext: {…}, ngErrorLogger: (), stack: "./nodemodules/jwt-decode/lib/index.js@http://localhost:4200/vendor.js:67379:31\n__webpackrequire@http://localhost:4200/runtime.js:77:30\n./src/app/core/user/user.service.ts@http://localhost:4200/main.js:490:68\nwebpackrequire@http://localhost:4200/runtime.js:77:30\n./src/app/core/auth/auth.service.ts@http://localhost:4200/main.js:284:76\nwebpackrequire@http://localhost:4200/runtime.js:77:30\n./src/app/home/signin/signin.component.ts@http://localhost:4200/main.js:723:88\nwebpackrequire@http://localhost:4200/runtime.js:77:30\n./src/app/app.routing.module.ts@http://localhost:4200/main.js:193:87\nwebpackrequire@http://localhost:4200/runtime.js:77:30\n./src/app/app.module.ts@http://localhost:4200/main.js:132:77\nwebpackrequire@http://localhost:4200/runtime.js:77:30\n./src/main.ts@http://localhost:4200/main.js:1865:73\nwebpackrequire@http://localhost:4200/runtime.js:77:30\n0@http://localhost:4200/main.js:1888:18\nwebpackrequire__@http://localhost:4200/runtime.js:77:30\ncheckDeferredModules@http://localhost:4200/runtime.js:44:23\nwebpackJsonpCallback@http://localhost:4200/runtime.js:31:19\n@http://localhost:4200/main.js:1:57\n" } AppComponent.html:1 ViewAppComponent_0 AppComponent.html:1 Angular 18

Fala ai Arthur, tudo bem? Não possuo acesso para acessar a pasta e posteriormente realizar o download do zip.

Fiz a solicitação do mesmo, consegue aprovar?

Fico no aguardo.

Quer mergulhar em tecnologia e aprendizagem?

Receba a newsletter que o nosso CEO escreve pessoalmente, com insights do mercado de trabalho, ciência e desenvolvimento de software