Skip to content

Commit 7c726ab

Browse files
author
zhouyiheng.go
committed
feat: custom json and base64 encoders for Token and Parser
1 parent b88a60f commit 7c726ab

8 files changed

+196
-21
lines changed

encoder.go

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
package jwt
2+
3+
// Base64Encoder is an interface that allows to implement custom Base64 encoding/decoding algorithms.
4+
type Base64Encoder interface {
5+
EncodeToString(src []byte) string
6+
DecodeString(s string) ([]byte, error)
7+
}
8+
9+
// JSONEncoder is an interface that allows to implement custom JSON encoding/decoding algorithms.
10+
type JSONEncoder interface {
11+
Marshal(v any) ([]byte, error)
12+
Unmarshal(data []byte, v any) error
13+
}

encoder_test.go

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package jwt_test
2+
3+
import (
4+
"encoding/base64"
5+
"encoding/json"
6+
)
7+
8+
type customJSONEncoder struct{}
9+
10+
func (s *customJSONEncoder) Marshal(v any) ([]byte, error) {
11+
return json.Marshal(v)
12+
}
13+
14+
func (s *customJSONEncoder) Unmarshal(data []byte, v any) error {
15+
return json.Unmarshal(data, v)
16+
}
17+
18+
type customBase64Encoder struct{}
19+
20+
func (s *customBase64Encoder) EncodeToString(data []byte) string {
21+
return base64.StdEncoding.EncodeToString(data)
22+
}
23+
24+
func (s *customBase64Encoder) DecodeString(data string) ([]byte, error) {
25+
return base64.RawURLEncoding.DecodeString(data)
26+
}

parser.go

+36-10
Original file line numberDiff line numberDiff line change
@@ -12,17 +12,25 @@ type Parser struct {
1212
// If populated, only these methods will be considered valid.
1313
validMethods []string
1414

15-
// Use JSON Number format in JSON decoder.
15+
// Use JSON Number format in JSON decoder. This field is disabled when using a custom json encoder.
1616
useJSONNumber bool
1717

1818
// Skip claims validation during token parsing.
1919
skipClaimsValidation bool
2020

2121
validator *validator
2222

23+
// This field is disabled when using a custom base64 encoder.
2324
decodeStrict bool
2425

26+
// This field is disabled when using a custom base64 encoder.
2527
decodePaddingAllowed bool
28+
29+
// Custom base64 encoder.
30+
base64Encoder Base64Encoder
31+
32+
// Custom json encoder.
33+
jsonEncoder JSONEncoder
2634
}
2735

2836
// NewParser creates a new Parser with the specified options
@@ -135,7 +143,12 @@ func (p *Parser) ParseUnverified(tokenString string, claims Claims) (token *Toke
135143
}
136144
return token, parts, newError("could not base64 decode header", ErrTokenMalformed, err)
137145
}
138-
if err = json.Unmarshal(headerBytes, &token.Header); err != nil {
146+
if p.jsonEncoder != nil {
147+
err = p.jsonEncoder.Unmarshal(headerBytes, &token.Header)
148+
} else {
149+
err = json.Unmarshal(headerBytes, &token.Header)
150+
}
151+
if err != nil {
139152
return token, parts, newError("could not JSON decode header", ErrTokenMalformed, err)
140153
}
141154

@@ -146,21 +159,30 @@ func (p *Parser) ParseUnverified(tokenString string, claims Claims) (token *Toke
146159
if claimBytes, err = p.DecodeSegment(parts[1]); err != nil {
147160
return token, parts, newError("could not base64 decode claim", ErrTokenMalformed, err)
148161
}
149-
dec := json.NewDecoder(bytes.NewBuffer(claimBytes))
150-
if p.useJSONNumber {
151-
dec.UseNumber()
152-
}
162+
153163
// JSON Decode. Special case for map type to avoid weird pointer behavior
154-
if c, ok := token.Claims.(MapClaims); ok {
155-
err = dec.Decode(&c)
164+
mapClaims, isMapClaims := token.Claims.(MapClaims)
165+
if p.jsonEncoder != nil {
166+
if isMapClaims {
167+
err = p.jsonEncoder.Unmarshal(claimBytes, &mapClaims)
168+
} else {
169+
err = p.jsonEncoder.Unmarshal(claimBytes, &claims)
170+
}
156171
} else {
157-
err = dec.Decode(&claims)
172+
decoder := json.NewDecoder(bytes.NewBuffer(claimBytes))
173+
if p.useJSONNumber {
174+
decoder.UseNumber()
175+
}
176+
if isMapClaims {
177+
err = decoder.Decode(&mapClaims)
178+
} else {
179+
err = decoder.Decode(&claims)
180+
}
158181
}
159182
// Handle decode error
160183
if err != nil {
161184
return token, parts, newError("could not JSON decode claim", ErrTokenMalformed, err)
162185
}
163-
164186
// Lookup signature method
165187
if method, ok := token.Header["alg"].(string); ok {
166188
if token.Method = GetSigningMethod(method); token.Method == nil {
@@ -177,6 +199,10 @@ func (p *Parser) ParseUnverified(tokenString string, claims Claims) (token *Toke
177199
// take into account whether the [Parser] is configured with additional options,
178200
// such as [WithStrictDecoding] or [WithPaddingAllowed].
179201
func (p *Parser) DecodeSegment(seg string) ([]byte, error) {
202+
if p.base64Encoder != nil {
203+
return p.base64Encoder.DecodeString(seg)
204+
}
205+
180206
encoding := base64.RawURLEncoding
181207

182208
if p.decodePaddingAllowed {

parser_option.go

+13
Original file line numberDiff line numberDiff line change
@@ -125,3 +125,16 @@ func WithStrictDecoding() ParserOption {
125125
p.decodeStrict = true
126126
}
127127
}
128+
129+
// WithJSONEncoder supports
130+
func WithJSONEncoder(enc JSONEncoder) ParserOption {
131+
return func(p *Parser) {
132+
p.jsonEncoder = enc
133+
}
134+
}
135+
136+
func WithBase64Encoder(enc Base64Encoder) ParserOption {
137+
return func(p *Parser) {
138+
p.base64Encoder = enc
139+
}
140+
}

0 commit comments

Comments
 (0)