public static async Task<IndexViewModel> ToViewModel(this ApplicationUser user, UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager) { var result = new IndexViewModel { HasPassword = await userManager.HasPasswordAsync(user), EmailAddress = user.Email, IsEmailAddressConfirmed = user.EmailConfirmed, IsPhoneNumberConfirmed = user.PhoneNumberConfirmed, PhoneNumber = await userManager.GetPhoneNumberAsync(user), TwoFactor = await userManager.GetTwoFactorEnabledAsync(user), Logins = await userManager.GetLoginsAsync(user), BrowserRemembered = await signInManager.IsTwoFactorClientRememberedAsync(user), AssociatedSkills = user.AssociatedSkills, TimeZoneId = user.TimeZoneId, Name = user.Name, ProposedNewEmailAddress = user.PendingNewEmail }; return result; }
public static async Task<IndexViewModel> ToViewModel(this ApplicationUser user, UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager) { var profileCompletenessWarnings = user.ValidateProfileCompleteness(); var result = new IndexViewModel { HasPassword = await userManager.HasPasswordAsync(user), EmailAddress = user.Email, IsEmailAddressConfirmed = user.EmailConfirmed, IsPhoneNumberConfirmed = user.PhoneNumberConfirmed, PhoneNumber = await userManager.GetPhoneNumberAsync(user), TwoFactor = await userManager.GetTwoFactorEnabledAsync(user), Logins = await userManager.GetLoginsAsync(user), BrowserRemembered = await signInManager.IsTwoFactorClientRememberedAsync(user), AssociatedSkills = user.AssociatedSkills, TimeZoneId = user.TimeZoneId, FirstName = user.FirstName, LastName = user.LastName, ProposedNewEmailAddress = user.PendingNewEmail, IsProfileComplete = user.IsProfileComplete(), ProfileCompletenessWarnings = profileCompletenessWarnings.Select(p => p.ErrorMessage) }; return result; }
public async Task <IActionResult> Index(ManageMessageId?message = null) { ViewData["StatusMessage"] = message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed." : message == ManageMessageId.SetPasswordSuccess ? "Your password has been set." : message == ManageMessageId.SetTwoFactorSuccess ? "Your two-factor authentication provider has been set." : message == ManageMessageId.Error ? "An error has occurred." : message == ManageMessageId.AddPhoneSuccess ? "Your phone number was added." : message == ManageMessageId.RemovePhoneSuccess ? "Your phone number was removed." : ""; var user = await GetCurrentUserAsync(); var model = new IndexViewModel { HasPassword = await _userManager.HasPasswordAsync(user), PhoneNumber = await _userManager.GetPhoneNumberAsync(user), TwoFactor = await _userManager.GetTwoFactorEnabledAsync(user), Logins = await _userManager.GetLoginsAsync(user), BrowserRemembered = await _signInManager.IsTwoFactorClientRememberedAsync(user) }; return(View(model)); }
public virtual async Task <bool> GetTwoFactorEnabledAsync(int userId) { return(await _userManager.GetTwoFactorEnabledAsync(userId).ConfigureAwait(false)); }
public void TwoFactorEnabled() { using (UserStore<IdentityUser> store = new UserStore<IdentityUser>()) { using (UserManager<IdentityUser> manager = new UserManager<IdentityUser>(store)) { var user = User; bool twoFactorEnabled = true; var taskTwoFactorEnabledSet = manager.SetTwoFactorEnabledAsync(user.Id, twoFactorEnabled); taskTwoFactorEnabledSet.Wait(); Assert.IsTrue(taskTwoFactorEnabledSet.Result.Succeeded, string.Concat(taskTwoFactorEnabledSet.Result.Errors)); var taskUser = manager.GetTwoFactorEnabledAsync(user.Id); taskUser.Wait(); Assert.AreEqual<bool>(twoFactorEnabled, taskUser.Result, "TwoFactorEnabled not true"); try { var task = store.GetTwoFactorEnabledAsync(null); task.Wait(); } catch (Exception ex) { Assert.IsNotNull(ex, "Argument exception not raised"); } try { var task = store.SetTwoFactorEnabledAsync(null, twoFactorEnabled); task.Wait(); } catch (Exception ex) { Assert.IsNotNull(ex, "Argument exception not raised"); } } } }
public override Task <bool> CanGenerateTwoFactorTokenAsync(UserManager <ApplicationUser> manager, ApplicationUser user) { return(manager.GetTwoFactorEnabledAsync(user)); }
private async Task <IActionResult> ExchangePasswordGrantType(OpenIdConnectRequest request) { var user = await _userManager.FindByNameAsync(request.Username); if (user == null) { return(BadRequest(new OpenIdConnectResponse { Error = OpenIdConnectConstants.Errors.InvalidGrant, ErrorDescription = T["The username/password couple is invalid."] })); } // Ensure the user is allowed to sign in. if (!await _signInManager.CanSignInAsync(user)) { return(BadRequest(new OpenIdConnectResponse { Error = OpenIdConnectConstants.Errors.InvalidGrant, ErrorDescription = T["The specified user is not allowed to sign in."] })); } // Reject the token request if two-factor authentication has been enabled by the user. if (_userManager.SupportsUserTwoFactor && await _userManager.GetTwoFactorEnabledAsync(user)) { return(BadRequest(new OpenIdConnectResponse { Error = OpenIdConnectConstants.Errors.InvalidGrant, ErrorDescription = T["The specified user is not allowed to sign in."] })); } // Ensure the user is not already locked out. if (_userManager.SupportsUserLockout && await _userManager.IsLockedOutAsync(user)) { return(BadRequest(new OpenIdConnectResponse { Error = OpenIdConnectConstants.Errors.InvalidGrant, ErrorDescription = T["The username/password couple is invalid."] })); } // Ensure the password is valid. if (!await _userManager.CheckPasswordAsync(user, request.Password)) { if (_userManager.SupportsUserLockout) { await _userManager.AccessFailedAsync(user); } return(BadRequest(new OpenIdConnectResponse { Error = OpenIdConnectConstants.Errors.InvalidGrant, ErrorDescription = T["The username/password couple is invalid."] })); } if (_userManager.SupportsUserLockout) { await _userManager.ResetAccessFailedCountAsync(user); } var ticket = await CreateTicketAsync(request, user); return(SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme)); }
public async Task <bool> GetTwoFactorEnabledAsync(dynamic user) { return(await UserManager.GetTwoFactorEnabledAsync(user)); }
public Task <bool> GetTwoFactorEnabledAsync(T user) { return(u.GetTwoFactorEnabledAsync(user)); }
public async Task <IActionResult> Exchange(OpenIdConnectRequest request) { Debug.Assert(request.IsTokenRequest(), "The OpenIddict binder for ASP.NET Core MVC is not registered. " + "Make sure services.AddOpenIddict().AddMvcBinders() is correctly called."); if (request.IsPasswordGrantType()) { var user = await _userManager.FindByNameAsync(request.Username); if (user == null) { return(BadRequest(new OpenIdConnectResponse { Error = OpenIdConnectConstants.Errors.InvalidGrant, ErrorDescription = "The username/password couple is invalid." })); } // Ensure the user is allowed to sign in. if (!await _signInManager.CanSignInAsync(user)) { return(BadRequest(new OpenIdConnectResponse { Error = OpenIdConnectConstants.Errors.InvalidGrant, ErrorDescription = "The specified user is not allowed to sign in." })); } // Reject the token request if two-factor authentication has been enabled by the user. if (_userManager.SupportsUserTwoFactor && await _userManager.GetTwoFactorEnabledAsync(user)) { return(BadRequest(new OpenIdConnectResponse { Error = OpenIdConnectConstants.Errors.InvalidGrant, ErrorDescription = "The specified user is not allowed to sign in." })); } // Ensure the user is not already locked out. if (_userManager.SupportsUserLockout && await _userManager.IsLockedOutAsync(user)) { return(BadRequest(new OpenIdConnectResponse { Error = OpenIdConnectConstants.Errors.InvalidGrant, ErrorDescription = "The username/password couple is invalid." })); } // Ensure the password is valid. if (!await _userManager.CheckPasswordAsync(user, request.Password)) { if (_userManager.SupportsUserLockout) { await _userManager.AccessFailedAsync(user); } return(BadRequest(new OpenIdConnectResponse { Error = OpenIdConnectConstants.Errors.InvalidGrant, ErrorDescription = "The username/password couple is invalid." })); } // The user is now validated, so reset lockout counts, if necessary if (_userManager.SupportsUserLockout) { await _userManager.ResetAccessFailedCountAsync(user); } // Create a new authentication ticket. var ticket = await CreateTicketAsync(request, user); return(SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme)); } return(BadRequest(new OpenIdConnectResponse { Error = OpenIdConnectConstants.Errors.UnsupportedGrantType, ErrorDescription = "The specified grant type is not supported." })); }
public virtual Task <bool> GetTwoFactorEnabled(TUser user) => UserManager.GetTwoFactorEnabledAsync(user);
public async Task <IActionResult> Token([ModelBinder(BinderType = typeof(OpenIddictMvcBinder))] OpenIdConnectRequest model) { try { if (model.IsPasswordGrantType()) { var applicationUser = await _userManager.FindByNameAsync(model.Username); if (applicationUser is null) { return(BadRequest(new OpenIdConnectResponse { Error = OpenIdConnectConstants.Errors.InvalidGrant, ErrorDescription = "Login or password is incorrect." })); } // Ensure the user is allowed to sign in. if (!await _signInManager.CanSignInAsync(applicationUser) || applicationUser.IsDeleted) { return(BadRequest(new OpenIdConnectResponse { Error = OpenIdConnectConstants.Errors.AccessDenied, ErrorDescription = "You are not allowed to sign in." })); } // Reject the token request if two-factor authentication has been enabled by the user. if (_userManager.SupportsUserTwoFactor && await _userManager.GetTwoFactorEnabledAsync(applicationUser)) { return(BadRequest(new OpenIdConnectResponse { Error = OpenIdConnectConstants.Errors.AccessDenied, ErrorDescription = "You are not allowed to sign in." })); } // Ensure the user is not already locked out. if (_userManager.SupportsUserLockout && await _userManager.IsLockedOutAsync(applicationUser)) { return(BadRequest(new OpenIdConnectResponse { Error = OpenIdConnectConstants.Errors.AccessDenied, ErrorDescription = "Your profile is temporary locked." })); } // Ensure the password is valid. if (!await _userManager.CheckPasswordAsync(applicationUser, model.Password)) { if (_userManager.SupportsUserLockout) { await _userManager.AccessFailedAsync(applicationUser); } return(BadRequest(new OpenIdConnectResponse { Error = OpenIdConnectConstants.Errors.InvalidGrant, ErrorDescription = "Login or password is incorrect." })); } if (_userManager.SupportsUserLockout) { await _userManager.ResetAccessFailedCountAsync(applicationUser); } applicationUser.LastLoginDate = Clock.Now; await _userManager.UpdateAsync(applicationUser); var ticket = await CreateTicketAsync(model, applicationUser); return(SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme)); } // Create a new authentication ticket. //var ticket = await CreateTicketAsync(model, applicationUser, isAdUser: isAdUser); //return SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme); else if (model.IsRefreshTokenGrantType()) { // Retrieve the claims principal stored in the refresh token. var info = await HttpContext.AuthenticateAsync( OpenIddictServerDefaults.AuthenticationScheme); // Retrieve the user profile corresponding to the refresh token. // Note: if you want to automatically invalidate the refresh token // when the user password/roles change, use the following line instead: // var user = _signInManager.ValidateSecurityStampAsync(info.Principal); var user = await _userManager.GetUserAsync(info.Principal); if (user == null) { return(BadRequest(new OpenIdConnectResponse { Error = OpenIdConnectConstants.Errors.InvalidGrant, ErrorDescription = "The refresh token is no longer valid." })); } // Ensure the user is still allowed to sign in. if (!await _signInManager.CanSignInAsync(user)) { return(BadRequest(new OpenIdConnectResponse { Error = OpenIdConnectConstants.Errors.InvalidGrant, ErrorDescription = "The user is no longer allowed to sign in." })); } // Create a new authentication ticket, but reuse the properties stored // in the refresh token, including the scopes originally granted. var ticket = await CreateTicketAsync(model, user, info.Properties); return(SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme)); } return(BadRequest(new OpenIdConnectResponse { Error = OpenIdConnectConstants.Errors.UnsupportedGrantType, ErrorDescription = "The specified grant type is not supported." })); } catch (Exception ex) { return(HandleError(ex)); } }
public async Task <IActionResult> Exchange(OpenIdConnectRequest request) { if (request.IsPasswordGrantType()) { var user = await _userManager.FindByNameAsync(request.Username); if (user == null) { return(BadRequest(new OpenIdConnectResponse { Error = OpenIdConnectConstants.Errors.InvalidGrant, ErrorDescription = "The username/password couple is invalid." })); } // Ensure the user is allowed to sign in. if (!await _signInManager.CanSignInAsync(user)) { return(BadRequest(new OpenIdConnectResponse { Error = OpenIdConnectConstants.Errors.InvalidGrant, ErrorDescription = "The specified user is not allowed to sign in." })); } // Reject the token request if two-factor authentication has been enabled by the user. if (_userManager.SupportsUserTwoFactor && await _userManager.GetTwoFactorEnabledAsync(user)) { return(BadRequest(new OpenIdConnectResponse { Error = OpenIdConnectConstants.Errors.InvalidGrant, ErrorDescription = "The specified user is not allowed to sign in." })); } // Ensure the user is not already locked out. if (_userManager.SupportsUserLockout && await _userManager.IsLockedOutAsync(user)) { return(BadRequest(new OpenIdConnectResponse { Error = OpenIdConnectConstants.Errors.InvalidGrant, ErrorDescription = "The username/password couple is invalid." })); } // Ensure the password is valid. if (!await _userManager.CheckPasswordAsync(user, request.Password)) { if (_userManager.SupportsUserLockout) { await _userManager.AccessFailedAsync(user); } return(BadRequest(new OpenIdConnectResponse { Error = OpenIdConnectConstants.Errors.InvalidGrant, ErrorDescription = "The username/password couple is invalid." })); } if (_userManager.SupportsUserLockout) { await _userManager.ResetAccessFailedCountAsync(user); } // Create a new authentication ticket. var ticket = await CreateTicketAsync(request, user); return(SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme)); } else if (request.GrantType == "urn:ietf:params:oauth:grant-type:external_identity_token") { //Assertion should be the access_token // Reject the request if the "assertion" parameter is missing. if (string.IsNullOrEmpty(request.Assertion)) { return(BadRequest(new OpenIdConnectResponse { Error = OpenIdConnectConstants.Errors.InvalidRequest, ErrorDescription = "The mandatory 'assertion' parameter was missing." })); } ; ExternalAuthProviders provider; var providerExists = Enum.TryParse(request["provider"].ToString(), out provider); if (!providerExists) { return(BadRequest(new OpenIdConnectResponse { Error = OpenIdConnectConstants.Errors.InvalidRequest, ErrorDescription = "The mandatory 'provider' parameter was missing." })); } ; var isValid = await _externalAuthManager.VerifyExternalAccessToken(request.Assertion, provider); if (!isValid) { return(BadRequest(new OpenIdConnectResponse { Error = OpenIdConnectConstants.Errors.InvalidRequest, ErrorDescription = "Invalid access_token, this usually happens when it is expired" })); } var profile = await _externalAuthManager.GetProfile(request.Assertion, provider); var user = await _userManager.FindByEmailAsync(profile.email); if (user == null) { return(BadRequest(new OpenIdConnectResponse { Error = OpenIdConnectConstants.Errors.InvalidGrant, ErrorDescription = "The user does not exist" })); } var ticket = await CreateTicketAsync(request, user); // Create a new ClaimsIdentity containing the claims that // will be used to create an id_token and/or an access token. //var identity = new ClaimsIdentity(OpenIdConnectServerDefaults.AuthenticationScheme); // Manually validate the identity token issued by Google, // including the issuer, the signature and the audience. // Then, copy the claims you need to the "identity" instance. // Create a new authentication ticket holding the user identity. //var ticket = new AuthenticationTicket( // new ClaimsPrincipal(identity), // new AuthenticationProperties(), // OpenIdConnectServerDefaults.AuthenticationScheme); //ticket.SetScopes( // OpenIdConnectConstants.Scopes.OpenId, // OpenIdConnectConstants.Scopes.OfflineAccess); return(SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme)); } return(BadRequest(new OpenIdConnectResponse { Error = OpenIdConnectConstants.Errors.UnsupportedGrantType, ErrorDescription = "The specified grant type is not supported." })); }
public async Task <IActionResult> Login(LoginModel model) { if (ModelState.IsValid) { var user = await _userManager.FindByNameAsync(model.UserName); // OBS: IsLockedOutAsync faz parte da configuração de 'options.Lockout' em startup. if (user != null && !await _userManager.IsLockedOutAsync(user)) { if (await _userManager.CheckPasswordAsync(user, model.Password)) { if (!await _userManager.IsEmailConfirmedAsync(user)) { ModelState.AddModelError("", "E-mail não esta válido!"); return(View()); } await _userManager.ResetAccessFailedCountAsync(user); if (await _userManager.GetTwoFactorEnabledAsync(user)) { var validator = await _userManager.GetValidTwoFactorProvidersAsync(user); if (validator.Contains("Email")) { var token = await _userManager.GenerateTwoFactorTokenAsync(user, "Email"); System.IO.File.WriteAllText("email2sv.txt", token); await HttpContext.SignInAsync(IdentityConstants.TwoFactorUserIdScheme, Store2FA(user.Id, "Email")); return(RedirectToAction("TwoFactor")); } } var principal = await _userClaimsPrincipalFactory.CreateAsync(user); await HttpContext.SignInAsync(IdentityConstants.ApplicationScheme, principal); return(RedirectToAction("About")); // --- O _signInManager faz a mesma coisa que o codigo acima - SIGNIN MANAGER INICIO //var signInResult = await _signInManager.PasswordSignInAsync( // model.UserName, model.Password, false, false); //if(signInResult.Succeeded) //{ // return RedirectToAction("About"); //} // --- SIGNIN MANAGER FIM } await _userManager.AccessFailedAsync(user); await _userManager.GetAccessFailedCountAsync(user); if (await _userManager.IsLockedOutAsync(user)) { //E-mail deve ser enviado com sugestão de mudança de senha! } } ModelState.AddModelError("", "Usuário ou senha invalida"); } return(View()); }
public async Task <IActionResult> Login(Login model) { if (ModelState.IsValid) { #region Forma de Logar A var user = await _userManager.FindByNameAsync(model.UserName); var paswordCheck = await _userManager.CheckPasswordAsync(user, model.Password); var emailCheck = await _userManager.IsEmailConfirmedAsync(user); var lockCheck = await _userManager.IsLockedOutAsync(user); var twoFactorCheck = await _userManager.GetTwoFactorEnabledAsync(user); if (lockCheck == false) { if (user != null) { if (paswordCheck == true) { if (emailCheck == true) { await _userManager.ResetAccessFailedCountAsync(user); if (twoFactorCheck == true) { var validator = await _userManager.GetValidTwoFactorProvidersAsync(user); if (validator.Contains("Email")) { var token = await _userManager.GenerateTwoFactorTokenAsync(user, "Email"); System.IO.File.WriteAllText("email2sv.txt", token); await HttpContext.SignInAsync(IdentityConstants.TwoFactorUserIdScheme, Store2FA(user.Id, "Email")); return(RedirectToAction("TwoFactor")); } } var principal = await _userClaimsPrincipalFactory.CreateAsync(user); await HttpContext.SignInAsync(IdentityConstants.ApplicationScheme, principal); return(RedirectToAction("About")); } else { ModelState.AddModelError("", "O Email não foi confirmado!"); } } else { ModelState.AddModelError("", "Senha inválida!"); } } else { ModelState.AddModelError("", "Usuário inválido!"); } } else { ModelState.AddModelError("", "Usuário bloqueado, aguarde..."); await _userManager.AccessFailedAsync(user); //Enviar sugestão para troca de email aqui } #endregion #region Forma de Logar B //// Outra Forma de Logar // Salva o estado de login no cookie (manter logado após fechar browser) [true = manter | false = não manter] //var persistLogin = false; // Bloquear a conta do usuário após tentativas sem sucesso de logar [true = bloquear | false = não bloquear] //var lockUser = false; //var signInResult = await _signInManager.PasswordSignInAsync(model.UserName, model.Password, persistLogin, lockUser); //if (signInResult.Succeeded) //{ // return RedirectToAction("About"); //} #endregion } return(View()); }
public async Task <IActionResult> ExchangeAsync(OpenIdConnectRequest request) { // Reject the token request if client_id or client_secret is missing. /* if (string.IsNullOrEmpty(request.ClientId) || string.IsNullOrEmpty(request.ClientSecret)) * { * return BadRequest(new OpenIdConnectResponse * { * Error = OpenIdConnectConstants.Errors.InvalidRequest, * ErrorDescription = "Missing credentials: ensure that your credentials were correctly " + * "flowed in the request body or in the authorization header" * }); * } */ // Retrieve the application details from the database. /* var application = await _applicationManager.FindByClientIdAsync(request.ClientId, HttpContext.RequestAborted); * * if (application == null) * { * return BadRequest(new OpenIdConnectResponse * { * Error = OpenIdConnectConstants.Errors.InvalidClient, * ErrorDescription = "The credentials is invalid." * }); * } */ if (request.IsPasswordGrantType()) { /* if (!string.Equals(application.Type, OpenIddictConstants.ClientTypes.Confidential, StringComparison.Ordinal)) * { * return BadRequest(new OpenIdConnectResponse * { * Error = OpenIdConnectConstants.Errors.InvalidClient, * ErrorDescription = "Only confidential clients are allowed to use password grant type." * }); * } */ var user = _ctx.Users .Where(x => x.Email.Equals(request.Username)) .Where(x => x.ProviderName.Equals("EMAIL")) .FirstOrDefault(); //var user = await _userManager.FindByEmailAsync(request.Username); if (user == null) { return(BadRequest(new OpenIdConnectResponse { Error = OpenIdConnectConstants.Errors.InvalidGrant, ErrorDescription = "The username/password couple is invalid." })); } var canSignIn = await _signInManager.CanSignInAsync(user); // Ensure the user is allowed to sign in. if (!canSignIn) { return(BadRequest(new OpenIdConnectResponse { Error = OpenIdConnectConstants.Errors.InvalidGrant, ErrorDescription = "The specified user is not allowed to sign in." })); } // Reject the token request if two-factor authentication has been enabled by the user. if (_userManager.SupportsUserTwoFactor && await _userManager.GetTwoFactorEnabledAsync(user)) { return(BadRequest(new OpenIdConnectResponse { Error = OpenIdConnectConstants.Errors.InvalidGrant, ErrorDescription = "The specified user is not allowed to sign in." })); } // Ensure the user is not already locked out. if (_userManager.SupportsUserLockout && await _userManager.IsLockedOutAsync(user)) { return(BadRequest(new OpenIdConnectResponse { Error = OpenIdConnectConstants.Errors.InvalidGrant, ErrorDescription = "The username/password couple is invalid." })); } // Ensure the password is valid. if (!await _userManager.CheckPasswordAsync(user, request.Password)) { if (_userManager.SupportsUserLockout) { await _userManager.AccessFailedAsync(user); } return(BadRequest(new OpenIdConnectResponse { Error = OpenIdConnectConstants.Errors.InvalidGrant, ErrorDescription = "The username/password couple is invalid." })); } if (_userManager.SupportsUserLockout) { await _userManager.ResetAccessFailedCountAsync(user); } var identity = new ClaimsIdentity(OpenIdConnectServerDefaults.AuthenticationScheme); identity.AddClaim(OpenIdConnectConstants.Claims.Subject, user.Id, OpenIdConnectConstants.Destinations.AccessToken); identity.AddClaim(OpenIdConnectConstants.Claims.Email, user.Email, OpenIdConnectConstants.Destinations.AccessToken); if (user.FirstName != null) { identity.AddClaim(OpenIdConnectConstants.Claims.GivenName, user.FirstName, OpenIdConnectConstants.Destinations.AccessToken); } if (user.LastName != null) { identity.AddClaim(OpenIdConnectConstants.Claims.FamilyName, user.LastName, OpenIdConnectConstants.Destinations.AccessToken); } var ticket = new AuthenticationTicket( new ClaimsPrincipal(identity), new AuthenticationProperties(), OpenIdConnectServerDefaults.AuthenticationScheme); ticket.SetScopes( OpenIdConnectConstants.Scopes.OpenId, OpenIdConnectConstants.Scopes.OfflineAccess, OpenIdConnectConstants.Scopes.Profile, OpenIdConnectConstants.Scopes.Email); return(SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme)); } if (request.IsAuthorizationCodeGrantType()) { // Retrieve the claims principal stored in the authorization code. var info = await HttpContext.AuthenticateAsync( OpenIdConnectServerDefaults.AuthenticationScheme); // Retrieve the user profile corresponding to the authorization code. // Note: if you want to automatically invalidate the authorization code // when the user password/roles change, use the following line instead: //var user = await _signInManager.ValidateSecurityStampAsync(info.Principal); var user = await _userManager.GetUserAsync(info.Principal); if (user == null) { return(BadRequest(new OpenIdConnectResponse { Error = OpenIdConnectConstants.Errors.InvalidGrant, ErrorDescription = "The authorization code is no longer valid." })); } // Ensure the user is still allowed to sign in. if (!await _signInManager.CanSignInAsync(user)) { return(BadRequest(new OpenIdConnectResponse { Error = OpenIdConnectConstants.Errors.InvalidGrant, ErrorDescription = "The user is no longer allowed to sign in." })); } // Create a new authentication ticket, but reuse the properties stored // in the authorization code, including the scopes originally granted. var ticket = await CreateTicketAsync(request, user, info.Properties); return(SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme)); } if (request.IsRefreshTokenGrantType()) { // Retrieve the claims principal stored in the refresh token. var info = await HttpContext.AuthenticateAsync( OpenIdConnectServerDefaults.AuthenticationScheme); // Retrieve the user profile corresponding to the refresh token. // Note: if you want to automatically invalidate the refresh token // when the user password/roles change, use the following line instead: var user = await _signInManager.ValidateSecurityStampAsync(info.Principal); //var user = await _userManager.GetUserAsync(info.Principal); if (user == null) { return(BadRequest(new OpenIdConnectResponse { Error = OpenIdConnectConstants.Errors.InvalidGrant, ErrorDescription = "The refresh token is no longer valid." })); } // Ensure the user is still allowed to sign in. if (!await _signInManager.CanSignInAsync(user)) { return(BadRequest(new OpenIdConnectResponse { Error = OpenIdConnectConstants.Errors.InvalidGrant, ErrorDescription = "The user is no longer allowed to sign in." })); } // Create a new authentication ticket, but reuse the properties stored // in the refresh token, including the scopes originally granted. var ticket = await CreateTicketAsync(request, user, info.Properties); return(SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme)); } if (request.GrantType == "urn:ietf:params:oauth:grant-type:google_identity_token") { // Reject the request if the "assertion" parameter is missing. if (string.IsNullOrEmpty(request.Assertion)) { return(BadRequest(new OpenIdConnectResponse { Error = OpenIdConnectConstants.Errors.InvalidRequest, ErrorDescription = "The mandatory 'assertion' parameter was missing." })); } // Create a new ClaimsIdentity containing the claims that // will be used to create an id_token and/or an access token. var identity = new ClaimsIdentity(OpenIdConnectServerDefaults.AuthenticationScheme); Console.WriteLine(identity.ToString()); Console.WriteLine(request.Code); var googleDetails = await GetGoogleDetailsAsync(request.Assertion); if (googleDetails != null) { // save //check to see if the ProviderId is already listed for this user var repeatUser = _ctx.Users .Where(x => x.ProviderId.Equals(googleDetails.ProviderUserId)) .FirstOrDefault(); //this signed in google user is not a repeat user and hasn't been saved yet if (repeatUser == null) { var result = await _userManager.CreateAsync( new ApplicationUser() { Email = googleDetails.Email, FirstName = googleDetails.FirstName, UserName = $"{googleDetails.Email.Split('@')[0]}_Google", FullName = googleDetails.Name, LastName = googleDetails.LastName, ProviderId = googleDetails.ProviderUserId, ProviderName = "GOOGLE", PictureUrl = "https://cdn.iconscout.com/public/images/icon/premium/png-512/gamer-games-video-casino-372bcf114ef0140a-512x512.png" }); if (!result.Succeeded) { AddErrors(result); return(BadRequest(result)); } else { _logger.LogInformation("Social User created a new account without password."); //var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); //var callbackUrl = Url.EmailConfirmationLink(user.Id, code, Request.Scheme); //await _emailSender.SendEmailConfirmationAsync(model.Email, callbackUrl); //await _signInManager.SignInAsync(user, isPersistent: false); //_logger.LogInformation("User created a new account with password."); //return Ok(result); //return RedirectToLocal(returnUrl); } } } // Manually validate the identity token issued by Google, // including the issuer, the signature and the audience. // Then, copy the claims you need to the "identity" instance. identity.AddClaim(OpenIdConnectConstants.Claims.Subject, googleDetails.ProviderUserId, OpenIdConnectConstants.Destinations.AccessToken); identity.AddClaim(OpenIdConnectConstants.Claims.Name, googleDetails.Name, OpenIdConnectConstants.Destinations.AccessToken); identity.AddClaim(OpenIdConnectConstants.Claims.Email, googleDetails.Email, OpenIdConnectConstants.Destinations.AccessToken); identity.AddClaim(OpenIdConnectConstants.Claims.GivenName, googleDetails.FirstName, OpenIdConnectConstants.Destinations.AccessToken); identity.AddClaim(OpenIdConnectConstants.Claims.FamilyName, googleDetails.LastName, OpenIdConnectConstants.Destinations.AccessToken); identity.AddClaim(OpenIdConnectConstants.Claims.Locale, googleDetails.Locale, OpenIdConnectConstants.Destinations.AccessToken); // Create a new authentication ticket holding the user identity. var ticket = new AuthenticationTicket( new ClaimsPrincipal(identity), new AuthenticationProperties(), OpenIdConnectServerDefaults.AuthenticationScheme); // Then, copy the claims you need to the "identity" instance. ticket.SetScopes( OpenIdConnectConstants.Scopes.OpenId, OpenIdConnectConstants.Scopes.OfflineAccess, OpenIdConnectConstants.Scopes.Profile, OpenIdConnectConstants.Scopes.Email); return(SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme)); } if (request.GrantType == "urn:ietf:params:oauth:grant-type:facebook_access_token") { // Reject the request if the "assertion" parameter is missing. if (string.IsNullOrEmpty(request.Assertion)) { return(BadRequest(new OpenIdConnectResponse { Error = OpenIdConnectConstants.Errors.InvalidRequest, ErrorDescription = "The mandatory 'assertion' parameter was missing." })); } // Create a new ClaimsIdentity containing the claims that // will be used to create an id_token and/or an access token. var identity = new ClaimsIdentity(OpenIdConnectServerDefaults.AuthenticationScheme); Console.WriteLine(identity.ToString()); Console.WriteLine(request.Code); var fbDetails = await GetFacebookDetailsAsync(request.Assertion); if (fbDetails != null) { // save //check to see if the ProviderId is already listed for this user var repeatUser = _ctx.Users .Where(x => x.ProviderId.Equals(fbDetails.ProviderUserId)) .FirstOrDefault(); // save if (repeatUser == null) { var result = await _userManager.CreateAsync( new ApplicationUser() { Email = fbDetails.Email, UserName = $"{fbDetails.Email.Split('@')[0]}_Facebook", FirstName = fbDetails.FirstName, FullName = fbDetails.Name, LastName = fbDetails.LastName, ProviderId = fbDetails.ProviderUserId, ProviderName = "FACEBOOK", PictureUrl = "https://cdn.iconscout.com/public/images/icon/premium/png-512/gamer-games-video-casino-372bcf114ef0140a-512x512.png" }); if (!result.Succeeded) { AddErrors(result); return(BadRequest(result)); } else { _logger.LogInformation("Social User created a new account without password."); //var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); //var callbackUrl = Url.EmailConfirmationLink(user.Id, code, Request.Scheme); //await _emailSender.SendEmailConfirmationAsync(model.Email, callbackUrl); //await _signInManager.SignInAsync(user, isPersistent: false); //_logger.LogInformation("User created a new account with password."); //return Ok(result); //return RedirectToLocal(returnUrl); } } } // Manually validate the identity token issued by Google, // including the issuer, the signature and the audience. // Then, copy the claims you need to the "identity" instance. identity.AddClaim(OpenIdConnectConstants.Claims.Subject, fbDetails.ProviderUserId, OpenIdConnectConstants.Destinations.AccessToken); identity.AddClaim(OpenIdConnectConstants.Claims.Name, fbDetails.Name, OpenIdConnectConstants.Destinations.AccessToken); identity.AddClaim(OpenIdConnectConstants.Claims.Email, fbDetails.Email, OpenIdConnectConstants.Destinations.AccessToken); identity.AddClaim(OpenIdConnectConstants.Claims.GivenName, fbDetails.FirstName, OpenIdConnectConstants.Destinations.AccessToken); identity.AddClaim(OpenIdConnectConstants.Claims.FamilyName, fbDetails.LastName, OpenIdConnectConstants.Destinations.AccessToken); identity.AddClaim(OpenIdConnectConstants.Claims.Locale, fbDetails.Locale, OpenIdConnectConstants.Destinations.AccessToken); // Create a new authentication ticket holding the user identity. var ticket = new AuthenticationTicket( new ClaimsPrincipal(identity), new AuthenticationProperties(), OpenIdConnectServerDefaults.AuthenticationScheme); // Then, copy the claims you need to the "identity" instance. ticket.SetScopes( OpenIdConnectConstants.Scopes.OpenId, OpenIdConnectConstants.Scopes.OfflineAccess, OpenIdConnectConstants.Scopes.Profile, OpenIdConnectConstants.Scopes.Email); return(SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme)); } return(BadRequest(new OpenIdConnectResponse { Error = OpenIdConnectConstants.Errors.UnsupportedGrantType, ErrorDescription = "The specified grant type is not supported." })); }
public async Task <IActionResult> Exchange(OpenIdConnectRequest request) { if (request.IsPasswordGrantType()) { var user = await _userManager.FindByEmailAsync(request.Username) ?? await _userManager.FindByNameAsync(request.Username); if (user == null) { return(BadRequest(new OpenIdConnectResponse { Error = OpenIdConnectConstants.Errors.InvalidGrant, ErrorDescription = "Please check that your email and password is correct" })); } // Ensure the user is allowed to sign in. if (!await _signInManager.CanSignInAsync(user)) { return(BadRequest(new OpenIdConnectResponse { Error = OpenIdConnectConstants.Errors.InvalidGrant, ErrorDescription = "The specified user is not allowed to sign in" })); } // Reject the token request if two-factor authentication has been enabled by the user. if (_userManager.SupportsUserTwoFactor && await _userManager.GetTwoFactorEnabledAsync(user)) { return(BadRequest(new OpenIdConnectResponse { Error = OpenIdConnectConstants.Errors.InvalidGrant, ErrorDescription = "The specified user is not allowed to sign in" })); } // Ensure the user is not already locked out. if (_userManager.SupportsUserLockout && await _userManager.IsLockedOutAsync(user)) { return(BadRequest(new OpenIdConnectResponse { Error = OpenIdConnectConstants.Errors.InvalidGrant, ErrorDescription = "The specified user account has been suspended" })); } // Ensure the user is enabled. if (!user.IsEnabled) { return(BadRequest(new OpenIdConnectResponse { Error = OpenIdConnectConstants.Errors.InvalidGrant, ErrorDescription = "The specified user account is disabled" })); } // Ensure the password is valid. if (!await _userManager.CheckPasswordAsync(user, request.Password)) { if (_userManager.SupportsUserLockout) { await _userManager.AccessFailedAsync(user); } return(BadRequest(new OpenIdConnectResponse { Error = OpenIdConnectConstants.Errors.InvalidGrant, ErrorDescription = "Please check that your email and password is correct" })); } if (_userManager.SupportsUserLockout) { await _userManager.ResetAccessFailedCountAsync(user); } // Create a new authentication ticket. var ticket = await CreateTicketAsync(request, user); return(SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme)); } else if (request.IsRefreshTokenGrantType()) { // Retrieve the claims principal stored in the refresh token. var info = await HttpContext.Authentication.GetAuthenticateInfoAsync( OpenIdConnectServerDefaults.AuthenticationScheme); // Retrieve the user profile corresponding to the refresh token. // Note: if you want to automatically invalidate the refresh token // when the user password/roles change, use the following line instead: // var user = _signInManager.ValidateSecurityStampAsync(info.Principal); var user = await _userManager.GetUserAsync(info.Principal); if (user == null) { return(BadRequest(new OpenIdConnectResponse { Error = OpenIdConnectConstants.Errors.InvalidGrant, ErrorDescription = "The refresh token is no longer valid" })); } // Ensure the user is still allowed to sign in. if (!await _signInManager.CanSignInAsync(user)) { return(BadRequest(new OpenIdConnectResponse { Error = OpenIdConnectConstants.Errors.InvalidGrant, ErrorDescription = "The user is no longer allowed to sign in" })); } // Create a new authentication ticket, but reuse the properties stored // in the refresh token, including the scopes originally granted. var ticket = await CreateTicketAsync(request, user, info.Properties); return(SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme)); } return(BadRequest(new OpenIdConnectResponse { Error = OpenIdConnectConstants.Errors.UnsupportedGrantType, ErrorDescription = "The specified grant type is not supported" })); }
private async Task <bool> IsTfaEnabled(IdentityUser user) => UserManager.SupportsUserTwoFactor && await UserManager.GetTwoFactorEnabledAsync(user) && (await UserManager.GetValidTwoFactorProvidersAsync(user)).Count > 0;
/// <summary> /// /// Custom implementation sign-in with password. /// /// Alternatively, use <see cref="SignInManager{TUser}.PasswordSignInAsync(string, string, bool, bool)"/> /// /// </summary> /// <param name="userName"></param> /// <param name="password"></param> /// <returns></returns> private async Task <Microsoft.AspNetCore.Identity.SignInResult> CustomPasswordSignInAsync(string userName, string password) { var user = await _userManager.FindByNameAsync(userName); if (user != null && !await _userManager.IsLockedOutAsync(user)) { if (await _userManager.CheckPasswordAsync(user, password)) { if (!await _userManager.IsEmailConfirmedAsync(user)) { ModelState.AddModelError("", "Email is not confirmed!"); return(Microsoft.AspNetCore.Identity.SignInResult.Failed); } await _userManager.ResetAccessFailedCountAsync(user); if (await _userManager.GetTwoFactorEnabledAsync(user)) { // perform Two-step Verification var validTFProviders = await _userManager.GetValidTwoFactorProvidersAsync(user); if (validTFProviders.Contains(_userManager.Options.Tokens.AuthenticatorTokenProvider)) { // Multi-Factor with local device which is a token generator (mobile app such as Google Authenticator, or Authy,...) await HttpContext.SignInAsync(scheme : IdentityConstants.TwoFactorUserIdScheme, principal : Store2FA(user.Id, _userManager.Options.Tokens.AuthenticatorTokenProvider)); return(Microsoft.AspNetCore.Identity.SignInResult.TwoFactorRequired); } if (validTFProviders.Contains(TokenOptions.DefaultEmailProvider)) { // Multi-Factor with generated token and send to user's email var token = await _userManager.GenerateTwoFactorTokenAsync(user, TokenOptions.DefaultEmailProvider); // TODO: send the email contains this generated token System.IO.File.WriteAllText("GeneratedUrl/email2sv.txt", token); await HttpContext.SignInAsync(scheme : IdentityConstants.TwoFactorUserIdScheme, principal : Store2FA(user.Id, TokenOptions.DefaultEmailProvider)); return(Microsoft.AspNetCore.Identity.SignInResult.TwoFactorRequired); } } ClaimsPrincipal principal = await _claimsPrincipalFactory.CreateAsync(user); await HttpContext.SignInAsync(scheme : IdentityConstants.ApplicationScheme, principal : principal); return(Microsoft.AspNetCore.Identity.SignInResult.Success); } await _userManager.AccessFailedAsync(user); if (await _userManager.IsLockedOutAsync(user)) { // at this time, user's account is locked out // email user, notifying them of lockout } } return(Microsoft.AspNetCore.Identity.SignInResult.Failed); }
private async Task <bool> TwoFactorRequiredAsync(User user) { return(_userManager.SupportsUserTwoFactor && await _userManager.GetTwoFactorEnabledAsync(user) && (await _userManager.GetValidTwoFactorProvidersAsync(user)).Count > 0); }
public async Task <IActionResult> Index(ManageMessageId?message = null) { // Optionaly use the region info to get default currency for user ViewData["StatusMessage"] = message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed." : message == ManageMessageId.SetPasswordSuccess ? "Your password has been set." : message == ManageMessageId.SetTwoFactorSuccess ? "Your two-factor authentication provider has been set." : message == ManageMessageId.Error ? "An error has occurred." : message == ManageMessageId.AddPhoneSuccess ? "Your phone number was added." : message == ManageMessageId.RemovePhoneSuccess ? "Your phone number was removed." : ""; var user = await GetCurrentUserAsync(); if (user == null) { return(View("Error")); } // Give the user a default currency if they dont have if (string.IsNullOrEmpty(user.Currency)) { var requestCulture = Request.HttpContext.Features.Get <IRequestCultureFeature>(); var culture = requestCulture.RequestCulture.Culture; user.Currency = _currencyService.GetCurrent().Name; } var currencies = _currencyService.GetAll(); var model = new IndexViewModel { HasPassword = await _userManager.HasPasswordAsync(user), PhoneNumber = await _userManager.GetPhoneNumberAsync(user), TwoFactor = await _userManager.GetTwoFactorEnabledAsync(user), Logins = await _userManager.GetLoginsAsync(user), BrowserRemembered = await _signInManager.IsTwoFactorClientRememberedAsync(user), FullName = user.FullName, Culture = user.Culture, Currency = user.Currency, CurrencyList = new List <SelectListItem>(currencies.Select(c => new SelectListItem { Text = c.Symbol, Value = c.CultureName })), CultureList = new List <SelectListItem> { new SelectListItem { Value = "en-US", Text = "English" }, new SelectListItem { Value = "zh-CN", Text = "Chinese" } } }; return(View(model)); }
public async Task <IActionResult> Exchange(OpenIdConnectRequest request) { Debug.Assert(request.IsTokenRequest(), "The OpenIddict binder for ASP.NET Core MVC is not registered. " + "Make sure services.AddOpenIddict().AddMvcBinders() is correctly called."); if (request.IsPasswordGrantType()) { var user = await _userManager.FindByNameAsync(request.Username); if (user == null) { return(BadRequest(new OpenIdConnectResponse { Error = OpenIdConnectConstants.Errors.InvalidGrant, ErrorDescription = "The username/password couple is invalid." })); } // Ensure the user is allowed to sign in. if (!await _signInManager.CanSignInAsync(user)) { return(BadRequest(new OpenIdConnectResponse { Error = OpenIdConnectConstants.Errors.InvalidGrant, ErrorDescription = "The specified user is not allowed to sign in." })); } // Reject the token request if two-factor authentication has been enabled by the user. if (_userManager.SupportsUserTwoFactor && await _userManager.GetTwoFactorEnabledAsync(user)) { return(BadRequest(new OpenIdConnectResponse { Error = OpenIdConnectConstants.Errors.InvalidGrant, ErrorDescription = "The specified user is not allowed to sign in." })); } // Ensure the user is not already locked out. if (_userManager.SupportsUserLockout && await _userManager.IsLockedOutAsync(user)) { return(BadRequest(new OpenIdConnectResponse { Error = OpenIdConnectConstants.Errors.InvalidGrant, ErrorDescription = "The username/password couple is invalid." })); } // Ensure the password is valid. if (!await _userManager.CheckPasswordAsync(user, request.Password)) { if (_userManager.SupportsUserLockout) { await _userManager.AccessFailedAsync(user); } return(BadRequest(new OpenIdConnectResponse { Error = OpenIdConnectConstants.Errors.InvalidGrant, ErrorDescription = "The username/password couple is invalid." })); } if (_userManager.SupportsUserLockout) { await _userManager.ResetAccessFailedCountAsync(user); } // Create a new authentication ticket. var ticket = await CreateTicketAsync(request, user); return(SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme)); } else if (request.IsRefreshTokenGrantType()) { // Retrieve the claims principal stored in the refresh token. var info = await HttpContext.Authentication.GetAuthenticateInfoAsync( OpenIdConnectServerDefaults.AuthenticationScheme); // Retrieve the user profile corresponding to the refresh token. var user = await _userManager.GetUserAsync(info.Principal); if (user == null) { return(BadRequest(new OpenIdConnectResponse { Error = OpenIdConnectConstants.Errors.InvalidGrant, ErrorDescription = "The refresh token is no longer valid." })); } // Ensure the user is still allowed to sign in. if (!await _signInManager.CanSignInAsync(user)) { return(BadRequest(new OpenIdConnectResponse { Error = OpenIdConnectConstants.Errors.InvalidGrant, ErrorDescription = "The user is no longer allowed to sign in." })); } // Create a new authentication ticket, but reuse the properties stored // in the refresh token, including the scopes originally granted. var ticket = await CreateTicketAsync(request, user, info.Properties); return(SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme)); } return(BadRequest(new OpenIdConnectResponse { Error = OpenIdConnectConstants.Errors.UnsupportedGrantType, ErrorDescription = "The specified grant type is not supported." })); }
public async Task <IActionResult> Login([FromBody] LoginRequest request) { var context = await _interaction.GetAuthorizationContextAsync(request.ReturnUrl); var user = await _userManager.FindByNameAsync(request.Username) ?? await _userManager.FindByEmailAsync(request.Username); if (user != null && context != null) { /* * if (String.IsNullOrEmpty(request.TwoFAToken)) * { * var result = await _signInManager.PasswordSignInAsync(user, request.Password, true, false); * * if (result.RequiresTwoFactor) * { * * } * } * else * { * var user = await _signInManager.GetTwoFactorAuthenticationUserAsync(); * * if (user == null) * { * * } * var result = await * } */ var passwordRight = await _userManager.CheckPasswordAsync(user, request.Password); if (passwordRight) { if (await _userManager.GetTwoFactorEnabledAsync(user)) { if (!String.IsNullOrEmpty(request.TwoFAToken)) { var authorized = await _userManager.VerifyTwoFactorTokenAsync(user, "Login", request.TwoFAToken); if (authorized) { await _signInManager.SignInAsync(user, true); return(new JsonResult(new { RedirectUrl = request.ReturnUrl, IsOk = true })); } } else { var result = new JsonResult(new { IsOK = false, Error = "2fa_enabled", ErrorDescription = "Two Factor Authentication is enabled for this account." }); result.StatusCode = 401; return(result); } } else { await _signInManager.SignInAsync(user, true); return(new JsonResult(new { RedirectUrl = request.ReturnUrl, IsOk = true })); } } } return(Unauthorized()); }