From 5ed1b49ce887bce04c69f94d02de337e400c173e Mon Sep 17 00:00:00 2001 From: "Gerasimos (Makis) Maropoulos" Date: Wed, 9 Mar 2022 11:46:10 +0200 Subject: [PATCH] fix #8 --- claims.go | 21 +++++++++++++++++---- claims_test.go | 15 +++++++++++++++ 2 files changed, 32 insertions(+), 4 deletions(-) diff --git a/claims.go b/claims.go index 78c282f..d2777cd 100644 --- a/claims.go +++ b/claims.go @@ -3,6 +3,7 @@ package jwt import ( "encoding/json" "errors" + "fmt" "time" ) @@ -62,8 +63,8 @@ type claimsSecondChance struct { IssuedAt json.Number `json:"iat,omitempty"` Expiry json.Number `json:"exp,omitempty"` ID string `json:"jti,omitempty"` - Issuer string `json:"iss,omitempty"` - Subject string `json:"sub,omitempty"` + Issuer interface{} `json:"iss,omitempty"` + Subject interface{} `json:"sub,omitempty"` Audience Audience `json:"aud,omitempty"` } @@ -77,12 +78,24 @@ func (c claimsSecondChance) toClaims() Claims { IssuedAt: int64(iat), Expiry: int64(exp), ID: c.ID, - Issuer: c.Issuer, - Subject: c.Subject, + Issuer: getStr(c.Issuer), + Subject: getStr(c.Subject), Audience: c.Audience, } } +func getStr(v interface{}) string { + if v == nil { + return "" + } + + if s, ok := v.(string); ok { + return s + } else { + return fmt.Sprintf("%v", v) + } +} + // Audience represents the "aud" standard JWT claim. // See the `Claims` structure for details. type Audience []string diff --git a/claims_test.go b/claims_test.go index 33f35dc..6832d6b 100644 --- a/claims_test.go +++ b/claims_test.go @@ -147,3 +147,18 @@ func TestMaxAgeMap(t *testing.T) { // test no panic if nil. MaxAgeMap(maxAge, nil) } + +func TestClaimsSubAsInt(t *testing.T) { + secret := "secret" + token := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOjEyMywibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.QzFnWiase0tPyeNzn8ecl-kVfDVEZ1ctbf9ztM0Qjqg" + + verifiedToken, err := Verify(HS256, []byte(secret), []byte(token)) + if err != nil { + t.Fatal(err) + } + + expectedClaims := Claims{NotBefore: 0, IssuedAt: 1516239022, Expiry: 0, ID: "", Issuer: "", Subject: "123", Audience: nil} + if !reflect.DeepEqual(verifiedToken.StandardClaims, expectedClaims) { + t.Fatalf("expected: %#+v but got: %#+v\n", expectedClaims, verifiedToken.StandardClaims) + } +}