-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjwt.go
198 lines (178 loc) · 5.41 KB
/
jwt.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
// Tideland Go JSON Web Token
//
// Copyright (C) 2016-2021 Frank Mueller / Tideland / Oldenburg / Germany
//
// All rights reserved. Use of this source code is governed
// by the new BSD license.
package jwt // import "tideland.dev/go/jwt"
//--------------------
// IMPORTS
//--------------------
import (
"encoding/base64"
"encoding/json"
"fmt"
"strings"
"time"
)
//--------------------
// JSON WEB TOKEN
//--------------------
// jwtHeader contains the JWT header fields.
type jwtHeader struct {
Algorithm string `json:"alg"`
Type string `json:"typ"`
}
// JWT manages the parts of a JSON Web Token and the access to those.
type JWT struct {
claims Claims
key Key
algorithm Algorithm
token string
}
// Encode creates a JSON Web Token for the given claims
// based on key and algorithm.
func Encode(claims Claims, key Key, algorithm Algorithm) (*JWT, error) {
jwt := &JWT{
claims: claims,
key: key,
algorithm: algorithm,
}
headerPart, err := marshallAndEncode(jwtHeader{string(algorithm), "JWT"})
if err != nil {
return nil, fmt.Errorf("cannot encode the header: %v", err)
}
claimsPart, err := marshallAndEncode(claims)
if err != nil {
return nil, fmt.Errorf("cannot encode the claims: %v", err)
}
dataParts := headerPart + "." + claimsPart
signaturePart, err := signAndEncode([]byte(dataParts), key, algorithm)
if err != nil {
return nil, fmt.Errorf("cannot encode the signature: %v", err)
}
jwt.token = dataParts + "." + signaturePart
return jwt, nil
}
// Decode creates a token out of a string without verification.
func Decode(token string) (*JWT, error) {
parts := strings.Split(token, ".")
if len(parts) != 3 {
return nil, fmt.Errorf("cannot decode the parts")
}
var header jwtHeader
err := decodeAndUnmarshall(parts[0], &header)
if err != nil {
return nil, fmt.Errorf("cannot decode the header: %v", err)
}
var claims Claims
err = decodeAndUnmarshall(parts[1], &claims)
if err != nil {
return nil, fmt.Errorf("cannot decode the claims: %v", err)
}
return &JWT{
claims: claims,
algorithm: Algorithm(header.Algorithm),
token: token,
}, nil
}
// Verify creates a token out of a string and varifies it against
// the passed key.
func Verify(token string, key Key) (*JWT, error) {
parts := strings.Split(token, ".")
if len(parts) != 3 {
return nil, fmt.Errorf("cannot verify the parts")
}
var header jwtHeader
err := decodeAndUnmarshall(parts[0], &header)
if err != nil {
return nil, fmt.Errorf("cannot verify the header: %v", err)
}
err = decodeAndVerify(parts, key, Algorithm(header.Algorithm))
if err != nil {
return nil, fmt.Errorf("cannot verify the signature: %v", err)
}
var claims Claims
err = decodeAndUnmarshall(parts[1], &claims)
if err != nil {
return nil, fmt.Errorf("cannot verify the claims: %v", err)
}
return &JWT{
claims: claims,
key: key,
algorithm: Algorithm(header.Algorithm),
token: token,
}, nil
}
// Claims returns the claims payload of the token.
func (jwt *JWT) Claims() Claims {
return jwt.claims
}
// Key returns the key of the token only when it is a result of encoding or verification.
func (jwt *JWT) Key() (Key, error) {
if jwt.key == nil {
return nil, fmt.Errorf("no key available, only after encoding or verifying")
}
return jwt.key, nil
}
// Algorithm returns the algorithm of the token after encoding, decoding, or verification.
func (jwt *JWT) Algorithm() Algorithm {
return jwt.algorithm
}
// IsValid is a convenience method checking the registered claims if the token is valid.
func (jwt *JWT) IsValid(leeway time.Duration) bool {
return jwt.claims.IsValid(leeway)
}
// String implements the fmt.Stringer interface.
func (jwt *JWT) String() string {
return jwt.token
}
//--------------------
// HELPERS
//--------------------
// marshallAndEncode marshals the passed value to JSON and
// creates a BASE64 string out of it.
func marshallAndEncode(value interface{}) (string, error) {
jsonValue, err := json.Marshal(value)
if err != nil {
return "", fmt.Errorf("error marshalling to JSON: %v", err)
}
encoded := base64.RawURLEncoding.EncodeToString(jsonValue)
return encoded, nil
}
// decodeAndUnmarshall decodes a BASE64 encoded JSON string and
// unmarshals it into the passed value.
func decodeAndUnmarshall(part string, value interface{}) error {
decoded, err := base64.RawURLEncoding.DecodeString(part)
if err != nil {
return fmt.Errorf("part of the token contains invalid data: %v", err)
}
err = json.Unmarshal(decoded, value)
if err != nil {
return fmt.Errorf("error unmarshalling from JSON: %v", err)
}
return nil
}
// signAndEncode creates the signature for the data part (header and
// payload) of the token using the passed key and algorithm. The result
// is then encoded to BASE64.
func signAndEncode(data []byte, key Key, algorithm Algorithm) (string, error) {
sig, err := algorithm.Sign(data, key)
if err != nil {
return "", err
}
encoded := base64.RawURLEncoding.EncodeToString(sig)
return encoded, nil
}
// decodeAndVerify decodes a BASE64 encoded signature and verifies
// the correct signing of the data part (header and payload) using the
// passed key and algorithm.
func decodeAndVerify(parts []string, key Key, algorithm Algorithm) error {
data := []byte(parts[0] + "." + parts[1])
sig, err := base64.RawURLEncoding.DecodeString(parts[2])
if err != nil {
return fmt.Errorf("part of the token contains invalid data: %v", err)
}
return algorithm.Verify(data, sig, key)
}
// EOF