Skip to content

Commit

Permalink
insured that genericclaims type is a string, so we properly can (#133)
Browse files Browse the repository at this point in the history
identify custom generic jwt types as generic on their "ClaimType".
  • Loading branch information
aricart committed Dec 17, 2020
1 parent 911e216 commit 7217f9c
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 2 deletions.
31 changes: 30 additions & 1 deletion v2/genericclaims_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ package jwt
import (
"testing"
"time"

jwtv1 "github.com/nats-io/jwt"
)

func TestNewGenericClaims(t *testing.T) {
Expand Down Expand Up @@ -84,7 +86,34 @@ func TestGenericClaimsCanHaveCustomType(t *testing.T) {
t.Fatal("failed to decode", err)
}
if gc2.ClaimType() != GenericClaim {
t.Fatalf("expected claimtype to be generic got: %v", gc.ClaimType())
t.Fatalf("expected claimtype to be generic got: %v", gc2.ClaimType())
}
if gc2.Data["type"] != "my_type" {
t.Fatalf("expected internal type to be 'my_type': %v", gc2.Data["type"])
}
}

func TestGenericClaimsCanHaveCustomTypeFromV1(t *testing.T) {
akp := createAccountNKey(t)
apk := publicKey(akp, t)

gc := jwtv1.NewGenericClaims(apk)
gc.Expires = time.Now().Add(time.Hour).UTC().Unix()
gc.Name = "alberto"
gc.Data["hello"] = "world"
gc.Data["count"] = 5
gc.Type = "my_type"
token, err := gc.Encode(akp)
if err != nil {
t.Fatalf("failed to encode v1 JWT: %v", err)
}

gc2, err := DecodeGeneric(token)
if err != nil {
t.Fatal("failed to decode", err)
}
if gc2.ClaimType() != GenericClaim {
t.Fatalf("expected claimtype to be generic got: %v", gc2.ClaimType())
}
if gc2.Data["type"] != "my_type" {
t.Fatalf("expected internal type to be 'my_type': %v", gc2.Data["type"])
Expand Down
5 changes: 4 additions & 1 deletion v2/genericlaims.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,10 @@ func DecodeGeneric(token string) (*GenericClaims, error) {
return nil, errors.New("claim failed V1 signature verification")
}
if tp := gc.GenericFields.Type; tp != "" {
gc.GenericClaims.Data["type"] = tp
// the conversion needs to be from a string because
// on custom types the type is not going to be one of
// the constants
gc.GenericClaims.Data["type"] = string(tp)
}
if tp := gc.GenericFields.Tags; len(tp) != 0 {
gc.GenericClaims.Data["tags"] = tp
Expand Down

0 comments on commit 7217f9c

Please sign in to comment.