Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to decode jwt with jwt-decode

I'm trying to decode my token with jwt-decode but I can't. It gives me the following error. Does anyone know why?

ERROR Error: Uncaught (in promise): TypeError: jwt_decode_1.default is not a function TypeError: jwt_decode_1.default is not a function at RoleGuardService.canActivate (role-guard.service.ts?d7c4:19)

import jwt_decode from 'jwt-decode';

canActivate(route: ActivatedRouteSnapshot): boolean {
        // this will be passed from the route config
        // on the data property
        const expectedRole = route.data.expectedRole;
        const token = localStorage.getItem('token');
        // decode the token to get its payload
        const tokenPayload = jwt_decode(token);
        console.log(tokenPayload);
        if (
            !this.auth.isAuthenticated() ||
            tokenPayload.role !== expectedRole
        ) {
            this.router.navigate(['login']);
            return false;
        }
        return true;
    }
like image 971
tilly Avatar asked Feb 13 '18 15:02

tilly


People also ask

How do I fix JWT error?

Resolution. Ensure that the variable referenced in the <Source> element of the Decode JWT policy is defined, contains a valid (decodable) JWT and is available in the specific flow where the Decode JWT policy is being executed.

Can any JWT be decoded?

By design, anyone can decode a JWT and read the contents of the header and payload sections. But we need access to the secret key used to create the signature to verify a token's integrity.

What does JWT failed mean?

This error occurs if the JSON Web Token (JWT) specified in the <Source> element of the Decode JWT policy is malformed, invalid or otherwise not decodable. A properly structured JWT should contain a header, payload and signature in the following format: header. payload.


1 Answers

I think you should import it like this:

import * as jwt_decode from 'jwt-decode';
like image 177
pioro90 Avatar answered Sep 21 '22 08:09

pioro90