void SignInUser(AuthenticationUser user, string impersonatorId = null) { var identity = IdentityManagers.UserManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie); if (impersonatorId != null) identity.AddImpersonatorId(impersonatorId); IdentityManagers.AuthenticationManager.SignIn(new AuthenticationProperties { IsPersistent = false }, identity); System.Threading.Thread.CurrentPrincipal = new ClaimsPrincipal(identity); }
public async Task<string> CreateAsync(string userId) { var user = new AuthenticationUser { Id = userId, UserName = userId }; string password = new RandomString(8); var result = await IdentityManagers.UserManager.CreateAsync(user, password); if (!result.Succeeded) throw new InvalidOperationException(string.Join(", ", result.Errors)); return password; }
public async Task CreateAsync(string userId, string password = null) { var appUser = new AuthenticationUser { Id = userId, UserName = userId }; var result = password != null ? await IdentityManagers.UserManager.CreateAsync(appUser, password) : await IdentityManagers.UserManager.CreateAsync(appUser); if (!result.Succeeded) throw new InvalidOperationException(string.Join(", ", result.Errors)); }
async Task SignInUserAsync(AuthenticationUser user, string impersonatorId = null) { var identity = await IdentityManagers.UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie); if (impersonatorId != null) identity.AddImpersonatorId(impersonatorId); IdentityManagers.AuthenticationManager.SignIn(new AuthenticationProperties { IsPersistent = false }, identity); // Cannot assign CurrentPrincipal to thread in async because it can't be propagated up. // If you need to access current logged in user immediately after signing in, use synchronous version. //System.Threading.Thread.CurrentPrincipal = new ClaimsPrincipal(identity); }
public async Task <User> AuthenticateAsync(AuthenticationUser authUser) { if (String.IsNullOrWhiteSpace(authUser.Login) || String.IsNullOrWhiteSpace(authUser.Password)) { throw new ArgumentException("Login or Password is Empty"); } var users = await _storage.GetAllAsync(); // user`s pswd var dbUser = users.FirstOrDefault(user => user.Login == authUser.Login && PasswordEncrypter.Decrypt(user.Password) == authUser.Password); if (dbUser == null) { throw new Exception("Wrong Login or Password"); } LoginedUser.User = dbUser; return(new User(dbUser.Guid, dbUser.FirstName, dbUser.LastName, dbUser.Email, dbUser.Login)); }
private async Task LoadSharedKeyAndQrCodeUriAsync(AuthenticationUser user) { // Load the authenticator key & QR code URI to display on the form var unformattedKey = await _userManager.GetAuthenticatorKeyAsync(user); if (string.IsNullOrEmpty(unformattedKey)) { await _userManager.ResetAuthenticatorKeyAsync(user); unformattedKey = await _userManager.GetAuthenticatorKeyAsync(user); } SharedKey = FormatKey(unformattedKey); var email = await _userManager.GetEmailAsync(user); AuthenticatorUri = GenerateQrCodeUri(email, unformattedKey); }
/// <summary> /// 授权验证 /// </summary> /// <param name="operation">授权操作</param> /// <returns></returns> public static bool CheckAuthorization(AuthenticationUser <long> user, OperationDto operation) { if (operation == null || user == null) { return(false); } if (user.IsAdmin) { return(true); } var checkAuthDto = new CheckAuthorizationDto() { UserId = user.Id, Operation = operation }; return(operationAppService.CheckAuthorization(checkAuthDto)); }
public async Task <IActionResult> PostSignup([FromBody] Signup user) { var userExist = await UserManager.FindByNameAsync(user.UserName); if (userExist != null) { return(Ok(new Response { Status = "Error", Message = "User Already Exists" })); } AuthenticationUser authenticationUser = new AuthenticationUser() { Email = user.Email, SecurityStamp = Guid.NewGuid().ToString(),//identifier UserName = user.UserName }; var result = await this.UserManager.CreateAsync(authenticationUser, user.Password); if (!result.Succeeded) { return(StatusCode(StatusCodes.Status500InternalServerError, new Response { Status = "Error", Message = "Cant create user" })); } if (!await this.RoleManager.RoleExistsAsync("Admin")) { await this.RoleManager.CreateAsync(new IdentityRole("Admin")); } if (!await this.RoleManager.RoleExistsAsync("User")) { await this.RoleManager.CreateAsync(new IdentityRole("User")); } await this.UserManager.AddToRoleAsync(authenticationUser, user.Role); return(Ok(new Response { Status = "Success", Message = "Account Created Successfully" })); }
public async Task GetUserByLoginAsync_QueryReturnsEmpty_ReturnsNull() { // Arrange var cxn = new SqlConnectionWrapperMock(); var repository = new SqlUserRepository(cxn.Object, cxn.Object); string login = "******"; AuthenticationUser[] result = { }; cxn.SetupQueryAsync("GetUserByLogin", new Dictionary <string, object> { { "Login", login } }, result); // Act AuthenticationUser user = await repository.GetUserByLoginAsync(login); // Assert cxn.Verify(); Assert.IsNull(user); }
/// <summary> /// 保存登陆信息 /// </summary> /// <param name="userId">用户编号</param> static void SaveLoginCredential(UserDto user) { if (null == user) { return; } AuthenticationUser <long> authUser = new AuthenticationUser <long>() { Id = user.SysNo, Name = user.UserName, RealName = user.RealName }; HttpContextHelper.Current.SignInAsync(authUser, new AuthenticationProperties() { IsPersistent = true, ExpiresUtc = DateTime.UtcNow.AddMinutes(30) }).GetAwaiter().GetResult(); }
private bool LoadUserData() { // TODO: Loading Screen UpdateMacAddress(); ProcessData.LoadData(); AuthenticationUser.GetInstance().UpdateToken(); if (AuthenticationUser.GetInstance().IsDataValid()) { // Creating AuthView to initialize AuthModel _goToApp action AuthView authView = new AuthView(GoToApp, false); AuthModel.SignIn(); return(true); } return(false); }
/// <summary> /// 授权验证 /// </summary> /// <param name="request">认证授权信息</param> /// <returns></returns> public static VerifyAuthorizationResult Authentication(VerifyAuthorizationOption request) { if (request == null) { return(VerifyAuthorizationResult.ForbidResult()); } var operation = new AuthorityOperationCmdDto() { ActionCode = request.ActionCode, ControllerCode = request.ControllerCode }; var user = AuthenticationUser <long> .GetUserFromClaims(request.Claims?.Select(c => new Claim(c.Key, c.Value)).ToList()); var allowAccess = Authorization(user, operation); return(new VerifyAuthorizationResult() { Status = allowAccess ? AuthorizationVerificationStatus.Success : AuthorizationVerificationStatus.Forbid }); }
public static void ParseToken(string json) { JObject obj = JObject.Parse(json); string token = (string)obj.SelectToken("data.authToken"); // Save token to current user AuthenticationUser.GetInstance().Token = token; Client.SetToken(); token = AesOperation.EncryptString(Variables.MacAdress, token); FileStream stream = new FileStream(Variables.EnviromentPath + Variables.JwtFileName, FileMode.Create); stream.Close(); StreamWriter sw = new StreamWriter(Variables.EnviromentPath + Variables.JwtFileName, true, Encoding.UTF8); sw.Write(token); sw.Close(); }
public async Task <IActionResult> DeletePost(string id) { if (id == null || id.Trim().Length == 0) { return(NotFound()); } try { AuthenticationUser UserDb = _db.AuthenticationUsers.Where(u => u.Id == id).FirstOrDefault(); UserDb.LockoutEnd = DateTime.Now.AddYears(1000); await _db.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } catch (DbUpdateException /* ex */) { //Log the error (uncomment ex variable name and write a log.) return(RedirectToAction(nameof(Delete), new { id = id, saveChangesError = true })); } }
/// <summary> /// 授权验证 /// </summary> /// <param name="request">认证授权信息</param> /// <returns></returns> public static AuthorizeResult CheckAuthorization(AuthorizeOptions request) { if (request == null) { return(AuthorizeResult.ForbidResult()); } var operation = new OperationDto() { ActionCode = request.Action, ControllerCode = request.Controller }; var user = AuthenticationUser <long> .GetUserFromClaims(request.Claims?.Select(c => new Claim(c.Key, c.Value)).ToList()); var allowAccess = CheckAuthorization(user, operation); return(new AuthorizeResult() { Status = allowAccess ? AuthorizationStatus.Success : AuthorizationStatus.Forbid }); }
/// <summary> /// 授权验证 /// </summary> /// <param name="request">认证授权信息</param> /// <returns></returns> public static async Task <AuthorizeVerifyResult> AuthenticationAsync(AuthorizeVerifyRequest request) { if (request == null) { return(AuthorizeVerifyResult.ForbidResult()); } var operation = new AuthorityOperationCmdDto() { ActionCode = request.ActionCode, ControllerCode = request.ControllerCode }; var user = AuthenticationUser <long> .GetUserFromClaims(request.Claims?.Select(c => new Claim(c.Key, c.Value)).ToList()); var allowAccess = await AuthorizationAsync(user, operation).ConfigureAwait(false); return(new AuthorizeVerifyResult() { VerifyValue = allowAccess ? AuthorizeVerifyValue.Success : AuthorizeVerifyValue.Forbid }); }
public async Task <User> Authenticate(AuthenticationUser authUser) { if (String.IsNullOrWhiteSpace(authUser.Login) || String.IsNullOrWhiteSpace(authUser.Password)) { throw new ArgumentException("Login or password is empty"); } UserHandler userHandler = new UserHandler(); userHandler.Filename = @"../../../DataBase/Customer/customers.json"; var users = await userHandler.Find(authUser.Login); var dbUser = users.FirstOrDefault(user => user.Login == authUser.Login && user.Password == authUser.Password); if (dbUser == null) { throw new Exception("Incorrect password!"); } return(new User(dbUser.Guid, dbUser.FirstName, dbUser.LastName, dbUser.Email, dbUser.Login)); }
public async Task <IActionResult> OnPostConfirmationAsync(string returnUrl = null) { returnUrl = returnUrl ?? Url.Content("~/"); // Get the information about the user from the external login provider var info = await _signInManager.GetExternalLoginInfoAsync(); if (info == null) { ErrorMessage = "Error loading external login information during confirmation."; return(RedirectToPage("./Login", new { ReturnUrl = returnUrl })); } if (ModelState.IsValid) { var user = new AuthenticationUser { UserName = Input.Email, Email = Input.Email }; var result = await _userManager.CreateAsync(user); if (result.Succeeded) { result = await _userManager.AddLoginAsync(user, info); if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent : false); _logger.LogInformation("User created an account using {Name} provider.", info.LoginProvider); return(LocalRedirect(returnUrl)); } } foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } LoginProvider = info.LoginProvider; ReturnUrl = returnUrl; return(Page()); }
private AuthenticationStatus AuthenticateDatabaseUser(AuthenticationUser user, string password, int passwordExpirationInDays = 0) { var hashedPassword = HashingUtilities.GenerateSaltedHash(password, user.UserSalt); if (!string.Equals(user.Password, hashedPassword)) { return(AuthenticationStatus.InvalidCredentials); } if (!user.IsEnabled) { return(AuthenticationStatus.Locked); } if (HasExpiredPassword(user, passwordExpirationInDays)) { return(AuthenticationStatus.PasswordExpired); } return(AuthenticationStatus.Success); }
/// <summary> /// 授权验证 /// </summary> /// <param name="operation">授权操作</param> /// <returns></returns> public static async Task <bool> AuthorizationAsync(AuthenticationUser <long> user, AuthorityOperationCmdDto operation) { if (operation == null || user == null) { return(false); } AuthenticationCmdDto authInfo = new AuthenticationCmdDto() { Operation = operation, User = new AdminUserCmdDto() { UserType = UserType.管理账户, SysNo = user.Id } }; return(await Task.Run(() => { return operation.Instance <IAuthService>().Authentication(authInfo); }).ConfigureAwait(false)); }
public ActionResult RemoveAccessUser(string UserAccessId) { if (Session["UserId"] != null) { userId = Session["UserId"].ToString(); } AuthenticationUser autuser = db.AuthenticationUsers.Where(a => a.UserAccess == UserAccessId && a.UserAdmin == userId).FirstOrDefault(); if (autuser != null) { db.AuthenticationUsers.Remove(autuser); db.SaveChanges(); } else if (autuser == null) { ViewBag.Message = "User Not Found"; } return(View()); }
public async Task <User> Authenticate(AuthenticationUser authUser) { Thread.Sleep(2000); if (string.IsNullOrWhiteSpace(authUser.Login) || string.IsNullOrWhiteSpace(authUser.Password)) { throw new ArgumentException("Blank login/password"); } System.Collections.Generic.List <DBUser> dbUsers = await _storage.GetAllAsync(); DBUser dbUser = dbUsers.FirstOrDefault(user => user.Login == authUser.Login && user.Password == Encrypt(authUser.Password)); if (dbUser == null) { throw new Exception("Invalid login/password"); } User curUser = new(dbUser); CurrentSession.User = curUser; return(curUser); }
/// <summary> /// 获取验证码 /// </summary> /// <returns></returns> public ActionResult GetCode(string mobile) { if (!MyRegex.IsPhone(mobile)) { return(JsonResult(APIErrCode.PhoneFormatError, "手机格式错误")); } AuthenticationUser authenticationUser = BLLAuthentication.GetAuthenticationUser(); string code = HT.Utility.Utils.Number(6); return(JsonResult(APIErrCode.Success, "获取验证码成功", code)); string sms_expire = BLLConfig.Get("sms_expire"); int expire = Convert.ToInt32(sms_expire); string msg = ""; if (BLLSendSms.SendMsg(mobile, code, "mobile", expire, out msg)) { new XCache().Add("Code" + authenticationUser.openid, code, expire);//写入缓存 return(JsonResult(APIErrCode.Success, "获取验证码成功", code)); } return(JsonResult(APIErrCode.OperateFail, msg)); }
/// <summary> /// 保存登陆信息 /// </summary> /// <param name="user">用户信息</param> static void SaveLoginCredential(UserDto user) { if (null == user) { return; } #region 记录登录用户,不记录超级管理员 if (!user.SuperUser) { CacheManager.Set.Add(new SetAddOption() { Key = CacheUtil.AllLoginUserCacheKey, Value = user.SysNo.ToString() }); var userCacheKey = CacheUtil.GetUserCacheKey(user.SysNo.ToString()); CacheManager.SetDataByRelativeExpiration(userCacheKey, user, TimeSpan.FromHours(1), true); CacheDataManager.RefreshLoginUser(user.SysNo, user.SuperUser); } #endregion #region 记录登录凭据 AuthenticationUser <long> authUser = new AuthenticationUser <long>() { Id = user.SysNo, Name = user.UserName, RealName = user.RealName, IsAdmin = user.SuperUser }; HttpContextHelper.Current.SignInAsync(authUser, new AuthenticationProperties() { IsPersistent = true, ExpiresUtc = DateTimeOffset.UtcNow.AddHours(1) }).GetAwaiter().GetResult(); #endregion }
public JsonResult Login(string email, string senha) { try { bool logado = new AuthenticationUser().Logon(email, senha, true); if (logado) { RedirectToAction("Index", "Home"); } else { throw new Exception("E-mail ou senha inválidos"); } } catch (Exception ex) { return(Json(new { erros = ex.Message })); } return(Json(new { })); }
public async Task <IActionResult> OnPostAsync(string returnUrl = null) { returnUrl = returnUrl ?? Url.Content("~/"); if (ModelState.IsValid) { var user = new AuthenticationUser { UserName = Input.UserName, Email = Input.Email }; var result = await _userManager.CreateAsync(user, Input.Password); if (result.Succeeded) { _logger.LogInformation("User created a new account with password."); var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); var callbackUrl = Url.Page( "/Account/ConfirmEmail", pageHandler: null, values: new { userId = user.Id, code = code }, protocol: Request.Scheme); await _emailSender.SendEmailAsync(Input.Email, "Confirm your email", $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>."); await _signInManager.SignInAsync(user, isPersistent : false); return(LocalRedirect(returnUrl)); } foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } // If we got this far, something failed, redisplay form return(Page()); }
private async Task GenerateToken(HttpContext context, string username, string password) { AuthenticationUser user = await _userManager.FindByEmailAsync(username); ClaimsIdentity identity = await GetIdentity(user, username, password); if (identity == null) { context.Response.StatusCode = 200; await context.Response.WriteAsync( SeriaizeErrorResponse("Invalid username or password.")); return; } identity.AddClaims(await GetUserClaims(username, user)); DateTime now = DateTime.UtcNow; JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler(); JwtSecurityToken jwt = handler.CreateJwtSecurityToken(subject: identity, signingCredentials: _options.SigningCredentials, issuer: _options.Issuer, audience: _options.Audience, notBefore: now, expires: now.Add(_options.Expiration)); string encodedJwt = handler.WriteToken(jwt); var response = new TokenResponce() { AccessToken = encodedJwt, ExpiresIn = (int)_options.Expiration.TotalSeconds }; context.Response.ContentType = "application/json"; await context.Response.WriteAsync(SeriaizeOkResponse(response)); }
private bool HasExpiredPassword(AuthenticationUser user, int passwordExpirationInDays) { // If the value is 0 then password never expires if (passwordExpirationInDays <= 0) { return(false); } if (!user.ExpirePassword.GetValueOrDefault()) { return(false); } if (!user.LastPasswordChangeTimestamp.HasValue) { return(false); } var currentUtcTime = DateTime.UtcNow; var hasExpiredPassword = user.LastPasswordChangeTimestamp.Value.AddDays(passwordExpirationInDays) <= currentUtcTime; return(hasExpiredPassword); }
public async Task <User> Authenticate(AuthenticationUser authUser) { Thread.Sleep(2000); if (string.IsNullOrWhiteSpace(authUser.Login) || string.IsNullOrWhiteSpace(authUser.Password)) { throw new ArgumentException("Login or Password is empty"); } var users = await Task.Run(() => _storage.GetAllAsync()); var dbUser = users.FirstOrDefault(user => user.Login == authUser.Login && user.Password == Encrypt(authUser.Password)); if (dbUser == null) { throw new Exception("wrong login or password"); } //Todo Call Method for user login or password validation and retrieve password from storage User curUser = new User(dbUser.Guid, dbUser.LastName, dbUser.FirstName, dbUser.Email, dbUser.Login); CurrentInformation.User = curUser; return(curUser); }
public async Task UpdateUserOnPasswordResetAsync_Success() { // Arrange var cxn = new SqlConnectionWrapperMock(); var repository = new SqlUserRepository(cxn.Object, cxn.Object); var user = new AuthenticationUser { Login = "******", Id = 99, Password = "******", UserSalt = new Guid() }; cxn.SetupExecuteAsync( "AddCurrentUserPasswordToHistory", new Dictionary <string, object> { { "@userId", user.Id } }, 1); cxn.SetupExecuteAsync( "UpdateUserOnPasswordResetAsync", new Dictionary <string, object> { { "@Login", user.Login }, { "@Password", user.Password }, { "@UserSALT", user.UserSalt } }, 1); // Act await repository.UpdateUserOnPasswordResetAsync(user); // Assert cxn.Verify(); }
public ActionResult AddReview(ht_review review) { Model.ht_review model = new Model.ht_review(); AuthenticationUser loginInfo = HT.BLL.BLLUser.GetLoginUserInfo(); if (loginInfo == null) { apiResp.msg = "请先登录"; apiResp.code = (int)HT.Model.Enum.APIErrCode.UserIsNotLogin; return(Json(apiResp)); } model.avatar = loginInfo.avatar; model.userid = loginInfo.id; model.nickname = loginInfo.nickname; model.status = 0; model.add_time = DateTime.Now; model.review_content = review.review_content; model.news_id = review.news_id; model.review_type = review.review_type; model.review_id = review.review_id; if (HT.BLL.BLLReview.AddReview(model) > 0) { apiResp.status = true; apiResp.result = model; apiResp.msg = "评论完成"; } else { apiResp.msg = "评论出错"; apiResp.code = (int)HT.Model.Enum.APIErrCode.OperateFail; } return(Json(apiResp)); }
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { var userManager = context.OwinContext.GetUserManager <ApplicationUserManager>(); AuthenticationUser user = await userManager.FindAsync(context.UserName, context.Password); if (user == null) { context.SetError("invalid_grant", "The user name or password is incorrect."); return; } ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, OAuthDefaults.AuthenticationType); ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager, CookieAuthenticationDefaults.AuthenticationType); AuthenticationProperties properties = CreateProperties(user.UserName); AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties); context.Validated(ticket); context.Request.Context.Authentication.SignIn(cookiesIdentity); }
public int Create(User user, string password) { if (string.IsNullOrWhiteSpace(password)) { return(1); } if (DbContext.Users.Any(x => x.Username == user.Username)) { return(-1); } byte[] passwordHash; byte[] passwordSalt; AuthenticationUser.CreatePasswordHash(password, out passwordHash, out passwordSalt); user.PasswordHash = passwordHash; user.PasswordSalt = passwordSalt; user.ImgAvatar = "0000userPng.png"; DbContext.Users.Add(user); DbContext.SaveChanges(); return(2); }
/// <summary> /// 保存登陆信息 /// </summary> /// <param name="user">用户信息</param> static void SaveLoginCredential(UserDto user) { if (null == user) { return; } #region 记录登录凭据 AuthenticationUser <long> authUser = new AuthenticationUser <long>() { Id = user.SysNo, Name = user.UserName, RealName = user.RealName, IsAdmin = user.SuperUser }; HttpContextHelper.Current.SignInAsync(authUser, new AuthenticationProperties() { IsPersistent = true, ExpiresUtc = DateTimeOffset.UtcNow.AddHours(1) }).GetAwaiter().GetResult(); #endregion }