简体   繁体   中英

Validate AWS Cognito JWT in GO

I am trying validate JWT returned from a login from AWS Cognito (hosted UI). I noticed that once the login is done in cognito, it tries to access my app with some params like "id_token" and "access_token". Checked with jwt.io and looks like "id_token" is the jwt.

As a test, I wrote a post function in GO expecting a body with the jwt token and the access token (and implemented from this answer )

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)
}

Packages I am using are

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

Obviously, it failed at the token parse. What am I doing wrong and also what should I do with the parsedToken ?

I am new to this so, I have no clue if this is the correct approach and would really like some guidance.

I would suggest to start out by doing the minimal checks -- ie, first try just parsing without validation, then add validations one by one:

  1. jwt.Parse([]byte(token)) // probably fails because of JWS
  2. jwt.Parse([]byte(token), jwt.WithKeySet(...)) // should be OK?
  3. jwt.Parse(..., jwt.WithValidation(true), ...) // add conditions one by one

Please note that I have no idea what's in id_token, as I have never used Cognito If it's a raw JWT, you shouldn't need a key set, and (1) should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM