Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decode Jwt token React

Tags:

reactjs

jwt

I use jsonwebtoken to decode my Token to see if it has expired or not. But, the console.log return null.

 var token = response.headers.authorization;
 token = token.replace('Bearer','');
 var jwt = require('jsonwebtoken');
 var decoded = jwt.decode(token);
 console.log(decoded);

I'm don't understand because my token is not null

like image 798
dna Avatar asked Dec 18 '18 15:12

dna


2 Answers

It seems like you are using JWT. To decode this type of token you can simply use jwt-decode library. For example, in ReactJS:

import jwt from 'jwt-decode' // import dependency
...
// some logic
axios.post(`${axios.defaults.baseURL}/auth`, { email, password })
    .then(res => {
      const token = res.data.token;
      const user = jwt(token); // decode your token here
      localStorage.setItem('token', token);
      dispatch(actions.authSuccess(token, user));
    })
    .catch(err => {
      dispatch(actions.loginUserFail());
  });
like image 139
Serhii Onishchenko Avatar answered Sep 22 '22 17:09

Serhii Onishchenko


Assuming your header is something like Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c then after line 2 you have a leading space. See the below example for the difference the leading space makes. Trimming the leading space should resolve your issue.

var jwt = require("jsonwebtoken");

var token1 = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c";
var token2 = " eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c";

var decode1 = jwt.decode(token1);
var decode2 = jwt.decode(token2);

console.log("without leading space");
console.log(decode1);
// { sub: '1234567890', name: 'John Doe', iat: 1516239022 }

console.log("with leading space");
console.log(decode2);
// null
like image 41
Chris Avatar answered Sep 24 '22 17:09

Chris