Rahul
Rahul

Reputation: 21

How to validate & verify JWT token payload in golang

I am trying to validate my json token but i am not able to do that,

Here is my sample token

Header:
{
  "alg": "HS256",
  "typ": "JWT"
}

Payloads:

{
  "admin": false,
  "School_ID": 123,
  "name": "XXXXXX",
  "sub": "XXXXXXXX"
}

Singature: Key

My problem is as soon as i am trying to manipulate JSON web token and change the value of admin 'false' to 'true', it is bypassing my API and becoming as an admin user from the normal user, to prevent that i tried using

token, err: = new(jwt.Parser).ParseWithClaims(tokenString, newClaims(), func( * jwt.Token)(interface {}, error) {
    return tokenString, nil
})

but problem still there can anyone help me how to fix that issue as its critical security bug and i need to fix it.

Upvotes: 1

Views: 2315

Answers (2)

Jack Yu
Jack Yu

Reputation: 2425

First thing, JWT prevents the users from changing the payload because the users couldn't have key to regenerate the JWT token. If you change admin from false to true in the payload, do you regenerate the signature?

For example, you could paste the following text in jtw.io eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c. You'll see valid signature verified.

But, if you change only payload, you'll get invalid signature, like this, eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRHd3d29lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c. You also could copy it to try in jtw.io.

So when you change payload without regenerating the JWT token, you'll get invalid JWT token. When your JWT token is modified (admin: false to true) by users who don't know your key, the users basically could not get the admin permission.

Last, signature in JWT is not the key, it's just a signature to approve this JWT token is signed by your key.

Upvotes: 1

Michal Trojanowski
Michal Trojanowski

Reputation: 12322

It doesn't look like you're verifying the signature anywhere. You're parsing the token payload, but you don't verify the signature. When you're reading a JWT you have to verify the signature in order to check whether someone has changed the contents of the token. So to prevent exactly what you have done in your example. When you change admin claim to true then the signature will no longer match the payload and you will be able to reject such a token.

Upvotes: 0

Related Questions