Skip to content

Commit 6b9408d

Browse files
ozburovishr
authored andcommitted
Added param:<name> lookup option to JWT Middleware (#1296)
* Added lookup option to JWT Middleware * Added param:<name> lookup option to JWT Middleware
1 parent c824b8d commit 6b9408d

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

middleware/jwt.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@ type (
5252
// Possible values:
5353
// - "header:<name>"
5454
// - "query:<name>"
55+
// - "param:<name>"
5556
// - "cookie:<name>"
5657
TokenLookup string
5758

@@ -155,6 +156,8 @@ func JWTWithConfig(config JWTConfig) echo.MiddlewareFunc {
155156
switch parts[0] {
156157
case "query":
157158
extractor = jwtFromQuery(parts[1])
159+
case "param":
160+
extractor = jwtFromParam(parts[1])
158161
case "cookie":
159162
extractor = jwtFromCookie(parts[1])
160163
}
@@ -228,6 +231,17 @@ func jwtFromQuery(param string) jwtExtractor {
228231
}
229232
}
230233

234+
// jwtFromParam returns a `jwtExtractor` that extracts token from the url param string.
235+
func jwtFromParam(param string) jwtExtractor {
236+
return func(c echo.Context) (string, error) {
237+
token := c.Param(param)
238+
if token == "" {
239+
return "", ErrJWTMissing
240+
}
241+
return token, nil
242+
}
243+
}
244+
231245
// jwtFromCookie returns a `jwtExtractor` that extracts token from the named cookie.
232246
func jwtFromCookie(name string) jwtExtractor {
233247
return func(c echo.Context) (string, error) {

middleware/jwt_test.go

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -159,6 +159,14 @@ func TestJWT(t *testing.T) {
159159
expErrCode: http.StatusBadRequest,
160160
info: "Empty query",
161161
},
162+
{
163+
config: JWTConfig{
164+
SigningKey: validKey,
165+
TokenLookup: "param:jwt",
166+
},
167+
reqURL: "/" + token,
168+
info: "Valid param method",
169+
},
162170
{
163171
config: JWTConfig{
164172
SigningKey: validKey,
@@ -195,6 +203,11 @@ func TestJWT(t *testing.T) {
195203
req.Header.Set(echo.HeaderCookie, tc.hdrCookie)
196204
c := e.NewContext(req, res)
197205

206+
if tc.reqURL == "/" + token {
207+
c.SetParamNames("jwt")
208+
c.SetParamValues(token)
209+
}
210+
198211
if tc.expPanic {
199212
assert.Panics(t, func() {
200213
JWTWithConfig(tc.config)

0 commit comments

Comments
 (0)