public LoginResponse Login([FromBody] LoginRequest data) { if (string.IsNullOrEmpty(data.userName)) { throw ModelException("userName", AuthMessage.UserNameMustHaveAValue.NiceToString()); } if (string.IsNullOrEmpty(data.password)) { throw ModelException("password", AuthMessage.PasswordMustHaveAValue.NiceToString()); } // Attempt to login UserEntity user = null; try { user = AuthLogic.Login(data.userName, Security.EncodePassword(data.password)); } catch (Exception e) when(e is IncorrectUsernameException || e is IncorrectPasswordException) { if (AuthServer.MergeInvalidUsernameAndPasswordMessages) { ModelState.AddModelError("userName", AuthMessage.InvalidUsernameOrPassword.NiceToString()); ModelState.AddModelError("password", AuthMessage.InvalidUsernameOrPassword.NiceToString()); throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, this.ModelState)); } else if (e is IncorrectUsernameException) { throw ModelException("userName", AuthMessage.InvalidUsername.NiceToString()); } else if (e is IncorrectPasswordException) { throw ModelException("password", AuthMessage.InvalidPassword.NiceToString()); } } catch (IncorrectPasswordException) { throw ModelException("password", AuthServer.MergeInvalidUsernameAndPasswordMessages ? AuthMessage.InvalidUsernameOrPassword.NiceToString() : AuthMessage.InvalidPassword.NiceToString()); } using (UserHolder.UserSession(user)) { if (data.rememberMe == true) { UserTicketServer.SaveCookie(); } AuthServer.AddUserSession(user); string message = AuthLogic.OnLoginMessage(); var token = AuthTokenServer.CreateToken(user); return(new LoginResponse { message = message, userEntity = user, token = token }); } }
public ActionResult <LoginResponse> Login([Required, FromBody] LoginRequest data) { if (string.IsNullOrEmpty(data.userName)) { return(ModelError("userName", LoginAuthMessage.UserNameMustHaveAValue.NiceToString())); } if (string.IsNullOrEmpty(data.password)) { return(ModelError("password", LoginAuthMessage.PasswordMustHaveAValue.NiceToString())); } string authenticationType; // Attempt to login UserEntity user; try { if (AuthLogic.Authorizer == null) { user = AuthLogic.Login(data.userName, Security.EncodePassword(data.password), out authenticationType); } else { user = AuthLogic.Authorizer.Login(data.userName, data.password, out authenticationType); } } catch (Exception e) when(e is IncorrectUsernameException || e is IncorrectPasswordException) { if (AuthServer.MergeInvalidUsernameAndPasswordMessages) { return(ModelError("login", LoginAuthMessage.InvalidUsernameOrPassword.NiceToString())); } else if (e is IncorrectUsernameException) { return(ModelError("userName", LoginAuthMessage.InvalidUsername.NiceToString())); } else if (e is IncorrectPasswordException) { return(ModelError("password", LoginAuthMessage.InvalidPassword.NiceToString())); } throw; } catch (Exception e) { return(ModelError("login", e.Message)); } AuthServer.OnUserPreLogin(ControllerContext, user); AuthServer.AddUserSession(ControllerContext, user); if (data.rememberMe == true) { UserTicketServer.SaveCookie(ControllerContext); } var token = AuthTokenServer.CreateToken(user); return(new LoginResponse { userEntity = user, token = token, authenticationType = authenticationType }); }
public static string?LoginWindowsAuthentication(ActionContext ac) { using (AuthLogic.Disable()) { try { if (!(ac.HttpContext.User is WindowsPrincipal wp)) { return($"User is not a WindowsPrincipal ({ac.HttpContext.User.GetType().Name})"); } if (AuthLogic.Authorizer is not ActiveDirectoryAuthorizer ada) { return("No AuthLogic.Authorizer set"); } var config = ada.GetConfig(); if (!config.LoginWithWindowsAuthenticator) { return($"{ReflectionTools.GetPropertyInfo(() => ada.GetConfig().LoginWithWindowsAuthenticator)} is set to false"); } var userName = wp.Identity.Name !; var domainName = config.DomainName.DefaultToNull() ?? userName.TryAfterLast('@') ?? userName.TryBefore('\\') !; var localName = userName.TryBeforeLast('@') ?? userName.TryAfter('\\') ?? userName; var sid = ((WindowsIdentity)wp.Identity).User !.Value; UserEntity?user = Database.Query <UserEntity>().SingleOrDefaultEx(a => a.Mixin <UserADMixin>().SID == sid); if (user == null) { user = Database.Query <UserEntity>().SingleOrDefault(a => a.UserName == userName) ?? (config.AllowMatchUsersBySimpleUserName ? Database.Query <UserEntity>().SingleOrDefault(a => a.Email == userName || a.UserName == localName) : null); } try { if (user == null) { if (!config.AutoCreateUsers) { return(null); } using (PrincipalContext pc = GetPrincipalContext(domainName, config)) { user = Database.Query <UserEntity>().SingleOrDefaultEx(a => a.Mixin <UserADMixin>().SID == sid); if (user == null) { user = ada.OnAutoCreateUser(new DirectoryServiceAutoCreateUserContext(pc, localName, domainName !)); } } } else { if (!config.AutoUpdateUsers) { return(null); } using (PrincipalContext pc = GetPrincipalContext(domainName, config)) { ada.UpdateUser(user, new DirectoryServiceAutoCreateUserContext(pc, localName, domainName !)); } } } catch (Exception e) { e.Data["Identity.Name"] = wp.Identity.Name; e.Data["domainName"] = domainName; e.Data["localName"] = localName; throw; } if (user == null) { if (user == null) { return("AutoCreateUsers is false"); } } AuthServer.OnUserPreLogin(ac, user); AuthServer.AddUserSession(ac, user); return(null); } catch (Exception e) { e.LogException(); return(e.Message); } } }
public static void Start(IApplicationBuilder app, Func <AuthTokenConfigurationEmbedded> tokenConfig, string hashableEncryptionKey) { SignumControllerFactory.RegisterArea(MethodInfo.GetCurrentMethod()); AuthTokenServer.Start(tokenConfig, hashableEncryptionKey); ReflectionServer.GetContext = () => new { Culture = ReflectionServer.GetCurrentValidCulture(), Role = UserEntity.Current == null ? null : RoleEntity.Current, }; AuthLogic.OnRulesChanged += () => ReflectionServer.cache.Clear(); if (TypeAuthLogic.IsStarted) { ReflectionServer.TypeExtension += (ti, t) => { if (typeof(Entity).IsAssignableFrom(t)) { if (UserEntity.Current == null) { return(null); } var ta = TypeAuthLogic.GetAllowed(t); if (ta.MaxUI() == TypeAllowedBasic.None) { return(null); } ti.Extension.Add("maxTypeAllowed", ta.MaxUI()); ti.Extension.Add("minTypeAllowed", ta.MinUI()); ti.RequiresEntityPack |= ta.Conditions.Any(); return(ti); } else { if (t.HasAttribute <AllowUnathenticatedAttribute>()) { return(ti); } if (UserEntity.Current == null) { return(null); } if (!AuthServer.IsNamespaceAllowed(t)) { return(null); } return(ti); } }; EntityPackTS.AddExtension += ep => { var typeAllowed = UserEntity.Current == null ? TypeAllowedBasic.None : ep.entity.IsNew ? TypeAuthLogic.GetAllowed(ep.entity.GetType()).MaxUI() : TypeAuthLogic.IsAllowedFor(ep.entity, TypeAllowedBasic.Write, true) ? TypeAllowedBasic.Write : TypeAuthLogic.IsAllowedFor(ep.entity, TypeAllowedBasic.Read, true) ? TypeAllowedBasic.Read : TypeAllowedBasic.None; ep.extension.Add("typeAllowed", typeAllowed); }; OperationController.AnyReadonly += (Lite <Entity>[] lites) => { return(lites.GroupBy(ap => ap.EntityType).Any(gr => { var ta = TypeAuthLogic.GetAllowed(gr.Key); if (ta.Min(inUserInterface: true) == TypeAllowedBasic.Write) { return false; } if (ta.Max(inUserInterface: true) <= TypeAllowedBasic.Read) { return true; } return giCountReadonly.GetInvoker(gr.Key)() > 0; })); }; } if (QueryAuthLogic.IsStarted) { ReflectionServer.TypeExtension += (ti, t) => { if (ti.QueryDefined) { var allowed = UserEntity.Current == null ? QueryAllowed.None : QueryAuthLogic.GetQueryAllowed(t); if (allowed == QueryAllowed.None) { ti.QueryDefined = false; } ti.Extension.Add("queryAllowed", allowed); } return(ti); }; ReflectionServer.FieldInfoExtension += (mi, fi) => { if (fi.DeclaringType !.Name.EndsWith("Query")) { var allowed = UserEntity.Current == null ? QueryAllowed.None : QueryAuthLogic.GetQueryAllowed(fi.GetValue(null) !); if (allowed == QueryAllowed.None) { return(null); } mi.Extension.Add("queryAllowed", allowed); } return(mi); }; } if (PropertyAuthLogic.IsStarted) { ReflectionServer.PropertyRouteExtension += (mi, pr) => { var allowed = UserEntity.Current == null?pr.GetAllowUnathenticated() : pr.GetPropertyAllowed(); if (allowed == PropertyAllowed.None) { return(null); } mi.Extension.Add("propertyAllowed", allowed); return(mi); }; EntityJsonConverter.CanReadPropertyRoute = pr => { var allowed = UserEntity.Current == null?pr.GetAllowUnathenticated() : pr.GetPropertyAllowed(); return(allowed == PropertyAllowed.None ? "Not allowed" : null); }; EntityJsonConverter.CanWritePropertyRoute = pr => { var allowed = UserEntity.Current == null?pr.GetAllowUnathenticated() : pr.GetPropertyAllowed(); return(allowed == PropertyAllowed.Write ? null : "Not allowed to write property: " + pr.ToString()); }; } if (OperationAuthLogic.IsStarted) { ReflectionServer.OperationExtension += (oits, oi, type) => { var allowed = UserEntity.Current == null ? false : OperationAuthLogic.GetOperationAllowed(oi.OperationSymbol, type, inUserInterface: true); if (!allowed) { return(null); } return(oits); }; } if (PermissionAuthLogic.IsStarted) { ReflectionServer.FieldInfoExtension += (mi, fi) => { if (fi.FieldType == typeof(PermissionSymbol)) { var allowed = UserEntity.Current == null ? false : PermissionAuthLogic.IsAuthorized((PermissionSymbol)fi.GetValue(null) !); if (allowed == false) { return(null); } } return(mi); }; } var piPasswordHash = ReflectionTools.GetPropertyInfo((UserEntity e) => e.PasswordHash); var pcs = PropertyConverter.GetPropertyConverters(typeof(UserEntity)); pcs.GetOrThrow("passwordHash").CustomWriteJsonProperty = ctx => { }; pcs.Add("newPassword", new PropertyConverter { AvoidValidate = true, CustomWriteJsonProperty = ctx => { }, CustomReadJsonProperty = ctx => { EntityJsonConverter.AssertCanWrite(ctx.ParentPropertyRoute.Add(piPasswordHash)); var password = (string)ctx.JsonReader.Value !; var error = UserEntity.OnValidatePassword(password); if (error != null) { throw new ApplicationException(error); } ((UserEntity)ctx.Entity).PasswordHash = Security.EncodePassword(password); } });
public static bool LoginAzureADAuthentication(ActionContext ac, string jwt, bool throwErrors) { using (AuthLogic.Disable()) { try { var ada = (ActiveDirectoryAuthorizer)AuthLogic.Authorizer !; if (!ada.GetConfig().LoginWithAzureAD) { return(false); } var principal = ValidateToken(jwt, out var jwtSecurityToken); var ctx = new AzureClaimsAutoCreateUserContext(principal); UserEntity?user = Database.Query <UserEntity>().SingleOrDefault(a => a.Mixin <UserOIDMixin>().OID == ctx.OID); if (user == null) { user = Database.Query <UserEntity>().SingleOrDefault(a => a.UserName == ctx.UserName) ?? (ctx.UserName.Contains("@") && ada.GetConfig().AllowMatchUsersBySimpleUserName ? Database.Query <UserEntity>().SingleOrDefault(a => a.Email == ctx.UserName || a.UserName == ctx.UserName.Before("@")) : null); if (user != null) { using (AuthLogic.Disable()) using (OperationLogic.AllowSave <UserEntity>()) { user.Mixin <UserOIDMixin>().OID = ctx.OID; user.UserName = ctx.UserName; user.Email = ctx.EmailAddress; if (!UserOIDMixin.AllowUsersWithPassswordAndOID) { user.PasswordHash = null; } user.Save(); } } } if (user == null) { user = ada.OnAutoCreateUser(ctx); if (user == null) { return(false); } } AuthServer.OnUserPreLogin(ac, user); AuthServer.AddUserSession(ac, user); return(true); } catch (Exception ex) { ex.LogException(); if (throwErrors) { throw; } return(false); } } }