forked from cristalhq/jwt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparse.go
86 lines (73 loc) · 1.99 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
86
package jwt
import (
"bytes"
"encoding/base64"
"encoding/json"
)
// ParseString decodes a token.
func ParseString(raw string) (*Token, error) {
return Parse([]byte(raw))
}
// Parse decodes a token from a raw bytes.
func Parse(raw []byte) (*Token, error) {
return parse(raw)
}
// ParseAndVerifyString decodes a token and verifies it's signature.
func ParseAndVerifyString(raw string, verifier Verifier) (*Token, error) {
return ParseAndVerify([]byte(raw), verifier)
}
// ParseAndVerify decodes a token and verifies it's signature.
func ParseAndVerify(raw []byte, verifier Verifier) (*Token, error) {
token, err := parse(raw)
if err != nil {
return nil, err
}
if !constTimeAlgEqual(token.Header().Algorithm, verifier.Algorithm()) {
return nil, ErrAlgorithmMismatch
}
if err := verifier.Verify(token.Payload(), token.Signature()); err != nil {
return nil, err
}
return token, nil
}
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
}
var b64Decode = base64.RawURLEncoding.Decode