public async Task <IActionResult> Auth( [FromForm] AuthBinding binding, [FromServices] AuthenticationService authenticationService, CancellationToken cancellationToken) { switch (binding.GrantType) { case GrantType.password: if (IsNullOrEmpty(binding.UserName)) { BadRequest(ErrorView.Build(O2AuthErrorCode.InvalidRequest, $"Field 'username' is required for '{GrantType.password}' grant type")); } if (IsNullOrEmpty(binding.Password)) { BadRequest(ErrorView.Build(O2AuthErrorCode.InvalidRequest, $"Field 'password' is required for '{GrantType.password}' grant type")); } try { var(accessToken, expiresIn, refreshToken) = await authenticationService.AuthenticationByPassword(binding.UserName, binding.Password, HttpContext.GetIp(), cancellationToken); return(Ok(new TokenView(accessToken, "Bearer", (Int64)expiresIn.TotalSeconds, refreshToken))); } catch (UnauthorizedException) { return(BadRequest(ErrorView.Build(O2AuthErrorCode.UnauthorizedClient, "Email or password is incorrect"))); } case GrantType.refresh_token: if (IsNullOrEmpty(binding.RefreshToken)) { BadRequest(ErrorView.Build(O2AuthErrorCode.InvalidRequest, $"Field 'refresh_token' is required for '{GrantType.refresh_token}' grant type")); } try { var(accessToken, expiresIn, refreshToken) = await authenticationService.AuthenticationByRefreshToken(binding.RefreshToken, HttpContext.GetIp(), cancellationToken); return(Ok(new TokenView(accessToken, "Bearer", (Int64)expiresIn.TotalSeconds, refreshToken))); } catch (UnauthorizedException) { return(BadRequest(ErrorView.Build(O2AuthErrorCode.UnauthorizedClient, "Refresh token is incorrect"))); } default: return(BadRequest(ErrorView.Build(O2AuthErrorCode.UnsupportedGrantType, $"Unsupported grant type: {binding.GrantType}."))); } }
public ActionResult <AuthResponse> Authenticate([FromBody] AuthBinding model) { var user = _ZaxHerbivoryTrainerRepository.Authenticate(model.UserName); // return null if user not found if (user == null) { return(BadRequest(new { message = "Username or password is incorrect" })); } //password check var passwordHash = new PasswordHasher(10000); var passwordCheck = passwordHash.Check(user.Password, model.Password); if (!passwordCheck.Verified) { return(BadRequest("Username or password is incorrect")); } // authentication successful so generate jwt token var tokenHandler = new JwtSecurityTokenHandler(); var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_appSettings.Secret)); var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var AuthTime = DateTime.Now; var claims = new[] { new Claim(JwtRegisteredClaimNames.Sub, model.UserName), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), new Claim(JwtRegisteredClaimNames.AuthTime, AuthTime.ToString()) }; var token = new JwtSecurityToken( issuer: _appSettings.Issuer, audience: _appSettings.Issuer, claims, expires: DateTime.Now.AddMinutes(120), signingCredentials: credentials); var encodeToken = new JwtSecurityTokenHandler().WriteToken(token); var response = new AuthResponse() { BearerToken = encodeToken, RoleType = user.RoleType, ExpiryDate = DateTime.Now.AddMinutes(120) }; var accessToken = new Token { UserGuid = "",//unknown at this point CreateTime = AuthTime, ExpiresTime = DateTime.Now.AddMinutes(120), RoleId = user.RoleType, UserId = user.RoleId }; //create login token var tokenResult = _ZaxHerbivoryTrainerRepository.CreateToken(accessToken); _ZaxHerbivoryTrainerRepository.Save(); response.AccessId = tokenResult.TokenId; return(Ok(response)); }