Skip to content

Commit

Permalink
feat(idtoken): add ParsePayload returning unvalidated token payload (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
eytankidron authored Sep 14, 2023
1 parent 124e36e commit d541d8e
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 1 deletion.
19 changes: 18 additions & 1 deletion idtoken/validate.go
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,23 @@ func Validate(ctx context.Context, idToken string, audience string) (*Payload, e
return defaultValidator.validate(ctx, idToken, audience)
}

// ParsePayload parses the given token and returns its payload.
//
// Warning: This function does not validate the token prior to parsing it.
//
// ParsePayload is primarily meant to be used to inspect a token's payload. This is
// useful when validation fails and the payload needs to be inspected.
//
// Note: A successful Validate() invocation with the same token will return an
// identical payload.
func ParsePayload(idToken string) (*Payload, error) {
jwt, err := parseJWT(idToken)
if err != nil {
return nil, err
}
return jwt.parsedPayload()
}

func (v *Validator) validate(ctx context.Context, idToken string, audience string) (*Payload, error) {
jwt, err := parseJWT(idToken)
if err != nil {
Expand All @@ -145,7 +162,7 @@ func (v *Validator) validate(ctx context.Context, idToken string, audience strin
}

if now().Unix() > payload.Expires {
return nil, fmt.Errorf("idtoken: token expired")
return nil, fmt.Errorf("idtoken: token expired: now=%v, expires=%v", now().Unix(), payload.Expires)
}

switch header.Algorithm {
Expand Down
33 changes: 33 additions & 0 deletions idtoken/validate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,39 @@ func TestValidateES256(t *testing.T) {
}
}

func TestParsePayload(t *testing.T) {
idToken, _ := createRS256JWT(t)
tests := []struct {
name string
token string
wantPayloadAudience string
wantErr bool
}{{
name: "valid token",
token: idToken,
wantPayloadAudience: testAudience,
}, {
name: "unparseable token",
token: "aaa.bbb.ccc",
wantErr: true,
}}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
payload, err := ParsePayload(tt.token)
gotErr := err != nil
if gotErr != tt.wantErr {
t.Errorf("ParsePayload(%q) got error %v, wantErr = %v", tt.token, err, tt.wantErr)
}
if tt.wantPayloadAudience != "" {
if payload == nil || payload.Audience != tt.wantPayloadAudience {
t.Errorf("ParsePayload(%q) got payload %+v, want payload with audience = %q", tt.token, payload, tt.wantPayloadAudience)
}
}
})
}
}

func createES256JWT(t *testing.T) (string, ecdsa.PublicKey) {
t.Helper()
token := commonToken(t, "ES256")
Expand Down

0 comments on commit d541d8e

Please sign in to comment.