我如何验证从 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 。
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
然后您可以:
使用第一个库下载并解析公钥 JSON
keySet, err := jwk.Fetch(THE_COGNITO_URL_DESCRIBED_ABOVE)
使用 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/