How to verify JWT signature with JWK in Go?
One challenge of authenticating JWTs is verifying signatures. This is especially true with JWKs and the Go language.
The Problem
Decoders allow us to parse JWTs. However, verifying signatures, especially with JWKs, offers a different challenge. Here's an example of a common error:
type myClaims struct { jwt.StandardClaims } func main() { claims := &myClaims{} _, err := jwt.ParseWithClaims("ey...", claims, getKey) if err != nil { log.Fatal(err) } }
Error: Key "kid" not found in token
The Solution
To resolve this, we must provide a Keyfunc that retrieves the public key. The following code demonstrates a solution:
const jwksURL = "https://companyx.okta.com/oauth2/v1/keys" func getKey(token *jwt.Token) (interface{}, error) { // TODO: Cache the response to avoid repeated HTTP requests set, err := jwk.FetchHTTP(jwksURL) if err != nil { return nil, err } keyID, ok := token.Header["kid"].(string) if !ok { return nil, errors.New("expecting JWT header to have string kid") } if key := set.LookupKeyID(keyID); len(key) == 1 { return key[0].Materialize() } return nil, fmt.Errorf("unable to find key %q", keyID) }
This getKey function:
By providing this getKey function, you can successfully verify JWT signatures using JWKs in Go.
The above is the detailed content of How to Verify JWT Signatures Using JWKs in Go?. For more information, please follow other related articles on the PHP Chinese website!