public ActionResult Authenticate(string id) { AuthenticateModel model = new AuthenticateModel(); model.WebApplicationDisplayName = "Your Client Name"; model.SignOnAttemptId = id; model.CancelAllowed = true; model.CaptchaRequired = true; model.CaptchaTheme = CaptchaThemes.clean.ToString(); return View(model); }
private async Task <bool> IsTwoFactorAuthRequiredAsync(AbpLoginResult <Tenant, User> loginResult, AuthenticateModel authenticateModel) { if (!await SettingManager.GetSettingValueAsync <bool>(AbpZeroSettingNames.UserManagement.TwoFactorLogin.IsEnabled)) { return(false); } if (!loginResult.User.IsTwoFactorEnabled) { return(false); } if ((await _userManager.GetValidTwoFactorProvidersAsync(loginResult.User)).Count <= 0) { return(false); } if (await TwoFactorClientRememberedAsync(loginResult.User.ToUserIdentifier(), authenticateModel)) { return(false); } return(true); }
private async Task <bool> TwoFactorClientRememberedAsync(UserIdentifier userIdentifier, AuthenticateModel authenticateModel) { if (!await SettingManager.GetSettingValueAsync <bool>(AbpZeroSettingNames.UserManagement.TwoFactorLogin.IsRememberBrowserEnabled)) { return(false); } if (string.IsNullOrWhiteSpace(authenticateModel.TwoFactorRememberClientToken)) { return(false); } try { var validationParameters = new TokenValidationParameters { ValidAudience = _configuration.Audience, ValidIssuer = _configuration.Issuer, IssuerSigningKey = _configuration.SecurityKey }; foreach (var validator in _jwtOptions.Value.SecurityTokenValidators) { if (validator.CanReadToken(authenticateModel.TwoFactorRememberClientToken)) { try { SecurityToken validatedToken; var principal = validator.ValidateToken(authenticateModel.TwoFactorRememberClientToken, validationParameters, out validatedToken); var useridentifierClaim = principal.FindFirst(c => c.Type == UserIdentifierClaimType); if (useridentifierClaim == null) { return(false); } return(useridentifierClaim.Value == userIdentifier.ToString()); } catch (Exception ex) { Logger.Debug(ex.ToString(), ex); } } } } catch (Exception ex) { Logger.Debug(ex.ToString(), ex); } return(false); }
public async Task <AuthenticateResultModel> Authenticate([FromBody] AuthenticateModel model) { if (UseCaptchaOnLogin()) { await ValidateReCaptcha(model.CaptchaResponse); } var loginResult = await GetLoginResultAsync( model.UserNameOrEmailAddress, model.Password, GetTenancyNameOrNull() ); var returnUrl = model.ReturnUrl; if (model.SingleSignIn.HasValue && model.SingleSignIn.Value && loginResult.Result == AbpLoginResultType.Success) { loginResult.User.SetSignInToken(); returnUrl = AddSingleSignInParametersToReturnUrl(model.ReturnUrl, loginResult.User.SignInToken, loginResult.User.Id, loginResult.User.TenantId); } //Password reset if (loginResult.User.ShouldChangePasswordOnNextLogin) { loginResult.User.SetNewPasswordResetCode(); return(new AuthenticateResultModel { ShouldResetPassword = true, PasswordResetCode = loginResult.User.PasswordResetCode, UserId = loginResult.User.Id, ReturnUrl = returnUrl }); } //Two factor auth await _userManager.InitializeOptionsAsync(loginResult.Tenant?.Id); string twoFactorRememberClientToken = null; if (await IsTwoFactorAuthRequiredAsync(loginResult, model)) { if (model.TwoFactorVerificationCode.IsNullOrEmpty()) { //Add a cache item which will be checked in SendTwoFactorAuthCode to prevent sending unwanted two factor code to users. _cacheManager .GetTwoFactorCodeCache() .Set( loginResult.User.ToUserIdentifier().ToString(), new TwoFactorCodeCacheItem() ); return(new AuthenticateResultModel { RequiresTwoFactorVerification = true, UserId = loginResult.User.Id, TwoFactorAuthProviders = await _userManager.GetValidTwoFactorProvidersAsync(loginResult.User), ReturnUrl = returnUrl }); } twoFactorRememberClientToken = await TwoFactorAuthenticateAsync(loginResult.User, model); } // One Concurrent Login if (AllowOneConcurrentLoginPerUser()) { await _userManager.UpdateSecurityStampAsync(loginResult.User); await _securityStampHandler.SetSecurityStampCacheItem(loginResult.User.TenantId, loginResult.User.Id, loginResult.User.SecurityStamp); loginResult.Identity.ReplaceClaim(new Claim(AppConsts.SecurityStampKey, loginResult.User.SecurityStamp)); } var accessToken = CreateAccessToken(await CreateJwtClaims(loginResult.Identity, loginResult.User)); var refreshToken = CreateRefreshToken(await CreateJwtClaims(loginResult.Identity, loginResult.User, tokenType: TokenType.RefreshToken)); return(new AuthenticateResultModel { AccessToken = accessToken, ExpireInSeconds = (int)_configuration.AccessTokenExpiration.TotalSeconds, RefreshToken = refreshToken, RefreshTokenExpireInSeconds = (int)_configuration.RefreshTokenExpiration.TotalSeconds, EncryptedAccessToken = GetEncryptedAccessToken(accessToken), TwoFactorRememberClientToken = twoFactorRememberClientToken, UserId = loginResult.User.Id, ReturnUrl = returnUrl }); }
public IActionResult Authenticate([FromBody] AuthenticateModel model) { var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(_appSettings.Secret); if (model.StudentOrEmployee == "Employee") { var user = _authenticationService.Authenticate(model.Email, model.Password, _employeeContext); if (user == null) { return(BadRequest(new { message = "Username or password is incorrect" })); } var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, user.Employee_Id.ToString()), new Claim(ClaimTypes.Role, user.Role.ToString()), }), Expires = DateTime.UtcNow.AddMinutes(30), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); var tokenString = tokenHandler.WriteToken(token); // return basic user info and authentication token return(Ok(new { Id = user.Employee_Id, First_Name = user.First_Name, Last_Name = user.Last_Name, Token = tokenString })); } else if (model.StudentOrEmployee == "Student") { var user = _authenticationService.Authenticate(model.Email, model.Password, _studentContext); if (user == null) { return(BadRequest(new { message = "Username or password is incorrect" })); } var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, user.Student_Id.ToString()), new Claim(ClaimTypes.Role, user.Role) }), Expires = DateTime.UtcNow.AddMinutes(30), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); var tokenString = tokenHandler.WriteToken(token); // return basic user info and authentication token return(Ok(new { Id = user.Student_Id, First_Name = user.First_Name, Last_Name = user.Last_Name, Token = tokenString })); } else { return(BadRequest(new { message = "Are you student or employee?" })); } }