我有一个公共密钥和一个JWT,如何检查它在Go中是否有效?

I have a public key from my identity provider

-----BEGIN PUBLIC KEY-----
THIS
-----END PUBLIC KEY-----

And a JWT token from my client.

How do I check the token against the key? I'm having difficulty with jwt-go because the Parse function takes the token string and a getKey function.

Not sure how exactly to proceed

Using jwt-go, you can do this

token, err := p.Parse(IDToken, func(*jwt.Token) (interface{}, error) {
    return []byte(signingKey), nil
})

And it will verify the token against the key.

Quoting the documentation,

type Keyfunc func(*Token) (interface{}, error)

Parse methods use this callback function to supply the key for verification. The function receives the parsed, but unverified Token. This allows you to use properties in the Header of the token (such as kid) to identify which key to use.

The token was signed by RSA algorithm that uses a private key to sign and a public key to verify. Store your public key to the files system and use jwt.SigningMethodRS256.Verify() to verify. As the following snippet:

package main

import (
    "fmt"
    "strings"
    "log"
    "io/ioutil"
    jwt "github.com/dgrijalva/jwt-go"
)

func main() {
    publicKeyPath := "~/public_key.key"
    token := "your_jwt_token_here"

    if isValid, err := verifyToken(token, publicKeyPath)
    if err != nil {
        log.Fatal(err)
    }

    if isValid {
        fmt.Println("The token is valid")
    } else {
        fmt.Println("The token is invalid")
    }
}

func verifyToken(token, publicKeyPath string) (bool, error) {
    keyData, err := ioutil.ReadFile(publicKeyPath)
    if err != nil {
        return false, err
    }
    key, err := jwt.ParseRSAPublicKeyFromPEM(keyData)
    if err != nil {
        return false, err
    }

    parts := strings.Split(token, ".")
    err = jwt.SigningMethodRS256.Verify(strings.Join(parts[0:2], "."), parts[2], key)
    if err != nil {
        return false, nil
    }
    return true, nil
}