Skip to content

Commit

Permalink
Added param:<name> lookup option to JWT Middleware (#1296)
Browse files Browse the repository at this point in the history
* Added  lookup option to JWT Middleware

* Added param:<name> lookup option to JWT Middleware
  • Loading branch information
ozburo authored and vishr committed Jun 9, 2019
1 parent c824b8d commit 6b9408d
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
14 changes: 14 additions & 0 deletions middleware/jwt.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ type (
// Possible values:
// - "header:<name>"
// - "query:<name>"
// - "param:<name>"
// - "cookie:<name>"
TokenLookup string

Expand Down Expand Up @@ -155,6 +156,8 @@ func JWTWithConfig(config JWTConfig) echo.MiddlewareFunc {
switch parts[0] {
case "query":
extractor = jwtFromQuery(parts[1])
case "param":
extractor = jwtFromParam(parts[1])
case "cookie":
extractor = jwtFromCookie(parts[1])
}
Expand Down Expand Up @@ -228,6 +231,17 @@ func jwtFromQuery(param string) jwtExtractor {
}
}

// jwtFromParam returns a `jwtExtractor` that extracts token from the url param string.
func jwtFromParam(param string) jwtExtractor {
return func(c echo.Context) (string, error) {
token := c.Param(param)
if token == "" {
return "", ErrJWTMissing
}
return token, nil
}
}

// jwtFromCookie returns a `jwtExtractor` that extracts token from the named cookie.
func jwtFromCookie(name string) jwtExtractor {
return func(c echo.Context) (string, error) {
Expand Down
13 changes: 13 additions & 0 deletions middleware/jwt_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,14 @@ func TestJWT(t *testing.T) {
expErrCode: http.StatusBadRequest,
info: "Empty query",
},
{
config: JWTConfig{
SigningKey: validKey,
TokenLookup: "param:jwt",
},
reqURL: "/" + token,
info: "Valid param method",
},
{
config: JWTConfig{
SigningKey: validKey,
Expand Down Expand Up @@ -195,6 +203,11 @@ func TestJWT(t *testing.T) {
req.Header.Set(echo.HeaderCookie, tc.hdrCookie)
c := e.NewContext(req, res)

if tc.reqURL == "/" + token {
c.SetParamNames("jwt")
c.SetParamValues(token)
}

if tc.expPanic {
assert.Panics(t, func() {
JWTWithConfig(tc.config)
Expand Down

0 comments on commit 6b9408d

Please sign in to comment.