This repository has been archived by the owner on Aug 19, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
jwt.go
206 lines (189 loc) · 5.58 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
199
200
201
202
203
204
205
206
package jwc
// https://tools.ietf.org/html/rfc7519
import (
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"strings"
)
const (
// JWTType - jwt type
jwtType = "JWT"
)
var (
// JWTBase64Encoding - encoding used to encode and decode tokens
JWTBase64Encoding = base64.URLEncoding.WithPadding(base64.NoPadding)
// ErrJWTUnparsable -
ErrJWTUnparsable = errors.New("ErrJWTUnparsable")
)
// NewJWT - creates a new JWT from the payload
func NewJWT(payload JWTPayload, signAlgo Algorithm) (*JWT, error) {
if signAlgo != RS256 && signAlgo != PS256 {
return nil, ErrUnsupportedAlgorithm
}
return &JWT{
Header: JWTHeader{
Algorithm: signAlgo,
Type: jwtType,
},
Payload: payload,
}, nil
}
// TokenID -
type TokenID string
// JWT - JSON Web Token
type JWT struct {
Header JWTHeader
Payload JWTPayload
}
// JWTHeader JWT header
type JWTHeader struct {
Algorithm Algorithm `json:"alg"`
Type string `json:"typ,omitempty"`
ContentType string `json:"cty,omitempty"`
SignKeyID JWKID `json:"kid,omitempty"`
JWKURI string `json:"jku,omitempty"`
Critical []string `jon:"crit,omitempty"`
Zip string `json:"zip,omitempty"`
JWK *JWK `json:"jwk,omitmepty"`
}
// JWTPayload - JWT payload
type JWTPayload struct {
RegisteredClaims
PrivateClaims `json:"priv"`
}
// RegisteredClaims - common data embedded in JWT
type RegisteredClaims struct {
ExpirationTimestamp int64 `json:"exp,omitempty"`
IssuedAtTimestamp int64 `json:"iat,omitempty"`
Issuer string `json:"iss,omitempty"`
Subject string `json:"sub,omitempty"`
Audiance string `json:"aud,omitempty"`
}
// PrivateClaims - app specific data embedded in JWT
type PrivateClaims map[string]interface{}
// Encode - encode jwt into signed base64 string
func (jwt *JWT) Encode(signKeyID JWKID, signKey crypto.PrivateKey) (string, error) {
jwt.Header.SignKeyID = signKeyID
// base64 encoding of the header
headerJSON, err := json.Marshal(jwt.Header)
if err != nil {
return "", err
}
headerBase64 := JWTBase64Encoding.EncodeToString(headerJSON)
payloadJSON, err := json.Marshal(jwt.Payload)
if err != nil {
return "", err
}
payloadBase64 := JWTBase64Encoding.EncodeToString(payloadJSON)
plainPart := fmt.Sprintf("%s.%s", headerBase64, payloadBase64)
hash := sha256.Sum256([]byte(plainPart))
var signature []byte
switch jwt.Header.Algorithm {
case RS256:
signature, err = rsa.SignPKCS1v15(rand.Reader, signKey.(*rsa.PrivateKey), crypto.SHA256, hash[:])
if err != nil {
return "", err
}
break
case PS256:
signature, err = rsa.SignPSS(rand.Reader, signKey.(*rsa.PrivateKey), crypto.SHA256, hash[:], nil)
if err != nil {
return "", err
}
}
signatureBase64 := JWTBase64Encoding.EncodeToString(signature)
encoded := fmt.Sprintf("%s.%s", plainPart, signatureBase64)
return encoded, nil
}
// ExtractJWTParts return base64 encoded string of the header, the payload and the signature
func ExtractJWTParts(jwtStr string) (headerBase64, payloadBase64, signatureBase64 string, err error) {
jwtStrSplit := strings.Split(jwtStr, ".")
if len(jwtStrSplit) != 3 {
return "", "", "", ErrJWTUnparsable
}
headerBase64, payloadBase64, signatureBase64 = jwtStrSplit[0], jwtStrSplit[1], jwtStrSplit[2]
return headerBase64, payloadBase64, signatureBase64, nil
}
// VerifyJWT - validate the jwt integerity
func VerifyJWT(jwtStr string, signKey crypto.PublicKey) error {
headerBase64, payloadBase64, signatureBase64, err := ExtractJWTParts(jwtStr)
if err != nil {
return err
}
jwt, err := decodeJWT(headerBase64, payloadBase64)
if err != nil {
return err
}
return verifyJWT(headerBase64, payloadBase64, signatureBase64, signKey, jwt.Header.Algorithm)
}
func verifyJWT(headerBase64, payloadBase64, signatureBase64 string, publicKey crypto.PublicKey, algo Algorithm) error {
plainPart := fmt.Sprintf("%s.%s", headerBase64, payloadBase64)
hash := sha256.Sum256([]byte(plainPart))
signature, err := JWTBase64Encoding.DecodeString(signatureBase64)
if err != nil {
return err
}
switch algo {
case RS256:
return rsa.VerifyPKCS1v15(publicKey.(*rsa.PublicKey), crypto.SHA256, hash[:], signature)
case PS256:
return rsa.VerifyPSS(publicKey.(*rsa.PublicKey), crypto.SHA256, hash[:], signature, nil)
default:
return ErrUnsupportedAlgorithm
}
}
// DecodeJWT - parse a base64 string into a jwt
func DecodeJWT(jwtStr string) (*JWT, error) {
headerBase64, payloadBase64, _, err := ExtractJWTParts(jwtStr)
if err != nil {
return nil, err
}
return decodeJWT(headerBase64, payloadBase64)
}
func decodeJWT(headerBase64, payloadBase64 string) (*JWT, error) {
headerJSON, err := JWTBase64Encoding.DecodeString(headerBase64)
if err != nil {
return nil, err
}
payloadJSON, err := JWTBase64Encoding.DecodeString(payloadBase64)
if err != nil {
return nil, err
}
var header JWTHeader
err = json.Unmarshal(headerJSON, &header)
if err != nil {
return nil, err
}
var payload JWTPayload
err = json.Unmarshal(payloadJSON, &payload)
if err != nil {
return nil, err
}
jwt := JWT{
Header: header,
Payload: payload,
}
return &jwt, nil
}
// DecodeVerifyJWT - parse a base64 string into a jwt
func DecodeVerifyJWT(jwtStr string, signKey crypto.PublicKey) (*JWT, error) {
headerBase64, payloadBase64, signatureBase64, err := ExtractJWTParts(jwtStr)
if err != nil {
return nil, err
}
jwt, err := decodeJWT(headerBase64, payloadBase64)
if err != nil {
return nil, err
}
err = verifyJWT(headerBase64, payloadBase64, signatureBase64, signKey, jwt.Header.Algorithm)
if err != nil {
return nil, err
}
return jwt, nil
}