public async Task <Authentication.OutModel> Authentication([FromBody] Authentication.InModel inModel) { AuthValidator validationRules = new AuthValidator(); await validationRules.ValidateAndThrowAsync(inModel); return(await _iAccessControlService.Authentication(inModel)); }
public async Task <Authentication.Models.OutModel> Authentication(Authentication.Models.InModel inModel, CancellationToken cancellationToken = default) { AuthValidator authValidator = new AuthValidator(); await authValidator.ValidateAndThrowAsync(inModel); var user = await _dbContext.Users.SingleOrDefaultAsync(x => x.Email == inModel.Email, cancellationToken); if (user == null) { throw new InvalidOperationException("User with email not exist."); } if (!Cryptor.VerifyPasswordHash(inModel.PasswordHash, user.PasswordHash)) { throw new InvalidOperationException("Email or password is incorrect."); } var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(_appSettings.Secret); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, user.Id.ToString()) }), Expires = DateTime.UtcNow.AddDays(7), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); user.Token = tokenHandler.WriteToken(token); return(new Authentication.Models.OutModel { IdUser = user.Id, UserName = user.Username, Token = user.Token }); }