-
Notifications
You must be signed in to change notification settings - Fork 7
/
jwt.go
234 lines (186 loc) · 6.65 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
// Package jwt provides JWT Auth handlers.
package jwt
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"strings"
"time"
"github.com/golang-jwt/jwt"
"github.com/nexmoinc/gosrvlib/pkg/httputil"
"github.com/nexmoinc/gosrvlib/pkg/logging"
"go.uber.org/zap"
"golang.org/x/crypto/bcrypt"
)
const (
// DefaultExpirationTime is the default JWT expiration time.
DefaultExpirationTime = 5 * time.Minute
// DefaultRenewTime is the default time before the JWT expiration when the renewal is allowed.
DefaultRenewTime = 30 * time.Second
// DefaultAuthorizationHeader is the default authorization header name.
DefaultAuthorizationHeader = "Authorization"
bearerHeader = "Bearer "
)
// SendResponseFn is the type of function used to send back the HTTP responses.
type SendResponseFn func(ctx context.Context, w http.ResponseWriter, statusCode int, data string)
// UserHashFn is the type of function used to retrieve the password hash associated with each user.
// The hash values should be generated via bcrypt.GenerateFromPassword(pwd, bcrypt.MinCost).
type UserHashFn func(username string) ([]byte, error)
// SigningMethod is a type alias for the Signing Method interface.
type SigningMethod jwt.SigningMethod
// Credentials holds the user name and password from the request body.
type Credentials struct {
Username string `json:"username"`
Password string `json:"password"`
}
// Claims holds the JWT information to be encoded.
type Claims struct {
Username string `json:"username"`
jwt.StandardClaims
}
// JWT represents an instance of the HTTP retrier.
type JWT struct {
key []byte // JWT signing key.
expirationTime time.Duration // JWT expiration time.
renewTime time.Duration // Time before the JWT expiration when the renewal is allowed.
sendResponseFn SendResponseFn // Response function used to send back the HTTP responses.
userHashFn UserHashFn // Function used to retrieve the password hash associated with each user.
signingMethod SigningMethod // Signing Method function
authorizationHeader string
}
func defaultJWT() *JWT {
return &JWT{
expirationTime: DefaultExpirationTime,
renewTime: DefaultRenewTime,
sendResponseFn: defaultSendResponse,
authorizationHeader: DefaultAuthorizationHeader,
signingMethod: defaultSigningMethod(),
}
}
func defaultSendResponse(ctx context.Context, w http.ResponseWriter, statusCode int, data string) {
httputil.SendText(ctx, w, statusCode, data)
}
func defaultSigningMethod() SigningMethod {
return jwt.SigningMethodHS256
}
// New creates a new instance.
func New(key []byte, userHashFn UserHashFn, opts ...Option) (*JWT, error) {
if len(key) == 0 {
return nil, fmt.Errorf("empty JWT key")
}
if userHashFn == nil {
return nil, fmt.Errorf("empty user hash function")
}
c := defaultJWT()
c.key = key
c.userHashFn = userHashFn
for _, applyOpt := range opts {
applyOpt(c)
}
return c, nil
}
// LoginHandler handles the login endpoint.
func (c *JWT) LoginHandler(w http.ResponseWriter, r *http.Request) {
var creds Credentials
defer logging.Close(r.Context(), r.Body, "error closing request body")
err := json.NewDecoder(r.Body).Decode(&creds)
if err != nil {
c.sendResponseFn(r.Context(), w, http.StatusBadRequest, err.Error())
logging.FromContext(r.Context()).Error("invalid JWT body", zap.Error(err))
return
}
hash, err := c.userHashFn(creds.Username)
if err != nil {
// invalid user
c.sendResponseFn(r.Context(), w, http.StatusUnauthorized, "invalid authentication credentials")
logging.FromContext(r.Context()).With(
zap.String("username", creds.Username),
).Error("invalid JWT username", zap.Error(err))
return
}
err = bcrypt.CompareHashAndPassword(hash, []byte(creds.Password))
if err != nil {
// invalid password
c.sendResponseFn(r.Context(), w, http.StatusUnauthorized, "invalid authentication credentials")
logging.FromContext(r.Context()).With(
zap.String("username", creds.Username),
).Error("invalid JWT password", zap.Error(err))
return
}
exp := time.Now().Add(c.expirationTime)
claims := Claims{
Username: creds.Username,
StandardClaims: jwt.StandardClaims{
ExpiresAt: exp.Unix(),
},
}
c.sendTokenResponse(w, r, &claims)
}
// RenewHandler handles the JWT renewal endpoint.
func (c *JWT) RenewHandler(w http.ResponseWriter, r *http.Request) {
claims, err := c.checkToken(r)
if err != nil {
c.sendResponseFn(r.Context(), w, http.StatusUnauthorized, err.Error())
logging.FromContext(r.Context()).With(
zap.String("username", claims.Username),
).Error("invalid JWT token", zap.Error(err))
return
}
if time.Until(time.Unix(claims.ExpiresAt, 0)) > c.renewTime {
c.sendResponseFn(r.Context(), w, http.StatusBadRequest, "the JWT token can be renewed only when it is close to expiration")
logging.FromContext(r.Context()).With(
zap.String("username", claims.Username),
).Error("invalid JWT renewal time", zap.Error(err))
return
}
c.sendTokenResponse(w, r, claims)
}
// IsAuthorized checks if the user is authorized via JWT token.
func (c *JWT) IsAuthorized(w http.ResponseWriter, r *http.Request) bool {
claims, err := c.checkToken(r)
if err != nil {
c.sendResponseFn(r.Context(), w, http.StatusUnauthorized, err.Error())
logging.FromContext(r.Context()).With(
zap.String("username", claims.Username),
).Error("unauthorized JWT user", zap.Error(err))
return false
}
return true
}
// sendTokenResponse sends the signed JWT token if claims are valid.
func (c *JWT) sendTokenResponse(w http.ResponseWriter, r *http.Request, claims *Claims) {
token := jwt.NewWithClaims(c.signingMethod, claims)
signedToken, err := token.SignedString(c.key)
if err != nil {
c.sendResponseFn(r.Context(), w, http.StatusInternalServerError, "unable to sign the JWT token")
logging.FromContext(r.Context()).With(
zap.String("username", claims.Username),
).Error("unable to sign the JWT token", zap.Error(err))
return
}
c.sendResponseFn(r.Context(), w, http.StatusOK, signedToken)
}
// checkToken extracts the JWT token from the header "Authorization: Bearer <TOKEN>"
// and returns an error if the token is invalid.
func (c *JWT) checkToken(r *http.Request) (*Claims, error) {
claims := &Claims{}
headAuth := r.Header.Get(c.authorizationHeader)
if len(headAuth) == 0 {
return claims, errors.New("missing Authorization header")
}
authSplit := strings.Split(headAuth, bearerHeader)
if len(authSplit) != 2 {
return claims, errors.New("missing JWT token")
}
signedToken := authSplit[1]
_, err := jwt.ParseWithClaims(
signedToken,
claims,
func(token *jwt.Token) (interface{}, error) {
return c.key, nil
},
)
return claims, err //nolint:wrapcheck
}