diff --git a/parser_option.go b/parser_option.go index fd285ebe..10362f3f 100644 --- a/parser_option.go +++ b/parser_option.go @@ -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) { diff --git a/parser_test.go b/parser_test.go index 1d92761a..48f72f3a 100644 --- a/parser_test.go +++ b/parser_test.go @@ -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 diff --git a/validation_helper.go b/validation_helper.go index 2edd0a46..2edbaaab 100644 --- a/validation_helper.go +++ b/validation_helper.go @@ -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 } @@ -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 @@ -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.