Auth: implement auto_sign_up for auth.jwt (#43502)

Co-authored-by: James Brown <jbrown@easypost.com>
This commit is contained in:
Emil Tullstedt
2022-01-13 17:15:22 +01:00
committed by GitHub
co-authored by James Brown
parent 45287b4129
commit 25736b6afb
7 changed files with 118 additions and 4 deletions
+33 -1
View File
@@ -9,6 +9,7 @@ import (
)
const InvalidJWT = "Invalid JWT"
const UserNotFound = "User not found"
func (h *ContextHandler) initContextWithJWT(ctx *models.ReqContext, orgId int64) bool {
if !h.Cfg.JWTAuthEnabled || h.Cfg.JWTAuthHeaderName == "" {
@@ -29,11 +30,29 @@ func (h *ContextHandler) initContextWithJWT(ctx *models.ReqContext, orgId int64)
query := models.GetSignedInUserQuery{OrgId: orgId}
sub, _ := claims["sub"].(string)
if sub == "" {
ctx.Logger.Warn("Got a JWT without the mandatory 'sub' claim", "error", err)
ctx.JsonApiErr(401, InvalidJWT, err)
return true
}
extUser := &models.ExternalUserInfo{
AuthModule: "jwt",
AuthId: sub,
}
if key := h.Cfg.JWTAuthUsernameClaim; key != "" {
query.Login, _ = claims[key].(string)
extUser.Login, _ = claims[key].(string)
}
if key := h.Cfg.JWTAuthEmailClaim; key != "" {
query.Email, _ = claims[key].(string)
extUser.Email, _ = claims[key].(string)
}
if name, _ := claims["name"].(string); name != "" {
extUser.Name = name
}
if query.Login == "" && query.Email == "" {
@@ -42,6 +61,18 @@ func (h *ContextHandler) initContextWithJWT(ctx *models.ReqContext, orgId int64)
return true
}
if h.Cfg.JWTAuthAutoSignUp {
upsert := &models.UpsertUserCommand{
ReqContext: ctx,
SignupAllowed: h.Cfg.JWTAuthAutoSignUp,
ExternalUser: extUser,
}
if err := bus.Dispatch(ctx.Req.Context(), upsert); err != nil {
ctx.Logger.Error("Failed to upsert JWT user", "error", err)
return false
}
}
if err := bus.Dispatch(ctx.Req.Context(), &query); err != nil {
if errors.Is(err, models.ErrUserNotFound) {
ctx.Logger.Debug(
@@ -50,10 +81,11 @@ func (h *ContextHandler) initContextWithJWT(ctx *models.ReqContext, orgId int64)
"username_claim", query.Login,
)
err = login.ErrInvalidCredentials
ctx.JsonApiErr(401, UserNotFound, err)
} else {
ctx.Logger.Error("Failed to get signed in user", "error", err)
ctx.JsonApiErr(401, InvalidJWT, err)
}
ctx.JsonApiErr(401, InvalidJWT, err)
return true
}
+2
View File
@@ -96,6 +96,8 @@ func GetAuthProviderLabel(authModule string) string {
return "SAML"
case "ldap", "":
return "LDAP"
case "jwt":
return "JWT"
default:
return "OAuth"
}