Home > Backend Development > Golang > How to Verify JWT Signatures Using JWKs in Go?

How to Verify JWT Signatures Using JWKs in Go?

Linda Hamilton
Release: 2024-12-28 17:00:12
Original
949 people have browsed it

How to Verify JWT Signatures Using JWKs in Go?

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)
    }
}
Copy after login

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)
}
Copy after login

This getKey function:

  1. Fetches the public keys from a provided URL.
  2. Retrieves the key ID from the JWT header.
  3. Looks up the key using the key ID.
  4. Materializes the key into an interface that jwt-go can use for verification.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template