Skip to content

Instantly share code, notes, and snippets.

@changhuixu
Last active July 24, 2020 18:24
Show Gist options
  • Save changhuixu/37d62f61d1ded8a48e231bf10a76df8a to your computer and use it in GitHub Desktop.
Save changhuixu/37d62f61d1ded8a48e231bf10a76df8a to your computer and use it in GitHub Desktop.
[ApiController]
[Authorize]
[Route("api/[controller]")]
public class AccountController : ControllerBase
{
private readonly ILogger<AccountController> _logger;
private readonly IUserService _userService;
private readonly IJwtAuthManager _jwtAuthManager;
public AccountController(ILogger<AccountController> logger, IUserService userService, IJwtAuthManager jwtAuthManager)
{
_logger = logger;
_userService = userService;
_jwtAuthManager = jwtAuthManager;
}
[AllowAnonymous]
[HttpPost("login")]
public ActionResult Login([FromBody] LoginRequest request)
{
if (!ModelState.IsValid)
{
return BadRequest();
}
if (!_userService.IsValidUserCredentials(request.UserName, request.Password))
{
return Unauthorized();
}
var role = _userService.GetUserRole(request.UserName);
var claims = new[]
{
new Claim(ClaimTypes.Name,request.UserName),
new Claim(ClaimTypes.Role, role)
};
var jwtResult = _jwtAuthManager.GenerateTokens(request.UserName, claims, DateTime.Now);
_logger.LogInformation($"User [{request.UserName}] logged in the system.");
return Ok(new LoginResult
{
UserName = request.UserName,
Role = role,
AccessToken = jwtResult.AccessToken,
RefreshToken = jwtResult.RefreshToken.TokenString
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment