-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjwt.go
212 lines (192 loc) · 4.31 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
207
208
209
210
211
212
package jwt
import (
"bytes"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"errors"
"fmt"
"strings"
"github.com/golang-jwt/jwt/v4"
)
type (
Session struct {
Keys *KeyPair
Options *SessionOptions
}
SessionOptions struct {
UserIdKeyName string // defaults to "UserId"
SessionIdKeyName string // defaults to "SessionId"
}
KeyPair struct {
*rsa.PrivateKey
*rsa.PublicKey
}
)
func NewSession(options *SessionOptions) *Session {
if options == nil {
options = &SessionOptions{}
}
return &Session{
Keys: NewKeyPair(),
Options: options,
}
}
func (s *Session) SetString(input string) (err error) {
if s.Keys == nil {
s.Keys = NewKeyPair()
}
return s.Keys.SetString(input)
}
func (s Session) String() string {
if s.Keys == nil {
return ""
}
return s.Keys.String()
}
func (s Session) uidKey() string {
if s.Options != nil && s.Options.UserIdKeyName != "" {
return s.Options.UserIdKeyName
}
return "UserId"
}
func (s Session) sidKey() string {
if s.Options != nil && s.Options.SessionIdKeyName != "" {
return s.Options.SessionIdKeyName
}
return "SessionId"
}
func (s Session) MustSign(claims map[string]interface{}) string {
token, err := s.Sign(claims)
if err != nil {
panic(err)
}
return token
}
func (s Session) Sign(claims map[string]interface{}) (string, error) {
token := jwt.NewWithClaims(jwt.SigningMethodRS256, jwt.MapClaims(claims))
return token.SignedString(s.Keys.PrivateKey)
}
func (s Session) MustParse(token string) map[string]interface{} {
claims, err := s.Parse(token)
if err != nil {
panic(err)
}
return claims
}
func (s Session) Parse(tokenString string) (map[string]interface{}, error) {
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
return s.Keys.PublicKey, nil
})
if err != nil {
return nil, err
}
claims, ok := token.Claims.(jwt.MapClaims)
if !ok || !token.Valid {
return nil, errors.New("invalid token")
}
return claims, nil
}
func (s Session) GenerateAuthorization(userId, sessionId string) (string, error) {
token := jwt.NewWithClaims(jwt.SigningMethodRS256, jwt.MapClaims{
s.uidKey(): userId,
s.sidKey(): sessionId,
})
auth, err := token.SignedString(s.Keys.PrivateKey)
if err != nil {
return "", err
}
return "Bearer " + auth, nil
}
func (s Session) ParseAuthorization(auth string) (userId, sessionId string, ok bool) {
parts := strings.SplitN(auth, " ", 2)
if parts[0] != "Bearer" {
return
}
claims, e := parseToken(s.Keys.PublicKey, parts[1])
if e != nil {
return
}
var uid, sid interface{}
uid, ok = claims[s.uidKey()]
if !ok {
return
}
switch v := uid.(type) {
case string:
userId = v
default:
ok = false
return
}
sid, ok = claims[s.sidKey()]
if !ok {
return
}
switch v := sid.(type) {
case string:
sessionId = v
default:
ok = false
return
}
ok = true
return
}
func NewKeyPair() *KeyPair {
privatekey, _ := rsa.GenerateKey(rand.Reader, 2048)
return &KeyPair{privatekey, &privatekey.PublicKey}
}
func (kp *KeyPair) SetString(input string) (err error) {
if input == "" {
return nil
}
privKey, err := jwt.ParseRSAPrivateKeyFromPEM([]byte(input))
if err != nil {
return err
}
pubKeyBytes, err := x509.MarshalPKIXPublicKey(&privKey.PublicKey)
if err != nil {
return err
}
publicKey, err := jwt.ParseRSAPublicKeyFromPEM(pem.EncodeToMemory(
&pem.Block{
Type: "RSA PUBLIC KEY",
Bytes: pubKeyBytes,
},
))
kp.PrivateKey = privKey
kp.PublicKey = publicKey
return nil
}
func (kp KeyPair) String() string {
var buffer bytes.Buffer
err := pem.Encode(&buffer, &pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: x509.MarshalPKCS1PrivateKey(kp.PrivateKey),
})
if err != nil {
return ""
}
return "\n" + buffer.String()
}
func parseToken(pubKey *rsa.PublicKey, input string) (jwt.MapClaims, error) {
token, err := jwt.Parse(input, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
return pubKey, nil
})
if err != nil {
return nil, err
}
claims, ok := token.Claims.(jwt.MapClaims)
if !ok || !token.Valid {
return nil, errors.New("invalid token")
}
return claims, nil
}