public async Task <IActionResult> Authenticate([FromForm] AuthenticateRequest model) { try { _logger.LogDebug("Users controller Authenticate('{Username}')", model?.Username); if (model == null) { return(BadRequest(new ErrorResponse("No auth data provided"))); } var res = string.IsNullOrWhiteSpace(model.Token) ? await _usersManager.Authenticate(model.Username, model.Password) : await _usersManager.Authenticate(model.Token); if (res == null) { return(Unauthorized(new ErrorResponse("Unauthorized"))); } return(Ok(res)); } catch (Exception ex) { _logger.LogError(ex, "Exception in Users controller Authenticate('{Username}')", model?.Username); return(ExceptionResult(ex)); } }
override public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) { HttpContext httpContext = context.HttpContext; string authHeader = httpContext.Request.Headers["Authorization"]; try { if (authHeader != null && authHeader.StartsWith("Basic")) { string encodedUsernamePassword = authHeader.Substring("Basic ".Length).Trim(); Encoding encoding = Encoding.GetEncoding("iso-8859-1"); string usernamePassword = encoding.GetString(Convert.FromBase64String(encodedUsernamePassword)); int seperatorIndex = usernamePassword.IndexOf(':'); var username = usernamePassword.Substring(0, seperatorIndex); var password = usernamePassword.Substring(seperatorIndex + 1); var res = await _usersManager.Authenticate(username, password); if (res != null) { var user = await _userManager.FindByNameAsync(res.Username); var isAdmin = await _userManager.IsInRoleAsync(user, ApplicationDbContext.AdminRoleName); httpContext.Response.Cookies.Append(_settings.AuthCookieName, res.Token); var identity = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, user.Id), new Claim(ApplicationDbContext.AdminRoleName.ToLowerInvariant(), isAdmin.ToString()), }, "authenticated"); var principal = new ClaimsPrincipal(identity); httpContext.User = principal; } } } catch (FormatException) { // Invalid auth header chars // Do nothing } await next(); }
public async Task <IActionResult> OnPostAsync() { if (ModelState.IsValid) { User user = await usersManager.Authenticate(Input.Login, Input.Password); if (user == null) { FormError = "Niepoprawne dane logowania!"; return(Page()); } if (user.VerificationCode != "0") { FormError = "Konto nie zostało jeszcze aktywowane!"; return(Page()); } var claims = new List <Claim> { new Claim(ClaimTypes.Name, user.Login), new Claim(ClaimTypes.Email, user.Email), new Claim(ClaimTypes.NameIdentifier, user.ID.ToString()) }; var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme); await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity), new AuthenticationProperties { IsPersistent = Input.RememberMe }); FormSuccess = "Zostałeś poprawnie zalogowany!"; return(LocalRedirect("/Panel/Index")); } return(Page()); }