1
0
mirror of https://github.com/labstack/echo.git synced 2024-11-24 08:22:21 +02:00

Jwt lookup from multiple sources (#1845)

* Jwt lookup from multiple sources
This commit is contained in:
Kaan Karakaya 2021-05-08 22:30:06 +03:00 committed by GitHub
parent 7256cb2274
commit de3f87eb23
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 38 additions and 13 deletions

View File

@ -160,17 +160,24 @@ func JWTWithConfig(config JWTConfig) echo.MiddlewareFunc {
} }
// Initialize // Initialize
parts := strings.Split(config.TokenLookup, ":") // Split sources
extractor := jwtFromHeader(parts[1], config.AuthScheme) sources := strings.Split(config.TokenLookup, ",")
var extractors []jwtExtractor
for _, source := range sources {
parts := strings.Split(source, ":")
switch parts[0] { switch parts[0] {
case "query": case "query":
extractor = jwtFromQuery(parts[1]) extractors = append(extractors, jwtFromQuery(parts[1]))
case "param": case "param":
extractor = jwtFromParam(parts[1]) extractors = append(extractors, jwtFromParam(parts[1]))
case "cookie": case "cookie":
extractor = jwtFromCookie(parts[1]) extractors = append(extractors, jwtFromCookie(parts[1]))
case "form": case "form":
extractor = jwtFromForm(parts[1]) extractors = append(extractors, jwtFromForm(parts[1]))
case "header":
extractors = append(extractors, jwtFromHeader(parts[1], config.AuthScheme))
}
} }
return func(next echo.HandlerFunc) echo.HandlerFunc { return func(next echo.HandlerFunc) echo.HandlerFunc {
@ -182,8 +189,17 @@ func JWTWithConfig(config JWTConfig) echo.MiddlewareFunc {
if config.BeforeFunc != nil { if config.BeforeFunc != nil {
config.BeforeFunc(c) config.BeforeFunc(c)
} }
var auth string
auth, err := extractor(c) var err error
for _, extractor := range extractors {
// Extract token from extractor, if it's not fail break the loop and
// set auth
auth, err = extractor(c)
if err == nil {
break
}
}
// If none of extractor has a token, handle error
if err != nil { if err != nil {
if config.ErrorHandler != nil { if config.ErrorHandler != nil {
return config.ErrorHandler(err) return config.ErrorHandler(err)
@ -194,6 +210,7 @@ func JWTWithConfig(config JWTConfig) echo.MiddlewareFunc {
} }
return err return err
} }
token := new(jwt.Token) token := new(jwt.Token)
// Issue #647, #656 // Issue #647, #656
if _, ok := config.Claims.(jwt.MapClaims); ok { if _, ok := config.Claims.(jwt.MapClaims); ok {

View File

@ -179,6 +179,14 @@ func TestJWT(t *testing.T) {
hdrCookie: "jwt=" + token, hdrCookie: "jwt=" + token,
info: "Valid cookie method", info: "Valid cookie method",
}, },
{
config: JWTConfig{
SigningKey: validKey,
TokenLookup: "query:jwt,cookie:jwt",
},
hdrCookie: "jwt=" + token,
info: "Multiple jwt lookuop",
},
{ {
config: JWTConfig{ config: JWTConfig{
SigningKey: validKey, SigningKey: validKey,