-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathjwt.go
261 lines (206 loc) · 5.99 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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
package webutils
import (
"context"
"crypto/rsa"
"encoding/json"
"net/http"
"strings"
"github.com/cyberhorsey/errors"
jwt "github.com/golang-jwt/jwt/v4"
echo "github.com/labstack/echo/v4"
)
// ContextKey is a key to add to request contexts
type ContextKey string // keys can not be untyped strings
// Context keys
const (
ContextKeyJWT = "jwt"
ContextKeyJWTClaims = "jwt-claims"
)
// JWTType is a type of token
type JWTType string
const (
// JWTAccess is a short-lived access token to grant access to the application
JWTAccess JWTType = "access"
// JWTRefresh is a long-lived refresh token used to gain access tokens
JWTRefresh JWTType = "refresh"
)
// Claims contains jwt.Token.Claims data
type Claims struct {
jwt.StandardClaims
Type string `json:"type"`
UserID uint `json:"user_id"`
Username string `json:"username"`
}
// AuthorizedUserID returns the authorized UserID from the claims
func (c *Claims) AuthorizedUserID() uint {
return c.UserID
}
// Authorized indicates whether the claims are valid
func (c *Claims) Authorized() error {
if err := c.StandardClaims.Valid(); err != nil {
return err
}
return nil
}
// CreateJWT creates a JWT string for the provided Claims, signed with the RSA key.
func CreateJWT(claims Claims, key *rsa.PrivateKey) (string, error) {
if err := claims.Valid(); err != nil {
return "", errors.Wrap(err, "claims.Valid()")
}
if key == nil {
return "", ErrNoKey
}
token := jwt.NewWithClaims(jwt.SigningMethodRS512, claims)
return token.SignedString(key)
}
// GetClaimsFromJWT parses and returns the Claims from the provided RSA encrypted token string
func GetClaimsFromJWT(token string, key *rsa.PublicKey) (*Claims, error) {
if token == "" {
return nil, ErrNoToken
}
if key == nil {
return nil, ErrNoKey
}
claims := &Claims{}
parsedToken, err := jwt.ParseWithClaims(token, claims, func(token *jwt.Token) (interface{}, error) {
return key, nil
})
if err != nil {
return nil, err
}
if !parsedToken.Valid {
return nil, ErrInvalidToken
}
return claims, nil
}
// GetClaimsFromJWTToken creates Claims from a *jwt.Token
func GetClaimsFromJWTToken(token *jwt.Token) (*Claims, error) {
if token == nil {
return nil, ErrNoToken
}
output, err := json.Marshal(token.Claims)
if err != nil {
return nil, err
}
claims := &Claims{}
err = json.Unmarshal(output, claims)
if err != nil {
return nil, err
}
return claims, nil
}
var defaultJWTMiddlewareSkipper = func(c echo.Context) bool {
switch c.Request().URL.Path {
case "/":
return true
case "/health":
return true
}
return false
}
// JWTMiddlewareOpts contains the options for ConfigureJWTMiddleware
type JWTMiddlewareOpts struct {
PublicKey func(c echo.Context) (*rsa.PublicKey, error)
Skipper func(c echo.Context) bool
}
// jwtMiddleware is a wrapper for echo jwt middleware
type jwtMiddleware struct {
PublicKey func(c echo.Context) (*rsa.PublicKey, error)
Skipper func(c echo.Context) bool
}
// ConfigureJWTMiddleware configures JWT middleware
func ConfigureJWTMiddleware(opts JWTMiddlewareOpts) (echo.MiddlewareFunc, error) {
mw := jwtMiddleware(opts)
if mw.PublicKey == nil {
return nil, ErrNoPublicKeyFunction
}
if mw.Skipper == nil {
mw.Skipper = defaultJWTMiddlewareSkipper
}
return mw.Handler, nil
}
func (mw *jwtMiddleware) Handler(
next echo.HandlerFunc,
) echo.HandlerFunc {
return func(c echo.Context) error {
// skip jwt?
if mw.Skipper(c) {
return next(c)
}
pk, err := mw.PublicKey(c)
if err != nil {
if errors.GetType(err) != errors.NoType {
return LogAndRenderErrors(c, ConvertErrorToStatusCode(err), err)
}
return LogAndRenderUnexpectedError(c, err)
}
claims, err := GetClaimsFromBearerJWT(c.Request().Header.Get("Authorization"), pk)
if err != nil {
return LogAndRenderErrors(c, http.StatusUnauthorized, errors.Wrap(err, "GetClaimsFromBearerJWT"))
}
if claims.Type != string(JWTAccess) {
return LogAndRenderErrors(c, http.StatusUnauthorized, ErrAuthorizationAccessTokenRequired)
}
c.Set(ContextKeyJWTClaims, claims)
ctx := context.WithValue(c.Request().Context(), ContextKey(ContextKeyJWTClaims), claims)
header := c.Request().Header.Get(echo.HeaderAuthorization)
jwt := header[len(bearerPrefix):]
c.Set(ContextKeyJWT, jwt)
ctx = context.WithValue(ctx, ContextKey(ContextKeyJWT), jwt)
c.SetRequest(c.Request().WithContext(ctx))
return next(c)
}
}
const (
bearerPrefix = `Bearer `
)
// GetClaimsFromBearerJWT gets claims from a Bearer JWT
func GetClaimsFromBearerJWT(
token string,
jwtPublicKey *rsa.PublicKey,
) (*Claims, error) {
if token == "" {
return nil, ErrAuthorizationAccessTokenRequired
}
if strings.HasPrefix(token, bearerPrefix) {
claims, err := GetClaimsFromJWT(token[len(bearerPrefix):], jwtPublicKey)
if err != nil {
return nil, errors.WithCause(ErrAuthorizationTokenInvalid, err)
}
return claims, nil
}
// enforce Bearer prefix
return nil, ErrAuthorizationBearerRequired
}
// GetJWTClaimsFromEchoContext retrieves the *webutils.Claims from the provided echo.Context.
func GetJWTClaimsFromEchoContext(c echo.Context) (*Claims, error) {
claims, ok := c.Get(ContextKeyJWTClaims).(*Claims)
if !ok {
return nil, ErrNoJWTClaimsInContext
}
return claims, nil
}
// GetJWTFromEchoContext retrieves the JWT from the provided echo.Context.
func GetJWTFromEchoContext(c echo.Context) (string, error) {
jwt, ok := c.Get(ContextKeyJWT).(string)
if !ok {
return "", ErrNoJWTInContext
}
return jwt, nil
}
// GetJWTFromContext retrieves the JWT from the provided context.Context.
func GetJWTFromContext(ctx context.Context) (string, error) {
jwt, ok := ctx.Value(ContextKey(ContextKeyJWT)).(string)
if !ok {
return "", ErrNoJWTInContext
}
return jwt, nil
}
// GetJWTClaimsFromContext retrieves the *webutils.Claims from the provided context.Context.
func GetJWTClaimsFromContext(ctx context.Context) (*Claims, error) {
claims, ok := ctx.Value(ContextKey(ContextKeyJWTClaims)).(*Claims)
if !ok || claims == nil {
return nil, ErrNoJWTClaimsInContext
}
return claims, nil
}