Skip to content

Commit

Permalink
feat: support adding new aud values
Browse files Browse the repository at this point in the history
  • Loading branch information
cloudcarver committed Oct 16, 2024
1 parent 869a37c commit 3623c6d
Show file tree
Hide file tree
Showing 2 changed files with 72 additions and 3 deletions.
25 changes: 22 additions & 3 deletions token/jwt/claims_id_token.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,10 +49,29 @@ func (c *IDTokenClaims) ToMap() map[string]interface{} {
ret["jti"] = uuid.New().String()
}

if _, ok := ret["aud"].([]string); !ok {
if _, ok := ret["aud"].(string); ok {
ret["aud"] = []string{ret["aud"].(string)}
} else {
ret["aud"] = []string{}
}
}

if len(c.Audience) > 0 {
ret["aud"] = c.Audience
} else {
ret["aud"] = []string{}
newAuds := []string{}
m := map[string]struct{}{}
for _, a := range c.Audience {
m[a] = struct{}{}
newAuds = append(newAuds, a)
}

var extraAud = ret["aud"].([]string)
for _, aud := range extraAud {
if _, ok := m[aud]; !ok {
newAuds = append(newAuds, aud)
}
}
ret["aud"] = newAuds
}

if !c.IssuedAt.IsZero() {
Expand Down
50 changes: 50 additions & 0 deletions token/jwt/claims_id_token_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,3 +76,53 @@ func TestIDTokenClaimsToMap(t *testing.T) {
"nonce": idTokenClaims.Nonce,
}, idTokenClaims.ToMap())
}

func TestIDTokenClaimsToMap_new_aud(t *testing.T) {
// extra & overlap
IDClaims := &IDTokenClaims{
JTI: "foo-id",
Audience: []string{"default"},
Extra: map[string]any{
"aud": []string{"default", "new"},
},
}
assert.Equal(t, map[string]any{
"jti": "foo-id",
"aud": []string{"default", "new"},
}, IDClaims.ToMap())

// extra & no original values
IDClaims = &IDTokenClaims{
JTI: "foo-id",
Extra: map[string]any{
"aud": []string{"default", "new"},
},
}
assert.Equal(t, map[string]any{
"jti": "foo-id",
"aud": []string{"default", "new"},
}, IDClaims.ToMap())

// only original values
IDClaims = &IDTokenClaims{
JTI: "foo-id",
Audience: []string{"default"},
}
assert.Equal(t, map[string]any{
"jti": "foo-id",
"aud": []string{"default"},
}, IDClaims.ToMap())

// extra value is an string
IDClaims = &IDTokenClaims{
JTI: "foo-id",
Audience: []string{"default"},
Extra: map[string]any{
"aud": "new",
},
}
assert.Equal(t, map[string]any{
"jti": "foo-id",
"aud": []string{"default", "new"},
}, IDClaims.ToMap())
}

0 comments on commit 3623c6d

Please sign in to comment.