Skip to content
This repository has been archived by the owner on May 21, 2022. It is now read-only.

add parser option to make aud required #412

Open
wants to merge 1 commit into
base: release_4_0_0
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions parser_option.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,14 @@ func WithAudience(aud string) ParserOption {
}
}

// WithAudienceRequired returns the ParserOption for specifying a required aud member value
func WithAudienceRequired(aud string) ParserOption {
return func(p *Parser) {
p.ValidationHelper.audience = &aud
p.ValidationHelper.requireAudience = true
}
}

// WithoutAudienceValidation returns the ParserOption that specifies audience check should be skipped
func WithoutAudienceValidation() ParserOption {
return func(p *Parser) {
Expand Down
9 changes: 9 additions & 0 deletions parser_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,15 @@ var jwtTestData = []struct {
[]error{&jwt.InvalidAudienceError{}},
jwt.NewParser(),
},
{
"Audience - Required in Claims",
"", // autogen
defaultKeyFunc,
jwt.MapClaims{"aud": []interface{}{}},
false,
[]error{&jwt.InvalidAudienceError{}},
jwt.NewParser(jwt.WithAudienceRequired("foo")),
},
{
"Audience - Ignored",
"", // autogen
Expand Down
13 changes: 11 additions & 2 deletions validation_helper.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ type ValidationHelper struct {
leeway time.Duration // Leeway to provide when validating time values
audience *string // Expected audience value
skipAudience bool // Ignore aud check
requireAudience bool // Make sure aud value exists
issuer *string // Expected issuer value. ignored if nil
}

Expand Down Expand Up @@ -97,7 +98,11 @@ func (h *ValidationHelper) ValidateAudience(aud ClaimStrings) error {

// If there's no audience claim, ignore
if aud == nil || len(aud) == 0 {
return nil
if h.requireAudience {
return &InvalidAudienceError{Message: "audience value is missing"}
} else {
return nil
}
}

// If there is an audience claim, but no value provided, fail
Expand All @@ -112,7 +117,11 @@ func (h *ValidationHelper) ValidateAudience(aud ClaimStrings) error {
// It is used by ValidateAudience, but exposed as a helper for other implementations
func (h *ValidationHelper) ValidateAudienceAgainst(aud ClaimStrings, compare string) error {
if aud == nil {
return nil
if h.requireAudience {
return &InvalidAudienceError{Message: "audience value is missing"}
} else {
return nil
}
}

// Compare provided value with aud claim.
Expand Down