public static bool LoginFromCookie(ActionContext ac) { using (AuthLogic.Disable()) { try { if (!ac.HttpContext.Request.Cookies.TryGetValue(CookieName, out string ticketText) || !ticketText.HasText()) { return(false); //there is no cookie } var httpConnection = ac.HttpContext.Features.Get <IHttpConnectionFeature>(); UserEntity user = UserTicketLogic.UpdateTicket(httpConnection.RemoteIpAddress.ToString(), ref ticketText); AuthServer.OnUserPreLogin(ac, user); ac.HttpContext.Response.Cookies.Append(CookieName, ticketText, new CookieOptions { Domain = ac.HttpContext.Request.Host.Host.ToString(), Path = new UrlHelper(ac).Content("~/"), Expires = DateTime.UtcNow.Add(UserTicketLogic.ExpirationInterval), }); AuthServer.AddUserSession(ac, user); return(true); } catch { //Remove cookie RemoveCookie(ac); return(false); } } }
public static bool LoginAzureADAuthentication(ActionContext ac, string jwt) { 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().AllowSimpleUserNames ? Database.Query <UserEntity>().SingleOrDefault(a => a.UserName == ctx.UserName.Before("@")) : null); if (user != null && user.Mixin <UserOIDMixin>().OID == null) { user.Mixin <UserOIDMixin>().OID = ctx.OID; using (AuthLogic.Disable()) using (OperationLogic.AllowSave <UserEntity>()) { 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 { return(false); } } }
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 <UserADMixin>().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) { user = ada.OnAutoCreateUser(ctx); if (user == null) { return(false); } } else { ada.UpdateUser(user, ctx); } AuthServer.OnUserPreLogin(ac, user); AuthServer.AddUserSession(ac, user); return(true); } catch (Exception ex) { ex.LogException(); if (throwErrors) { throw; } return(false); } } }
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 ActiveDirectoryAuthorizer ada && !ada.GetConfig().LoginWithWindowsAuthenticator) { return($"{ReflectionTools.GetPropertyInfo(() => ada.GetConfig().LoginWithWindowsAuthenticator)} is set to false"); } UserEntity?user = AuthLogic.RetrieveUser(wp.Identity.Name !); if (user == null) { if (AutoCreateUser == null) { return("AutoCreateUser is null"); } user = AutoCreateUser(wp); if (user == null) { return("AutoCreateUser returned null"); } } AuthServer.OnUserPreLogin(ac, user); AuthServer.AddUserSession(ac, user); return(null); } catch (Exception e) { e.LogException(); return(e.Message); } } }
public static bool LoginFromCookie() { using (AuthLogic.Disable()) { try { var authCookie = System.Web.HttpContext.Current.Request.Cookies[CookieName]; if (authCookie == null || !authCookie.Value.HasText()) { return(false); //there is no cookie } string ticketText = authCookie.Value; UserEntity user = UserTicketLogic.UpdateTicket( System.Web.HttpContext.Current.Request.UserHostAddress, ref ticketText); AuthServer.OnUserPreLogin(null, user); System.Web.HttpContext.Current.Response.Cookies.Add(new HttpCookie(CookieName, ticketText) { Expires = DateTime.UtcNow.Add(UserTicketLogic.ExpirationInterval), HttpOnly = true, Domain = System.Web.HttpContext.Current.Request.Url.Host }); AuthServer.AddUserSession(user); return(true); } catch { //Remove cookie HttpCookie cookie = new HttpCookie(CookieName) { Expires = DateTime.UtcNow.AddDays(-10), // or any other time in the past HttpOnly = true, Domain = System.Web.HttpContext.Current.Request.Url.Host }; System.Web.HttpContext.Current.Response.Cookies.Set(cookie); return(false); } } }
public static bool LoginWindowsAuthentication(ActionContext ac) { using (AuthLogic.Disable()) { try { if (!(ac.HttpContext.User is WindowsPrincipal wp)) { return(false); } if (AuthLogic.Authorizer is ActiveDirectoryAuthorizer ada && !ada.GetConfig().LoginWithWindowsAuthenticator) { return(false); } UserEntity?user = AuthLogic.RetrieveUser(wp.Identity.Name); if (user == null) { if (AutoCreateUser == null) { return(false); } user = AutoCreateUser(wp); if (user == null) { return(false); } } AuthServer.OnUserPreLogin(ac, user); AuthServer.AddUserSession(ac, user); return(true); } catch { return(false); } } }
public async Task <LoginResponse> MakeAssertion([FromBody][Required] MakeAssertionRequest request) { using (AuthLogic.Disable()) using (Transaction tr = new Transaction()) { var assertionOptions = Database.Retrieve <WebAuthnAssertionOptionsEntity>(request.AssertionOptionsId); var options = AssertionOptions.FromJson(assertionOptions.Json); var cred = Database.Query <WebAuthnCredentialEntity>().SingleEx(cred => cred.CredentialId == request.AssertionRawResponse.Id); var res = await fido2.MakeAssertionAsync(request.AssertionRawResponse, options, cred.PublicKey, (uint)cred.Counter, (args) => { if (!MemoryExtensions.SequenceEqual <byte>(cred.CredentialId, args.CredentialId)) { return(Task.FromResult(false)); } var userId = Encoding.UTF8.GetBytes(cred.User.Id.ToString()); if (!MemoryExtensions.SequenceEqual <byte>(userId, args.UserHandle)) { return(Task.FromResult(false)); } return(Task.FromResult(true)); }); cred.Counter++; cred.Save(); var user = cred.User.RetrieveAndForget(); AuthServer.OnUserPreLogin(ControllerContext, user); AuthServer.AddUserSession(ControllerContext, user); var token = AuthTokenServer.CreateToken(user); return(tr.Commit(new LoginResponse { userEntity = user, token = token, authenticationType = "webauthn" })); } }
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); } } }