1
0
mirror of https://github.com/labstack/echo.git synced 2024-11-28 08:38:39 +02:00

Added param:<name> lookup option to JWT Middleware (#1296)

* Added  lookup option to JWT Middleware

* Added param:<name> lookup option to JWT Middleware
This commit is contained in:
ozburo 2019-06-09 11:49:52 -05:00 committed by Vishal Rana
parent c824b8ddc3
commit 6b9408d1d1
2 changed files with 27 additions and 0 deletions

View File

@ -52,6 +52,7 @@ type (
// Possible values: // Possible values:
// - "header:<name>" // - "header:<name>"
// - "query:<name>" // - "query:<name>"
// - "param:<name>"
// - "cookie:<name>" // - "cookie:<name>"
TokenLookup string TokenLookup string
@ -155,6 +156,8 @@ func JWTWithConfig(config JWTConfig) echo.MiddlewareFunc {
switch parts[0] { switch parts[0] {
case "query": case "query":
extractor = jwtFromQuery(parts[1]) extractor = jwtFromQuery(parts[1])
case "param":
extractor = jwtFromParam(parts[1])
case "cookie": case "cookie":
extractor = jwtFromCookie(parts[1]) extractor = jwtFromCookie(parts[1])
} }
@ -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. // jwtFromCookie returns a `jwtExtractor` that extracts token from the named cookie.
func jwtFromCookie(name string) jwtExtractor { func jwtFromCookie(name string) jwtExtractor {
return func(c echo.Context) (string, error) { return func(c echo.Context) (string, error) {

View File

@ -159,6 +159,14 @@ func TestJWT(t *testing.T) {
expErrCode: http.StatusBadRequest, expErrCode: http.StatusBadRequest,
info: "Empty query", info: "Empty query",
}, },
{
config: JWTConfig{
SigningKey: validKey,
TokenLookup: "param:jwt",
},
reqURL: "/" + token,
info: "Valid param method",
},
{ {
config: JWTConfig{ config: JWTConfig{
SigningKey: validKey, SigningKey: validKey,
@ -195,6 +203,11 @@ func TestJWT(t *testing.T) {
req.Header.Set(echo.HeaderCookie, tc.hdrCookie) req.Header.Set(echo.HeaderCookie, tc.hdrCookie)
c := e.NewContext(req, res) c := e.NewContext(req, res)
if tc.reqURL == "/" + token {
c.SetParamNames("jwt")
c.SetParamValues(token)
}
if tc.expPanic { if tc.expPanic {
assert.Panics(t, func() { assert.Panics(t, func() {
JWTWithConfig(tc.config) JWTWithConfig(tc.config)