/
jwt.go
178 lines (139 loc) · 3.91 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
package jwt
import (
"crypto/subtle"
"fmt"
"net/http"
"time"
"github.com/pkg/errors"
"github.com/golang-jwt/jwt"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
"github.com/libp2p/go-libp2p-core/crypto"
)
// Errors
var (
ErrJWTInvalidClaims = echo.NewHTTPError(http.StatusUnauthorized, "invalid jwt claims")
)
type JWTAuth struct {
subject string
sessionTimeout time.Duration
nodeID string
secret []byte
}
func NewJWTAuth(subject string, sessionTimeout time.Duration, nodeID string, secret crypto.PrivKey) (*JWTAuth, error) {
if len(subject) == 0 {
return nil, errors.New("subject must not be empty")
}
secretBytes, err := crypto.MarshalPrivateKey(secret)
if err != nil {
return nil, fmt.Errorf("unable to convert private key: %w", err)
}
return &JWTAuth{
subject: subject,
sessionTimeout: sessionTimeout,
nodeID: nodeID,
secret: secretBytes,
}, nil
}
type AuthClaims struct {
jwt.StandardClaims
Dashboard bool `json:"dashboard"`
API bool `json:"api"`
}
func (c *AuthClaims) compare(field string, expected string) bool {
if field == "" {
return false
}
if subtle.ConstantTimeCompare([]byte(field), []byte(expected)) != 0 {
return true
}
return false
}
func (c *AuthClaims) VerifySubject(expected string) bool {
return c.compare(c.Subject, expected)
}
func (j *JWTAuth) Middleware(skipper middleware.Skipper, allow func(c echo.Context, subject string, claims *AuthClaims) bool) echo.MiddlewareFunc {
config := middleware.JWTConfig{
ContextKey: "jwt",
Claims: &AuthClaims{},
SigningKey: j.secret,
}
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
// skip unprotected endpoints
if skipper(c) {
return next(c)
}
// use the default JWT middleware to verify and extract the JWT
handler := middleware.JWTWithConfig(config)(func(c echo.Context) error {
return nil
})
// run the JWT middleware
if err := handler(c); err != nil {
return err
}
token := c.Get("jwt").(*jwt.Token)
// validate the signing method we expect
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
// read the claims set by the JWT middleware on the context
claims, ok := token.Claims.(*AuthClaims)
// do extended claims validation
if !ok || !claims.VerifyAudience(j.nodeID, true) {
return ErrJWTInvalidClaims
}
// validate claims
if !allow(c, j.subject, claims) {
return ErrJWTInvalidClaims
}
// go to the next handler
return next(c)
}
}
}
func (j *JWTAuth) IssueJWT(api bool, dashboard bool) (string, error) {
now := time.Now()
// Set claims
stdClaims := jwt.StandardClaims{
Subject: j.subject,
Issuer: j.nodeID,
Audience: j.nodeID,
Id: fmt.Sprintf("%d", now.Unix()),
IssuedAt: now.Unix(),
NotBefore: now.Unix(),
}
if j.sessionTimeout > 0 {
stdClaims.ExpiresAt = now.Add(j.sessionTimeout).Unix()
}
claims := &AuthClaims{
StandardClaims: stdClaims,
Dashboard: dashboard,
API: api,
}
// Create token
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
// Generate encoded token and send it as response.
return token.SignedString(j.secret)
}
func (j *JWTAuth) VerifyJWT(token string, allow func(claims *AuthClaims) bool) bool {
t, err := jwt.ParseWithClaims(token, &AuthClaims{}, func(token *jwt.Token) (interface{}, error) {
// validate the signing method we expect
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
return j.secret, nil
})
if err == nil && t.Valid {
claims, ok := t.Claims.(*AuthClaims)
if !ok || !claims.VerifyAudience(j.nodeID, true) {
return false
}
// validate claims
if !allow(claims) {
return false
}
return true
}
return false
}