JWT: Allow conventional bearer token in Authorization header (#54821)
* fix: allow JWT to accept standard bearer token * fix: linter issues * fix: linter gosec false positive * fix: refactor logic into JWT handler * fix: move bearer trimming earlier
This commit is contained in:
@@ -4,6 +4,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/grafana/grafana/pkg/login"
|
||||
"github.com/grafana/grafana/pkg/models"
|
||||
@@ -32,6 +33,15 @@ func (h *ContextHandler) initContextWithJWT(ctx *models.ReqContext, orgId int64)
|
||||
return false
|
||||
}
|
||||
|
||||
// Strip the 'Bearer' prefix if it exists.
|
||||
jwtToken = strings.TrimPrefix(jwtToken, "Bearer ")
|
||||
|
||||
// The header is Authorization and the token does not look like a JWT,
|
||||
// this is likely an API key. Pass it on.
|
||||
if h.Cfg.JWTAuthHeaderName == "Authorization" && !looksLikeJWT(jwtToken) {
|
||||
return false
|
||||
}
|
||||
|
||||
claims, err := h.JWTAuthService.Verify(ctx.Req.Context(), jwtToken)
|
||||
if err != nil {
|
||||
ctx.Logger.Debug("Failed to verify JWT", "error", err)
|
||||
@@ -186,3 +196,9 @@ func searchClaimsForStringAttr(attributePath string, claims map[string]interface
|
||||
|
||||
return "", nil
|
||||
}
|
||||
|
||||
func looksLikeJWT(token string) bool {
|
||||
// A JWT must have 3 parts separated by `.`.
|
||||
parts := strings.Split(token, ".")
|
||||
return len(parts) == 3
|
||||
}
|
||||
|
||||
@@ -147,11 +147,11 @@ func (h *ContextHandler) Middleware(next http.Handler) http.Handler {
|
||||
// then test if anonymous access is enabled
|
||||
switch {
|
||||
case h.initContextWithRenderAuth(reqContext):
|
||||
case h.initContextWithJWT(reqContext, orgID):
|
||||
case h.initContextWithAPIKey(reqContext):
|
||||
case h.initContextWithBasicAuth(reqContext, orgID):
|
||||
case h.initContextWithAuthProxy(reqContext, orgID):
|
||||
case h.initContextWithToken(reqContext, orgID):
|
||||
case h.initContextWithJWT(reqContext, orgID):
|
||||
case h.initContextWithAnonymousUser(reqContext):
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user