-
Notifications
You must be signed in to change notification settings - Fork 46
/
parse.go
85 lines (73 loc) · 1.93 KB
/
parse.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package jwt
import (
"bytes"
"encoding/base64"
"encoding/json"
)
// Parse decodes a token and verifies it's signature.
func Parse(raw []byte, verifier Verifier) (*Token, error) {
token, err := ParseNoVerify(raw)
if err != nil {
return nil, err
}
if err := verifier.Verify(token); err != nil {
return nil, err
}
return token, nil
}
// ParseClaims decodes a token claims and verifies it's signature.
func ParseClaims(raw []byte, verifier Verifier, claims any) error {
token, err := Parse(raw, verifier)
if err != nil {
return err
}
return token.DecodeClaims(claims)
}
// ParseNoVerify decodes a token from a raw bytes.
// NOTE: Consider to use Parse with a verifier to verify token signature.
func ParseNoVerify(raw []byte) (*Token, error) {
return parse(raw)
}
func parse(token []byte) (*Token, error) {
// "eyJ" is `{"` which is begin of every JWT token.
// Quick check for the invalid input.
if !bytes.HasPrefix(token, []byte("eyJ")) {
return nil, ErrInvalidFormat
}
dot1 := bytes.IndexByte(token, '.')
dot2 := bytes.LastIndexByte(token, '.')
if dot2 <= dot1 {
return nil, ErrInvalidFormat
}
buf := make([]byte, len(token))
headerN, err := b64Decode(buf, token[:dot1])
if err != nil {
return nil, ErrInvalidFormat
}
var header Header
if err := json.Unmarshal(buf[:headerN], &header); err != nil {
return nil, ErrInvalidFormat
}
claimsN, err := b64Decode(buf[headerN:], token[dot1+1:dot2])
if err != nil {
return nil, ErrInvalidFormat
}
claims := buf[headerN : headerN+claimsN]
signN, err := b64Decode(buf[headerN+claimsN:], token[dot2+1:])
if err != nil {
return nil, ErrInvalidFormat
}
signature := buf[headerN+claimsN : headerN+claimsN+signN]
tk := &Token{
raw: token,
dot1: dot1,
dot2: dot2,
signature: signature,
header: header,
claims: claims,
}
return tk, nil
}
func b64Decode(dst, src []byte) (n int, err error) {
return base64.RawURLEncoding.Decode(dst, src)
}