0

I am storing JWT in localStorage , lets say my JWT is

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoiVVNFUiIsImlhdCI6MTY2MjU1NzE3Mn0.lRbHWxk8kSnTH8Okdko3cK8Nkce-0sNSeTNjQa1m33o

payload is like this

{
  "role": "USER",
  "iat": 1662557172
}

in my FrontEnd i have a protected route that decodes the JWT then tests the role like this

 if (jwt_decode(auth.user).role!=="ADMIN") {
        return <Navigate to="/home" />
    }
    return children

my problem is , if the user creates a new token manually and puts the role as "ADMIN" .

he won't be able to execute any API i know that since the token he created is invalid , but he will be able to enter the ADMIN routes .

is there a way to prevent this ?

  • You can decode the JWT with a proper JWT library to make sure it's actually valid. But stopping a malicious user from hacking the client is probably never 100% possible. You should rely on the fact that the client can't access any sensetive information without talking to the backend. Which requires a valid token. – super Sep 07 '22 at 14:55
  • validating token in frontend is not recommended . since it requires the private key . the best solution i found was to send an api to the backend verifying the token validity before taking the role from it , or just sending the token and the backend returns the role of that token . but i want as low possible requests to the backend – Wael Ben Mustapha Sep 07 '22 at 14:58
  • Not if you use a public/private key pair. Which I would recommend. Then you can freely distribute the public key and allow clients to validate tokens without being able to create new ones. – super Sep 07 '22 at 17:27

1 Answers1

0

Once your application receives the JWT from whatever identity provider you're using (e.g. Azure AD), you should validate the issuer. This ensures that a user cannot generate their own JWT, it could only come from the issuer that you trust.

How to validate jwt token from different issuer

You should then take the JWT stored in local storage, and invoke an API you write to inspect it, and return a well structured response that can indicate to your application the permissions of the user. This API should definitely validate the issuer too.

Something you can do to make your JWTs even more secure is, once you receive the JWT from the identity provider, generate your own JWTs and encrypt it. This'll ensure that the user can't decrypt them since they won't have your private key.