Home >Backend Development >Golang >How to Verify AWS Cognito JWT Tokens in Go?

How to Verify AWS Cognito JWT Tokens in Go?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-27 08:32:14218browse

How to Verify AWS Cognito JWT Tokens in Go?

Verifying AWS Cognito JWT Tokens in Go

Introduction

Validating and extracting information from JWT tokens issued by Amazon Cognito can be a challenge in Go. This article provides a concise guide to handling this task effectively.

Prerequisites

AWS Cognito users must retrieve the public JSON Web Key (JWK) set from the JWKS endpoint:

https://cognito-idp.{region}.amazonaws.com/{userPoolId}/.well-known/jwks.json

Parsing JWKs and Verifying JWTs

To parse the JWK set and verify JWTs, consider using:

  • [jwk](https://github.com/lestrrat-go/jwx): For JWK parsing
  • [jwt-go](https://github.com/dgrijalva/jwt-go): For JWT validation

Implementation

  1. Fetch and parse the JWK set using jwk.Fetch().
  2. Use jwt.Parse() to parse the JWT token.
  3. Extract the "kid" field from the JWT header to identify the matching public key in the JWK set.
  4. Use keySet.LookupKeyID(kid) to retrieve the public key associated with the "kid" header.
  5. Assign the public key to the func(token *jwt.Token) (interface{}, error) callback when parsing the JWT token.

Example Code

package main

import (
    "fmt"

    jwt "github.com/dgrijalva/jwt-go"
    "github.com/lestrrat-go/jwx/jwk"
)

func main() {
    // Replace with your Cognito token and Cognito JWKS endpoint
    tokenString := "YOUR_JWT_TOKEN"
    endpoint := "YOUR_COGNITO_JWKS_ENDPOINT"

    keySet, err := jwk.Fetch(endpoint)
    if err != nil {
        fmt.Println(err)
        return
    }

    // Parse the JWT token and validate its signature using the public key
    token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
        if _, ok := token.Method.(*jwt.SigningMethodRS256); !ok {
            return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
        }
        kid, ok := token.Header["kid"].(string)
        if !ok {
            return nil, errors.New("kid header not found")
        }
        keys := keySet.LookupKeyID(kid)
        if !ok {
            return nil, fmt.Errorf("key with specified kid is not present in jwks")
        }
        var publickey interface{}
        err = keys.Raw(&publickey)
        if err != nil {
            return nil, fmt.Errorf("could not parse pubkey")
        }
        return publickey, nil
    })

    if err != nil {
        fmt.Println(err)
        return
    }

    // Access the claims from the validated JWT token
    claims := token.Claims.(jwt.MapClaims)
    fmt.Println("User ID: ", claims["sub"])
}

Conclusion

By utilizing libraries such as jwk and jwt-go, developers can verify and retrieve data from Cognito JWT tokens in Go efficiently, providing a secure and convenient way to authenticate users in their applications.

The above is the detailed content of How to Verify AWS Cognito JWT Tokens in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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