Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate a JWT token in Golang

Tags:

go

jwt

jwt-go

I want to check if a JWT is generated from our server or not?

I use JWT to authenticate and use RS256 as ALGORITHM for our JWT

For now, I want to write a function in Golang to validate a JWT token is ours or not. Below is code i have implement:

    publicKey = "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAxxxxxxf2iF+20xHTZ4jTUBzYmikBuUsm0839T5SDmwEquTB\nfQIDAQAB\n-----END PUBLIC KEY-----\n"


    // sample token string taken from the New example
    tokenString := this.JWT[0]

    claims := jwt.MapClaims{}
    token, err := jwt.ParseWithClaims(tokenString, &claims, func(token *jwt.Token) (interface{}, error) {
        return []byte(publicKey), nil
    })

    // ... error handling
    if err != nil {
        fmt.Println(err)
    }

    fmt.Println("TOKEN is:", token.Valid)

    // do something with decoded claims
    for key, val := range claims {
        fmt.Printf("Key: %v, value: %v\n", key, val)
    }

And this is output:

-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvs97nrY4XqXVJT1Y4AU5
xxx
TLWXK2H4swuXSEyV75Ylem+f2iF+20xHTZ4jTUBzYmikBuUsm0839T5SDmwEquTB
fQIDAQAB
-----END PUBLIC KEY-----

key is of invalid type
TOKEN is: false
Key: iss, value: https://example.com
Key: nbf, value: 1.592797834e+09
Key: exp, value: 1.592801434e+09
Key: sub, value: 3
Key: aid, value: 2
Key: fea, value: 0
Key: iat, value: 1.592797834e+09
Key: aud, value: []
Key: jti, value: 7a97a2327e671d2bf01253819fb319d6

I observed that key is of invalid type and token.valid is false.

Could anybody help me point out the wrong code and how to fix this?

Tks in advance!!!

like image 359
Tho Quach Avatar asked Oct 15 '22 02:10

Tho Quach


2 Answers

Passing []byte(publicKey) to the keyFunc is wrong.

In case of rsa (i.e. RS256, RS512 or RS384), you should return a *rsa.PublicKey instead (see this for more information on how Verfiy() is implemented).

Use ExampleParsePKIXPublicKey() here to parse and decode your string public key or as mentioned by @Dan, you can use ParseRSAPublicKeyFromPEM (see this for more info).

like image 157
ifnotak Avatar answered Oct 20 '22 19:10

ifnotak


Remove new line character from public key and try it out.

publicKey = "-----BEGIN PUBLIC KEY-----MIIBIjANBgkqhkiG9w0BAQEFAAOCAxxxxxxf2iF+20xHTZ4jTUBzYmikBuUsm0839T5SDmwEquTBfQIDAQAB-----END PUBLIC KEY-----"
like image 22
Pankaj Avatar answered Oct 20 '22 20:10

Pankaj