[英]Validate AWS Cognito JWT in GO
我正在嘗試驗證從 AWS Cognito(托管 UI)登錄返回的 JWT。 我注意到,一旦在 cognito 中完成登錄,它就會嘗試使用諸如“id_token”和“access_token”之類的一些參數來訪問我的應用程序。 使用 jwt.io 檢查,看起來“id_token”是 jwt。
作為測試,我在 GO 中編寫了一個 post 函數,期待一個帶有 jwt 令牌和訪問令牌的主體(並從這個答案中實現)
func auth(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
keyset, err := jwk.Fetch(context.Background(), "https://cognito-idp.{Region}.amazonaws.com/{poolID}/.well-known/jwks.json")
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
json.NewEncoder(w).Encode(&model.ErrorResponse{
Response: model.Response{
Result: false,
},
StatusCd: "500",
StatusDesc: "Failed to fetch jwks. Authorization failed.",
Error: "errRes",
})
}
authRequest := &model.AuthRequest{}
json.NewDecoder(r.Body).Decode(&authRequest)
parsedToken, err := jwt.Parse(
[]byte(authRequest.Token), //This is the JWT
jwt.WithKeySet(keyset),
jwt.WithValidate(true),
jwt.WithIssuer("https://cognito-idp.{Region}.amazonaws.com/{poolID}"),
jwt.WithAudience("{XX APP CLIENT ID XX}"),
jwt.WithClaimValue("key", authRequest.Access), //This is the Access Token
)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
json.NewEncoder(w).Encode(&model.ErrorResponse{
Response: model.Response{
Result: false,
},
StatusCd: "500",
StatusDesc: "Failed token parse. Authorization failed.",
Error: "errRes",
})
}
result := parsedToken
json.NewEncoder(w).Encode(result)
}
我正在使用的軟件包是
"github.com/lestrrat-go/jwx/jwk"
"github.com/lestrrat-go/jwx/jwt"
顯然,它在令牌解析中失敗了。 我做錯了什么,我應該怎么處理parsedToken
?
我對此很陌生,所以我不知道這是否是正確的方法,並且真的需要一些指導。
我建議從做最少的檢查開始——即,首先嘗試不進行驗證就進行解析,然后逐一添加驗證:
請注意,我不知道 id_token 中有什么,因為我從未使用過 Cognito 如果它是原始 JWT,則您不需要密鑰集,並且 (1) 應該可以工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.