amazon-web-services - 如何在 Go 中验证来自 AWS Cognito 的 JWT token ?

标签 amazon-web-services go jwt amazon-cognito jwt-go

我如何验证从 Amazon Cognito 收到的 JWT 并从中获取信息?

我在 Cognito 中设置了 Google 身份验证,并将重定向 uri 设置为命中 API 网关,然后我收到一个代码,我将其发布到此端点:

https://docs.aws.amazon.com/cognito/latest/developerguide/token-endpoint.html

以 RS256 格式接收 JWT token 。我现在正在努力验证和解析 Golang 中的 token 。我尝试使用 jwt-go 解析它,但它似乎默认支持 HMAC,并在某处阅读了他们推荐使用前端验证的信息。我尝试了其他几个软件包并遇到了类似的问题。

我在这里遇到了这个答案:Go Language and Verify JWT但假设代码已经过时,因为它只是说 panic: unable to find key

jwt.io 可以轻松解码 key ,也可能进行验证。我不确定亚马逊生成 token 时公钥/私钥在哪里,但据我了解,我也需要使用 JWK URL 来验证吗?我找到了一些 AWS 特定的解决方案,但它们似乎都长达数百行。在 Golang 中肯定没那么复杂吧?

最佳答案

Amazon Cognito 的公钥

正如您已经猜到的那样,您将需要公钥来验证 JWT token 。

https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-tokens-verifying-a-jwt.html#amazon-cognito-user-pools-using-tokens-step-2

Download and store the corresponding public JSON Web Key (JWK) for your user pool. It is available as part of a JSON Web Key Set (JWKS). You can locate it at https://cognito-idp.{region}.amazonaws.com/{userPoolId}/.well-known/jwks.json

解析 key 并验证 token

网络上记录了该 JSON 文件结构,因此您可以手动解析它、生成公钥等。

但是使用一个库可能会更容易,例如这个: https://github.com/lestrrat-go/jwx

然后jwt-go去处理JWT部分:https://github.com/dgrijalva/jwt-go

然后您可以:

  1. 使用第一个库下载并解析公钥 JSON

     keySet, err := jwk.Fetch(THE_COGNITO_URL_DESCRIBED_ABOVE)
    
  2. 使用 jwt-go 解析 token 时,使用 JWT header 中的“kid”字段找到要使用的正确 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
    

关于amazon-web-services - 如何在 Go 中验证来自 AWS Cognito 的 JWT token ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56905995/

相关文章:

node.js - POST 到 AWS EC2 Mongodb 数据库在生产中不起作用

amazon-web-services - cfn-init 相对于 userdata 有哪些优势?

sql - 当 SQL 查询内存不足时会发生什么?

google-app-engine - Go:如何将 struct 转换为 []byte?

parsing - Go时间解析返回不同的值

node.js - 如何生成刷新 token ?

web-services - 防止 token 共享的最佳方法是什么?

python - 为 AWS Cognito 使用 python boto3 实现 USER_SRP_AUTH

go - 如何将FaunaDB的时间类型数据映射到go lang变量?

c# - 使用字符串中的公钥验证 JWT