forked from TykTechnologies/tyk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware_jwt.go
146 lines (120 loc) · 3.86 KB
/
middleware_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
package main
import "net/http"
import (
"errors"
"fmt"
"github.com/Sirupsen/logrus"
"github.com/dgrijalva/jwt-go"
"github.com/gorilla/context"
"io"
)
// KeyExists will check if the key being used to access the API is in the request data,
// and then if the key is in the storage engine
type JWTMiddleware struct {
*TykMiddleware
}
func (k JWTMiddleware) New() {}
// GetConfig retrieves the configuration from the API config
func (k *JWTMiddleware) GetConfig() (interface{}, error) {
return k.TykMiddleware.Spec.APIDefinition.Auth, nil
}
func (k *JWTMiddleware) copyResponse(dst io.Writer, src io.Reader) {
io.Copy(dst, src)
}
func (k *JWTMiddleware) ProcessRequest(w http.ResponseWriter, r *http.Request, configuration interface{}) (error, int) {
thisConfig := k.TykMiddleware.Spec.APIDefinition.Auth
var thisSessionState SessionState
var tykId string
// Get the token
rawJWT := r.Header.Get(thisConfig.AuthHeaderName)
if thisConfig.UseParam {
tempRes := CopyRequest(r)
// Set hte header name
rawJWT = tempRes.FormValue(thisConfig.AuthHeaderName)
}
if thisConfig.UseCookie {
tempRes := CopyRequest(r)
authCookie, notFoundErr := tempRes.Cookie(thisConfig.AuthHeaderName)
if notFoundErr != nil {
rawJWT = ""
} else {
rawJWT = authCookie.Value
}
}
if rawJWT == "" {
// No header value, fail
log.WithFields(logrus.Fields{
"path": r.URL.Path,
"origin": r.RemoteAddr,
}).Info("Attempted access with malformed header, no JWT auth header found.")
log.Debug("Looked in: ", thisConfig.AuthHeaderName)
log.Debug("Raw data was: ", rawJWT)
log.Debug("Headers are: ", r.Header)
return errors.New("Authorization field missing"), 400
}
// Verify the token
token, err := jwt.Parse(rawJWT, func(token *jwt.Token) (interface{}, error) {
// Don't forget to validate the alg is what you expect:
if k.TykMiddleware.Spec.JWTSigningMethod == "hmac" {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
}
} else if k.TykMiddleware.Spec.JWTSigningMethod == "rsa" {
if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
}
} else if k.TykMiddleware.Spec.JWTSigningMethod == "ecdsa" {
if _, ok := token.Method.(*jwt.SigningMethodECDSA); !ok {
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
}
} else {
log.Warning("No signing method found in API Definition, defaulting to HMAC")
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
}
}
idFound := false
if token.Header["kid"] != nil {
tykId = token.Header["kid"].(string)
idFound = true
}
if !idFound {
if token.Claims["sub"] != nil {
tykId = token.Claims["sub"].(string)
idFound = true
}
}
var keyExists bool
thisSessionState, keyExists = k.TykMiddleware.CheckSessionAndIdentityForValidKey(tykId)
if !keyExists {
return nil, errors.New("Token ivalid, key not found.")
}
return []byte(thisSessionState.JWTData.Secret), nil
})
if err == nil && token.Valid {
// all good to go
context.Set(r, SessionData, thisSessionState)
context.Set(r, AuthHeaderValue, tykId)
return nil, 200
} else {
var kID string
var found bool
if token != nil {
kID, found = token.Header["kid"].(string)
}
log.WithFields(logrus.Fields{
"path": r.URL.Path,
"origin": r.RemoteAddr,
"key": kID,
"key_present": found,
}).Info("Attempted JWT access with non-existent key.")
if err != nil {
log.Error("Token validtion errored: ", err)
}
// Fire Authfailed Event
AuthFailed(k.TykMiddleware, r, tykId)
// Report in health check
ReportHealthCheckValue(k.Spec.Health, KeyFailure, "1")
return errors.New("Key not authorised"), 403
}
}