private async Task <ClaimsIdentity> GetIdentity(UserLoginPassInputModel currentUser) { //ищем пользователя по логину var user = await userStorage.UserGetByLogin(UserPassLoginMapper.FromInputModel(currentUser)); // сравниваем введенный пароль с хешем пароля в базе if (user != null && Hashing.ValidateUserPassword(currentUser.Password, user.Password)) { var roles = userStorage.UserRolesSelectByUserId((int)user.Id).Result.ToList(); if (user != null) { var claims = new List <Claim> { new Claim(ClaimsIdentity.DefaultNameClaimType, user.Login), }; //добавляем все роли пользователя foreach (Role role in roles) { claims.Add(new Claim(ClaimsIdentity.DefaultRoleClaimType, role.Name)); } //формируе токен ClaimsIdentity claimsIdentity = new ClaimsIdentity(claims, "Token"); return(claimsIdentity); } } // если пользователя не найдено return(null); }
public async Task <IActionResult> Token(UserLoginPassInputModel currentUser) { var identity = await GetIdentity(currentUser); if (identity == null) { return(BadRequest(new { errorText = "Invalid username or password." })); } var now = DateTime.Now; // создаем JWT-токен var jwt = new JwtSecurityToken( issuer: AuthOptions.ISSUER, audience: AuthOptions.AUDIENCE, notBefore: now, claims: identity.Claims, expires: now.Add(TimeSpan.FromMinutes(AuthOptions.LIFETIME)), signingCredentials: new SigningCredentials(AuthOptions.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256)); var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt); var response = new { access_token = encodedJwt, username = identity.Name }; return(Json(response)); }
public static User FromInputModel(UserLoginPassInputModel loginPassword) { return(new User { Id = loginPassword.Id, Password = loginPassword.Password, Login = loginPassword.Login, }); }
public async Task <ActionResult> ChangePassword([FromBody] UserLoginPassInputModel model) { if (model == null || model.Id < 1) { return(BadRequest()); } model.Password = Hashing.HashUserPassword(model.Password); await userStorage.ChangePassword(UserPassLoginMapper.FromInputModel(model)); return(Ok()); }
public async Task <ActionResult> AddUserAsStudent([FromBody] UserLoginPassInputModel model) { if (model == null || model.Id < 1) { return(BadRequest("Uncorrect input data")); } model.Password = Hashing.HashUserPassword(model.Password); await userStorage.AddPasswordLoginToUser(UserPassLoginMapper.FromInputModel(model)); User_RoleInputModel userRole = new User_RoleInputModel(); userRole.UserId = model.Id; userRole.RoleId = 251; await userStorage.User_RoleAdd(User_RoleMapper.ToDataModel(userRole)); return(Ok()); }