0

Is it possible to validate the JWT token in a reactjs frontend application or does it require server side node/other framework to validate the signature?

From what I understand the JWT token has a signature portion that has to be validated against a secret key. So for this to happen security you require this part of the validation to be perform on the server side/backend.

Is this correct?

Blankman
  • 259,732
  • 324
  • 769
  • 1,199
  • Good practice treats the frontend as a hostile environment. I believe you *can* do this, but more than likely you'll be exposing some sort of key, creating a vulnerability. It's a bit out to date to current development, but feel free to reference https://github.com/RUJodan/Dockerized-Full-Stack my repo here and how I implement JWT signing – Sterling Archer Feb 15 '23 at 16:14
  • ** it require server side node/other framework to validate the signature** – Abbas Bagheri Feb 15 '23 at 16:34

1 Answers1

1

You can decode the JWT's payload on the frontend without the key, but you'll need the key to validate the token (meaning verify it was generated using the given key).

Exposing the key to the frontend makes JWT useless because anyone can generate tokens with any payload value, signed with your key. Therefore, any validation of the token should be done on the server side with the protected key.

Example frontend decode. Credit to @Peheje:

function parseJwt (token) {
    var base64Url = token.split('.')[1];
    var base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
    var jsonPayload = decodeURIComponent(window.atob(base64).split('').map(function(c) {
        return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
    }).join(''));

    return JSON.parse(jsonPayload);
}
MrCode
  • 63,975
  • 10
  • 90
  • 112