/// <summary> /// Validates the resource owner password credential /// </summary> /// <param name="context">The context.</param> /// <returns>Returns nothing, but update the context.</returns> /// <exception cref="ArgumentException">Subject ID not set - SubjectId</exception> public Task ValidateAsync(ResourceOwnerPasswordValidationContext context) { var user = _users.ValidateCredentials(context.UserName, context.Password); if (user != null) { context.Result = new GrantValidationResult( user.SubjectId ?? throw new ArgumentException("Subject ID not set", nameof(user.SubjectId)), OidcConstants.AuthenticationMethods.Password, _clock.UtcNow.UtcDateTime, user.Claims); } return(Task.CompletedTask); }
public async Task <IActionResult> Login(LoginInputModel model, string button) { if (button != "login") { // the user clicked the "cancel" button var context = await _interaction.GetAuthorizationContextAsync(model.ReturnUrl); if (context != null) { // if the user cancels, send a result back into IdentityServer as if they // denied the consent (even if this client does not require consent). // this will send back an access denied OIDC error response to the client. await _interaction.GrantConsentAsync(context, ConsentResponse.Denied); // we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null return(Redirect(model.ReturnUrl)); } else { // since we don't have a valid context, then we just go back to the home page return(Redirect("~/")); } } if (ModelState.IsValid) { // validate username/password against Ldap var user = _userStore.ValidateCredentials(model.Username, model.Password); if (user != default(IAppUser)) { await _events.RaiseAsync(new UserLoginSuccessEvent(user.Username, user.SubjectId, user.Username)); // only set explicit expiration here if user chooses "remember me". // otherwise we rely upon expiration configured in cookie middleware. AuthenticationProperties props = null; if (AccountOptions.AllowRememberLogin && model.RememberLogin) { props = new AuthenticationProperties { IsPersistent = true, ExpiresUtc = DateTimeOffset.UtcNow.Add(AccountOptions.RememberMeLoginDuration) }; } ; // issue authentication cookie with subject ID and username await HttpContext.SignInAsync(user.SubjectId, user.Username, props); // make sure the returnUrl is still valid, and if so redirect back to authorize endpoint or a local page if (_interaction.IsValidReturnUrl(model.ReturnUrl) || Url.IsLocalUrl(model.ReturnUrl)) { return(Redirect(model.ReturnUrl)); } return(Redirect("~/")); } await _events.RaiseAsync(new UserLoginFailureEvent(model.Username, "invalid credentials")); ModelState.AddModelError("", AccountOptions.InvalidCredentialsErrorMessage); } // something went wrong, show form with error var vm = await _account.BuildLoginViewModelAsync(model); return(View(vm)); }
public async Task <IActionResult> Login(LoginInputModel model) { var returnUrl = model.ReturnUrl; ViewData["ReturnUrl"] = returnUrl; if (ModelState.IsValid) { var user = _userStore.ValidateCredentials(model.Email, model.Password); if (user != default(IAppUser)) { await _events.RaiseAsync(new UserLoginSuccessEvent(user.Username, user.SubjectId, user.Username)); AuthenticationProperties props = null; if (model.RememberLogin) { props = new AuthenticationProperties { IsPersistent = true, ExpiresUtc = DateTimeOffset.UtcNow.Add(TimeSpan.FromDays(365)) }; } ; var identityUser = await _userManager.FindByNameAsync(user.Username); if (identityUser == null) { identityUser = new ApplicationUser(user.Username, user.Username); identityUser.Favorites.Add(new FavoriteColor { ColorName = "Green", RGB = "0,255,0" }); if (user.Username.ToLower() == "bender") { var role = await _roleManager.FindByNameAsync("Admin"); identityUser.Roles.Add(role.Id); } var result = await _userManager.CreateAsync(identityUser); if (!result.Succeeded) { throw new Exception("Couldn't create user"); } } //var claimsPrincipal = new ClaimsIdentity() //await HttpContext.SignInAsync() //// issue authentication cookie with subject ID and username //await HttpContext.SignInAsync(user.SubjectId, user.Username, props); await _signInManager.SignInAsync(identityUser, true); return(RedirectToLocal(returnUrl)); } //// This doesn't count login failures towards account lockout //// To enable password failures to trigger account lockout, set lockoutOnFailure: true //var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberLogin, lockoutOnFailure: false); //if (result.Succeeded) //{ // _logger.LogInformation(1, "User logged in."); // return RedirectToLocal(returnUrl); //} ////if (result.RequiresTwoFactor) ////{ //// return RedirectToAction(nameof(VerifyCode), new { ReturnUrl = returnUrl, RememberMe = model.RememberLogin }); ////} //if (result.IsLockedOut) //{ // _logger.LogWarning(2, "User account locked out."); // return View("Lockout"); //} //else //{ // ModelState.AddModelError(string.Empty, "Invalid login attempt."); // return View(await BuildLoginViewModelAsync(model)); //} } // If we got this far, something failed, redisplay form return(View(await BuildLoginViewModelAsync(model))); }
public async Task <IActionResult> Login(LoginInputModel model, string button) { // check if we are in the context of an authorization request var context = await _interaction.GetAuthorizationContextAsync(model.ReturnUrl); // the user clicked the "cancel" button if (button != "login") { if (context != null) { // if the user cancels, send a result back into IdentityServer as if they // denied the consent (even if this client does not require consent). // this will send back an access denied OIDC error response to the client. await _interaction.DenyAuthorizationAsync(context, AuthorizationError.AccessDenied); // we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null if (context.IsNativeClient()) { // The client is native, so this change in how to // return the response is for better UX for the end user. return(this.LoadingPage("Redirect", model.ReturnUrl)); } return(Redirect(model.ReturnUrl)); } else { // since we don't have a valid context, then we just go back to the home page return(Redirect("~/")); } } if (ModelState.IsValid) { // validate username/password against in-memory store var user = _users.ValidateCredentials(model.Username, model.Password); if (user != default(IAppUser)) { //var user = _users.FindByUsername(model.Username); await _events.RaiseAsync(new UserLoginSuccessEvent(user.Username, user.SubjectId, user.Username, clientId : context?.Client.ClientId)); // only set explicit expiration here if user chooses "remember me". // otherwise we rely upon expiration configured in cookie middleware. AuthenticationProperties props = null; if (AccountOptions.AllowRememberLogin && model.RememberLogin) { props = new AuthenticationProperties { IsPersistent = true, ExpiresUtc = DateTimeOffset.UtcNow.Add(AccountOptions.RememberMeLoginDuration) }; } ; // issue authentication cookie with subject ID and username var isuser = new IdentityServerUser(user.SubjectId) { DisplayName = user.Username }; await HttpContext.SignInAsync(isuser, props); if (context != null) { if (context.IsNativeClient()) { // The client is native, so this change in how to // return the response is for better UX for the end user. return(this.LoadingPage("Redirect", model.ReturnUrl)); } // we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null return(Redirect(model.ReturnUrl)); } // request for a local page if (Url.IsLocalUrl(model.ReturnUrl)) { return(Redirect(model.ReturnUrl)); } else if (string.IsNullOrEmpty(model.ReturnUrl)) { return(Redirect("~/")); } else { // user might have clicked on a malicious link - should be logged throw new Exception("invalid return URL"); } } await _events.RaiseAsync(new UserLoginFailureEvent(model.Username, "invalid credentials", clientId : context?.Client.ClientId)); ModelState.AddModelError(string.Empty, AccountOptions.InvalidCredentialsErrorMessage); } // something went wrong, show form with error var vm = await BuildLoginViewModelAsync(model); return(View(vm)); }