-
Notifications
You must be signed in to change notification settings - Fork 0
/
jwt.go
194 lines (175 loc) · 4.43 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
package jwt_verifier
import (
"context"
"crypto"
"crypto/rsa"
"crypto/x509"
"encoding/base64"
"encoding/json"
"encoding/pem"
"errors"
"log"
"net/http"
"os"
"strings"
"time"
)
var (
ErrInvalidJWT = errors.New("invalid jwt token")
ErrInvalidISS = errors.New("invalid iss")
ErrInvalidEXP = errors.New("invalid exp")
ErrInvalidNBF = errors.New("invalid nbf")
ErrInvalidKey = errors.New("invalid key")
ErrEmptyISS = errors.New("Issuer cannot be empty")
ErrEmptyPublicKey = errors.New("PublicKey cannot be empty")
ErrPublicKey = errors.New("key is not a valid RSA public key")
)
type Config struct {
PublicKey string
Issuer string
}
type JWTVerifier struct {
next http.Handler
publicKey *rsa.PublicKey
issuer string
name string
}
type Token struct {
header string
payload string
signature string
}
func CreateConfig() *Config {
return &Config{
PublicKey: "",
Issuer: "",
}
}
func New(ctx context.Context, next http.Handler, config *Config, name string) (http.Handler, error) {
if len(config.PublicKey) == 0 {
return nil, ErrEmptyPublicKey
}
if len(config.Issuer) == 0 {
return nil, ErrEmptyISS
}
publicKey, err := createPublicKey(config.PublicKey)
if err != nil {
return nil, err
}
log.SetOutput(os.Stdout)
return &JWTVerifier{
next: next,
publicKey: publicKey,
issuer: config.Issuer,
name: name,
}, nil
}
func (j *JWTVerifier) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
headerToken := req.Header.Get("Authorization")
if len(headerToken) == 0 {
j.next.ServeHTTP(rw, req)
return
}
token, preprocessError := PreprocessJWT(headerToken)
if preprocessError != nil {
log.Println("Invalid token format:", preprocessError)
http.Error(rw, "Not allowed", http.StatusForbidden)
return
}
signatureError := token.VerifySignature(j.publicKey)
if signatureError != nil {
log.Println("JWT signature error:", signatureError)
http.Error(rw, "Not allowed", http.StatusForbidden)
return
}
claimsError := token.VerifyClaims(time.Now().Unix(), j.issuer)
if claimsError != nil {
log.Println("JWT claims error:", claimsError)
http.Error(rw, "Not allowed", http.StatusForbidden)
return
}
j.next.ServeHTTP(rw, req)
}
func PreprocessJWT(authHeader string) (Token, error) {
cleanedJwt := strings.TrimPrefix(authHeader, "Bearer")
cleanedJwt = strings.TrimSpace(cleanedJwt)
parts := strings.Split(cleanedJwt, ".")
var token Token
if len(parts) != 3 {
return token, ErrInvalidJWT
}
token.header = parts[0]
token.payload = parts[1]
token.signature = parts[2]
return token, nil
}
func createPublicKey(publicKey string) (*rsa.PublicKey, error) {
keyData := strings.Join([]string{"-----BEGIN PUBLIC KEY-----", publicKey, "-----END PUBLIC KEY-----"}, "\n")
return ParseRSAPublicKeyFromPEM([]byte(keyData))
}
func ParseRSAPublicKeyFromPEM(key []byte) (*rsa.PublicKey, error) {
var block *pem.Block
if block, _ = pem.Decode(key); block == nil {
return nil, ErrInvalidKey
}
parsedKey, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
return nil, err
}
pkey, ok := parsedKey.(*rsa.PublicKey)
if !ok {
return nil, ErrPublicKey
}
return pkey, nil
}
func (t Token) VerifySignature(publicKey *rsa.PublicKey) error {
hash := crypto.SHA512
digest := hash.New()
digest.Write([]byte(t.headerAndPayload()))
sig, err := base64.RawURLEncoding.DecodeString(t.signature)
if err != nil {
return err
}
return rsa.VerifyPKCS1v15(publicKey, hash, digest.Sum(nil), sig)
}
func (t Token) headerAndPayload() string {
return strings.Join([]string{t.header, t.payload}, ".")
}
func (t Token) VerifyClaims(now int64, issuer string) error {
payload, err := base64.RawURLEncoding.DecodeString(t.payload)
if err != nil {
return err
}
var claims Claims
err = json.Unmarshal(payload, &claims)
if err != nil {
return err
}
return claims.Verify(now, issuer)
}
type Claims struct {
Issuer string `json:"iss"`
ExpiresAt int64 `json:"exp"`
NotBefore int64 `json:"nbf"`
}
func (c Claims) Verify(now int64, issuer string) error {
if !c.VerifyIssuer(issuer) {
return ErrInvalidISS
}
if !c.VerifyExpiresAt(now) {
return ErrInvalidEXP
}
if !c.VerifyNotBefore(now) {
return ErrInvalidNBF
}
return nil
}
func (c Claims) VerifyIssuer(issuer string) bool {
return c.Issuer == issuer
}
func (c Claims) VerifyExpiresAt(now int64) bool {
return now < c.ExpiresAt
}
func (c Claims) VerifyNotBefore(now int64) bool {
return c.NotBefore <= now
}