JWT Role-Based Authorization react js

Viewed 33

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 ?

1 Answers

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.

Related