简体   繁体   中英

Verify JWT Token fails in Golang

I have a JWT token generated in nodejs app. It is signed using HS256. I've written the code to validate it in golang. I get an error message of "signature is invalid" even though I verified it in the JWT.io site. The code validates also Public/Private, but this works. Only the HS256 is not I've also printed the token and the secret to make sure they are the right values. Any help will be appreciated. My golang code:

token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
        // Validate the alg is the expected algorithm:
        if conf.JwtAlgorithm != token.Header["alg"] {
            log.Printf("unexpected signing method: %s, conf algorithm: %s\n", token.Header["alg"], conf.JwtAlgorithm)
            return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
        }

        log.Printf("JWT algo is: %s, Public is %s, secret is %s", token.Header["alg"], publicKey, secret)

        if secret != "" {
            log.Printf("Returning secret %s", secret)
            return []byte(secret), nil
        }
        if publicKey != "" {
            pub, _ := jwt.ParseRSAPublicKeyFromPEM([]byte(publicKey))
            fmt.Println("pub is of type RSA:", pub)
            return pub, nil
        }
        return nil, fmt.Errorf("PublicKey and secret are empty")
    })

Since you only have a single HMAC key, you'll want something like this:

package main

import (
    "log"

    "github.com/golang-jwt/jwt/v4"
)

func main() {
    const tokenString = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.drt_po6bHhDOF_FJEHTrK-KD8OGjseJZpHwHIgsnoTM"

    var keyfunc jwt.Keyfunc = func(token *jwt.Token) (interface{}, error) {
        return []byte("mysecret"), nil
    }

    parsed, err := jwt.Parse(tokenString, keyfunc)
    if err != nil {
        log.Fatalf("Failed to parse JWT.\nError: %s", err.Error())
    }

    if !parsed.Valid {
        log.Fatalln("Token is not valid.")
    }

    log.Println("Token is valid.")
}

It's certainly confusing what the return type should be for a jwt.Keyfunc . For an HMAC key, the return type should be []byte .

Please note that HMAC keys do not use public key cryptography and therefore are only a private key that shouldn't be shared.

If the JWTs you need to parse and verify start to become more complex, check out this package: github.com/MicahParks/keyfunc . It has support for multiple given keys like HMAC and remote JWKS resources.

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