简体   繁体   中英

How to validate a JWT token in Golang

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!!!

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

In case of rsa (ie 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).

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

publicKey = "-----BEGIN PUBLIC KEY-----MIIBIjANBgkqhkiG9w0BAQEFAAOCAxxxxxxf2iF+20xHTZ4jTUBzYmikBuUsm0839T5SDmwEquTBfQIDAQAB-----END PUBLIC KEY-----"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM