Skip to content

Commit 4e6e1ba

Browse files
committed
More documentation cleanup
1 parent 57662e5 commit 4e6e1ba

File tree

5 files changed

+96
-75
lines changed

5 files changed

+96
-75
lines changed

map_claims.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,8 @@ import (
44
"encoding/json"
55
)
66

7-
// MapClaims is a claims type that uses the map[string]interface{} for JSON decoding.
8-
// This is the default claims type if you don't supply one
7+
// MapClaims is a claims type that uses the map[string]interface{} for JSON
8+
// decoding. This is the default claims type if you don't supply one
99
type MapClaims map[string]interface{}
1010

1111
// GetExpirationTime implements the Claims interface.

parser_option.go

Lines changed: 21 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -2,28 +2,32 @@ package jwt
22

33
import "time"
44

5-
// ParserOption is used to implement functional-style options that modify the behavior of the parser. To add
6-
// new options, just create a function (ideally beginning with With or Without) that returns an anonymous function that
7-
// takes a *Parser type as input and manipulates its configuration accordingly.
5+
// ParserOption is used to implement functional-style options that modify the
6+
// behavior of the parser. To add new options, just create a function (ideally
7+
// beginning with With or Without) that returns an anonymous function that takes
8+
// a *Parser type as input and manipulates its configuration accordingly.
89
type ParserOption func(*Parser)
910

10-
// WithValidMethods is an option to supply algorithm methods that the parser will check. Only those methods will be considered valid.
11-
// It is heavily encouraged to use this option in order to prevent attacks such as https://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries/.
11+
// WithValidMethods is an option to supply algorithm methods that the parser
12+
// will check. Only those methods will be considered valid. It is heavily
13+
// encouraged to use this option in order to prevent attacks such as
14+
// https://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries/.
1215
func WithValidMethods(methods []string) ParserOption {
1316
return func(p *Parser) {
1417
p.validMethods = methods
1518
}
1619
}
1720

18-
// WithJSONNumber is an option to configure the underlying JSON parser with UseNumber
21+
// WithJSONNumber is an option to configure the underlying JSON parser with
22+
// UseNumber.
1923
func WithJSONNumber() ParserOption {
2024
return func(p *Parser) {
2125
p.useJSONNumber = true
2226
}
2327
}
2428

25-
// WithoutClaimsValidation is an option to disable claims validation. This option should only be used if you exactly know
26-
// what you are doing.
29+
// WithoutClaimsValidation is an option to disable claims validation. This
30+
// option should only be used if you exactly know what you are doing.
2731
func WithoutClaimsValidation() ParserOption {
2832
return func(p *Parser) {
2933
p.skipClaimsValidation = true
@@ -58,9 +62,10 @@ func WithIssuedAt() ParserOption {
5862
// the `aud` claim. Validation will fail if the audience is not listed in the
5963
// token or the `aud` claim is missing.
6064
//
61-
// NOTE: While the `aud` claim is OPTIONAL is a JWT, the handling of it is
65+
// NOTE: While the `aud` claim is OPTIONAL in a JWT, the handling of it is
6266
// application-specific. Since this validation API is helping developers in
63-
// writing secure application, we decided to REQUIRE the existence of the claim.
67+
// writing secure application, we decided to REQUIRE the existence of the claim,
68+
// if an audience is expected.
6469
func WithAudience(aud string) ParserOption {
6570
return func(p *Parser) {
6671
p.validator.expectedAud = aud
@@ -71,9 +76,10 @@ func WithAudience(aud string) ParserOption {
7176
// `iss` claim. Validation will fail if a different issuer is specified in the
7277
// token or the `iss` claim is missing.
7378
//
74-
// NOTE: While the `iss` claim is OPTIONAL is a JWT, the handling of it is
79+
// NOTE: While the `iss` claim is OPTIONAL in a JWT, the handling of it is
7580
// application-specific. Since this validation API is helping developers in
76-
// writing secure application, we decided to REQUIRE the existence of the claim.
81+
// writing secure application, we decided to REQUIRE the existence of the claim,
82+
// if an issuer is expected.
7783
func WithIssuer(iss string) ParserOption {
7884
return func(p *Parser) {
7985
p.validator.expectedIss = iss
@@ -84,9 +90,10 @@ func WithIssuer(iss string) ParserOption {
8490
// `sub` claim. Validation will fail if a different subject is specified in the
8591
// token or the `sub` claim is missing.
8692
//
87-
// NOTE: While the `sub` claim is OPTIONAL is a JWT, the handling of it is
93+
// NOTE: While the `sub` claim is OPTIONAL in a JWT, the handling of it is
8894
// application-specific. Since this validation API is helping developers in
89-
// writing secure application, we decided to REQUIRE the existence of the claim.
95+
// writing secure application, we decided to REQUIRE the existence of the claim,
96+
// if a subject is expected.
9097
func WithSubject(sub string) ParserOption {
9198
return func(p *Parser) {
9299
p.validator.expectedSub = sub

token.go

Lines changed: 47 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -6,42 +6,49 @@ import (
66
"strings"
77
)
88

9-
// DecodePaddingAllowed will switch the codec used for decoding JWTs respectively. Note that the JWS RFC7515
10-
// states that the tokens will utilize a Base64url encoding with no padding. Unfortunately, some implementations
11-
// of JWT are producing non-standard tokens, and thus require support for decoding. Note that this is a global
12-
// variable, and updating it will change the behavior on a package level, and is also NOT go-routine safe.
13-
// To use the non-recommended decoding, set this boolean to `true` prior to using this package.
9+
// DecodePaddingAllowed will switch the codec used for decoding JWTs
10+
// respectively. Note that the JWS RFC7515 states that the tokens will utilize a
11+
// Base64url encoding with no padding. Unfortunately, some implementations of
12+
// JWT are producing non-standard tokens, and thus require support for decoding.
13+
// Note that this is a global variable, and updating it will change the behavior
14+
// on a package level, and is also NOT go-routine safe. To use the
15+
// non-recommended decoding, set this boolean to `true` prior to using this
16+
// package.
1417
var DecodePaddingAllowed bool
1518

1619
// DecodeStrict will switch the codec used for decoding JWTs into strict mode.
17-
// In this mode, the decoder requires that trailing padding bits are zero, as described in RFC 4648 section 3.5.
18-
// Note that this is a global variable, and updating it will change the behavior on a package level, and is also NOT go-routine safe.
19-
// To use strict decoding, set this boolean to `true` prior to using this package.
20+
// In this mode, the decoder requires that trailing padding bits are zero, as
21+
// described in RFC 4648 section 3.5. Note that this is a global variable, and
22+
// updating it will change the behavior on a package level, and is also NOT
23+
// go-routine safe. To use strict decoding, set this boolean to `true` prior to
24+
// using this package.
2025
var DecodeStrict bool
2126

2227
// Keyfunc will be used by the Parse methods as a callback function to supply
23-
// the key for verification. The function receives the parsed,
24-
// but unverified Token. This allows you to use properties in the
25-
// Header of the token (such as `kid`) to identify which key to use.
28+
// the key for verification. The function receives the parsed, but unverified
29+
// Token. This allows you to use properties in the Header of the token (such as
30+
// `kid`) to identify which key to use.
2631
type Keyfunc func(*Token) (interface{}, error)
2732

28-
// Token represents a JWT Token. Different fields will be used depending on whether you're
29-
// creating or parsing/verifying a token.
33+
// Token represents a JWT Token. Different fields will be used depending on
34+
// whether you're creating or parsing/verifying a token.
3035
type Token struct {
31-
Raw string // The raw token. Populated when you Parse a token
32-
Method SigningMethod // The signing method used or to be used
33-
Header map[string]interface{} // The first segment of the token
34-
Claims Claims // The second segment of the token
35-
Signature string // The third segment of the token. Populated when you Parse a token
36-
Valid bool // Is the token valid? Populated when you Parse/Verify a token
36+
Raw string // Raw contains the raw token. Populated when you [Parse] a token
37+
Method SigningMethod // Method is the signing method used or to be used
38+
Header map[string]interface{} // Header is the first segment of the token
39+
Claims Claims // Claims is the second segment of the token
40+
Signature string // Signature is the third segment of the token. Populated when you Parse a token
41+
Valid bool // Valid specifies if the token is valid. Populated when you Parse/Verify a token
3742
}
3843

39-
// New creates a new Token with the specified signing method and an empty map of claims.
44+
// New creates a new [Token] with the specified signing method and an empty map of
45+
// claims.
4046
func New(method SigningMethod) *Token {
4147
return NewWithClaims(method, MapClaims{})
4248
}
4349

44-
// NewWithClaims creates a new Token with the specified signing method and claims.
50+
// NewWithClaims creates a new [Token] with the specified signing method and
51+
// claims.
4552
func NewWithClaims(method SigningMethod, claims Claims) *Token {
4653
return &Token{
4754
Header: map[string]interface{}{
@@ -53,8 +60,8 @@ func NewWithClaims(method SigningMethod, claims Claims) *Token {
5360
}
5461
}
5562

56-
// SignedString creates and returns a complete, signed JWT.
57-
// The token is signed using the SigningMethod specified in the token.
63+
// SignedString creates and returns a complete, signed JWT. The token is signed
64+
// using the SigningMethod specified in the token.
5865
func (t *Token) SignedString(key interface{}) (string, error) {
5966
var sig, sstr string
6067
var err error
@@ -67,10 +74,9 @@ func (t *Token) SignedString(key interface{}) (string, error) {
6774
return strings.Join([]string{sstr, sig}, "."), nil
6875
}
6976

70-
// SigningString generates the signing string. This is the
71-
// most expensive part of the whole deal. Unless you
72-
// need this for something special, just go straight for
73-
// the SignedString.
77+
// SigningString generates the signing string. This is the most expensive part
78+
// of the whole deal. Unless you need this for something special, just go
79+
// straight for the SignedString.
7480
func (t *Token) SigningString() (string, error) {
7581
var err error
7682
var jsonValue []byte
@@ -90,36 +96,38 @@ func (t *Token) SigningString() (string, error) {
9096

9197
// Parse parses, validates, verifies the signature and returns the parsed token.
9298
// keyFunc will receive the parsed token and should return the cryptographic key
93-
// for verifying the signature.
94-
// The caller is strongly encouraged to set the WithValidMethods option to
95-
// validate the 'alg' claim in the token matches the expected algorithm.
96-
// For more details about the importance of validating the 'alg' claim,
97-
// see https://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries/
99+
// for verifying the signature. The caller is strongly encouraged to set the
100+
// WithValidMethods option to validate the 'alg' claim in the token matches the
101+
// expected algorithm. For more details about the importance of validating the
102+
// 'alg' claim, see
103+
// https://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries/
98104
func Parse(tokenString string, keyFunc Keyfunc, options ...ParserOption) (*Token, error) {
99105
return NewParser(options...).Parse(tokenString, keyFunc)
100106
}
101107

102108
// ParseWithClaims is a shortcut for NewParser().ParseWithClaims().
103109
//
104-
// Note: If you provide a custom claim implementation that embeds one of the standard claims (such as RegisteredClaims),
105-
// make sure that a) you either embed a non-pointer version of the claims or b) if you are using a pointer, allocate the
106-
// proper memory for it before passing in the overall claims, otherwise you might run into a panic.
110+
// Note: If you provide a custom claim implementation that embeds one of the
111+
// standard claims (such as RegisteredClaims), make sure that a) you either
112+
// embed a non-pointer version of the claims or b) if you are using a pointer,
113+
// allocate the proper memory for it before passing in the overall claims,
114+
// otherwise you might run into a panic.
107115
func ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc, options ...ParserOption) (*Token, error) {
108116
return NewParser(options...).ParseWithClaims(tokenString, claims, keyFunc)
109117
}
110118

111119
// EncodeSegment encodes a JWT specific base64url encoding with padding stripped
112120
//
113-
// Deprecated: In a future release, we will demote this function to a non-exported function, since it
114-
// should only be used internally
121+
// Deprecated: In a future release, we will demote this function to a
122+
// non-exported function, since it should only be used internally
115123
func EncodeSegment(seg []byte) string {
116124
return base64.RawURLEncoding.EncodeToString(seg)
117125
}
118126

119127
// DecodeSegment decodes a JWT specific base64url encoding with padding stripped
120128
//
121-
// Deprecated: In a future release, we will demote this function to a non-exported function, since it
122-
// should only be used internally
129+
// Deprecated: In a future release, we will demote this function to a
130+
// non-exported function, since it should only be used internally
123131
func DecodeSegment(seg string) ([]byte, error) {
124132
encoding := base64.RawURLEncoding
125133

types.go

Lines changed: 24 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -9,22 +9,23 @@ import (
99
"time"
1010
)
1111

12-
// TimePrecision sets the precision of times and dates within this library.
13-
// This has an influence on the precision of times when comparing expiry or
14-
// other related time fields. Furthermore, it is also the precision of times
15-
// when serializing.
12+
// TimePrecision sets the precision of times and dates within this library. This
13+
// has an influence on the precision of times when comparing expiry or other
14+
// related time fields. Furthermore, it is also the precision of times when
15+
// serializing.
1616
//
1717
// For backwards compatibility the default precision is set to seconds, so that
1818
// no fractional timestamps are generated.
1919
var TimePrecision = time.Second
2020

21-
// MarshalSingleStringAsArray modifies the behaviour of the ClaimStrings type, especially
22-
// its MarshalJSON function.
21+
// MarshalSingleStringAsArray modifies the behavior of the ClaimStrings type,
22+
// especially its MarshalJSON function.
2323
//
2424
// If it is set to true (the default), it will always serialize the type as an
25-
// array of strings, even if it just contains one element, defaulting to the behaviour
26-
// of the underlying []string. If it is set to false, it will serialize to a single
27-
// string, if it contains one element. Otherwise, it will serialize to an array of strings.
25+
// array of strings, even if it just contains one element, defaulting to the
26+
// behavior of the underlying []string. If it is set to false, it will serialize
27+
// to a single string, if it contains one element. Otherwise, it will serialize
28+
// to an array of strings.
2829
var MarshalSingleStringAsArray = true
2930

3031
// NumericDate represents a JSON numeric date value, as referenced at
@@ -58,9 +59,10 @@ func (date NumericDate) MarshalJSON() (b []byte, err error) {
5859
// For very large timestamps, UnixNano would overflow an int64, but this
5960
// function requires nanosecond level precision, so we have to use the
6061
// following technique to get round the issue:
62+
//
6163
// 1. Take the normal unix timestamp to form the whole number part of the
6264
// output,
63-
// 2. Take the result of the Nanosecond function, which retuns the offset
65+
// 2. Take the result of the Nanosecond function, which returns the offset
6466
// within the second of the particular unix time instance, to form the
6567
// decimal part of the output
6668
// 3. Concatenate them to produce the final result
@@ -72,9 +74,10 @@ func (date NumericDate) MarshalJSON() (b []byte, err error) {
7274
return output, nil
7375
}
7476

75-
// UnmarshalJSON is an implementation of the json.RawMessage interface and deserializses a
76-
// NumericDate from a JSON representation, i.e. a json.Number. This number represents an UNIX epoch
77-
// with either integer or non-integer seconds.
77+
// UnmarshalJSON is an implementation of the json.RawMessage interface and
78+
// deserializes a [NumericDate] from a JSON representation, i.e. a
79+
// [json.Number]. This number represents an UNIX epoch with either integer or
80+
// non-integer seconds.
7881
func (date *NumericDate) UnmarshalJSON(b []byte) (err error) {
7982
var (
8083
number json.Number
@@ -95,8 +98,9 @@ func (date *NumericDate) UnmarshalJSON(b []byte) (err error) {
9598
return nil
9699
}
97100

98-
// ClaimStrings is basically just a slice of strings, but it can be either serialized from a string array or just a string.
99-
// This type is necessary, since the "aud" claim can either be a single string or an array.
101+
// ClaimStrings is basically just a slice of strings, but it can be either
102+
// serialized from a string array or just a string. This type is necessary,
103+
// since the "aud" claim can either be a single string or an array.
100104
type ClaimStrings []string
101105

102106
func (s *ClaimStrings) UnmarshalJSON(data []byte) (err error) {
@@ -133,10 +137,11 @@ func (s *ClaimStrings) UnmarshalJSON(data []byte) (err error) {
133137
}
134138

135139
func (s ClaimStrings) MarshalJSON() (b []byte, err error) {
136-
// This handles a special case in the JWT RFC. If the string array, e.g. used by the "aud" field,
137-
// only contains one element, it MAY be serialized as a single string. This may or may not be
138-
// desired based on the ecosystem of other JWT library used, so we make it configurable by the
139-
// variable MarshalSingleStringAsArray.
140+
// This handles a special case in the JWT RFC. If the string array, e.g.
141+
// used by the "aud" field, only contains one element, it MAY be serialized
142+
// as a single string. This may or may not be desired based on the ecosystem
143+
// of other JWT library used, so we make it configurable by the variable
144+
// MarshalSingleStringAsArray.
140145
if len(s) == 1 && !MarshalSingleStringAsArray {
141146
return json.Marshal(s[0])
142147
}

validator.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,8 @@ import (
99
// a [Parser] during parsing and can be modified with various parser options.
1010
//
1111
// Note: This struct is intentionally not exported (yet) as we want to
12-
// internally finalize its API. In the future, we might make it publicly available.
12+
// internally finalize its API. In the future, we might make it publicly
13+
// available.
1314
type validator struct {
1415
// leeway is an optional leeway that can be provided to account for clock skew.
1516
leeway time.Duration

0 commit comments

Comments
 (0)