Skip to content

Commit

Permalink
Allow single string audience
Browse files Browse the repository at this point in the history
  • Loading branch information
dbramwell authored and csstaub committed Jun 3, 2019
1 parent c768d60 commit 41ba410
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
10 changes: 10 additions & 0 deletions jwt/claims.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,16 @@ func (s *Audience) UnmarshalJSON(b []byte) error {
return nil
}

// MarshalJSON converts audience to json representation.
func (s Audience) MarshalJSON() ([]byte, error) {
type Alias Audience
if len(s) == 1 {
return json.Marshal(s[0])
}
return json.Marshal((Alias)(s))
}

//Contains checks whether a given string is included in the Audience
func (s Audience) Contains(v string) bool {
for _, a := range s {
if a == v {
Expand Down
19 changes: 19 additions & 0 deletions jwt/claims_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,25 @@ func TestEncodeClaims(t *testing.T) {
assert.Equal(t, expected, string(b))
}

func TestEncodeClaimsWithSingleAudience(t *testing.T) {
now := time.Date(2016, 1, 1, 0, 0, 0, 0, time.UTC)

c := Claims{
Issuer: "issuer",
Subject: "subject",
Audience: Audience{"a1"},
NotBefore: NewNumericDate(time.Time{}),
IssuedAt: NewNumericDate(now),
Expiry: NewNumericDate(now.Add(1 * time.Hour)),
}

b, err := json.Marshal(c)
assert.NoError(t, err)

expected := `{"iss":"issuer","sub":"subject","aud":"a1","exp":1451610000,"iat":1451606400}`
assert.Equal(t, expected, string(b))
}

func TestDecodeClaims(t *testing.T) {
s := []byte(`{"iss":"issuer","sub":"subject","aud":["a1","a2"],"exp":1451610000,"iat":1451606400}`)
now := time.Date(2016, 1, 1, 0, 0, 0, 0, time.UTC)
Expand Down

0 comments on commit 41ba410

Please sign in to comment.