Skip to content

Instantly share code, notes, and snippets.

@marcosdeaguiar
Created May 20, 2020 17:53
Show Gist options
  • Save marcosdeaguiar/dadfe9c798cf368df7df9cc415948b8f to your computer and use it in GitHub Desktop.
Save marcosdeaguiar/dadfe9c798cf368df7df9cc415948b8f to your computer and use it in GitHub Desktop.
private readonly UserService _userService;
private readonly IAntiforgery _antiforgery;
public UserApiController(UserService userService,
IAntiforgery antiforgery)
{
_userService = userService;
_antiforgery = antiforgery;
}
private void RefreshCSRFToken()
{
var tokens = _antiforgery.GetAndStoreTokens(HttpContext);
HttpContext.Response.Cookies.Append("XSRF-TOKEN",
tokens.RequestToken,
new CookieOptions() { HttpOnly = false });
}
[HttpPost]
[Route("login")]
[ValidateAntiForgeryToken]
[ValidateModel]
[TrimInputStrings]
public async Task<IActionResult> Login([FromBody]LoginViewModel loginModel)
{
var userDto = await _userService.LoginAsync(loginModel);
if (userDto == null)
{
return Unauthorized("Invalid user name or password.");
}
var claimsIdentity = _userService.GenerateClaimsIdentity(userDto);
var jwtToken = _userService.GenerateJwtToken(claimsIdentity);
HttpContext.User = new ClaimsPrincipal(claimsIdentity);
RefreshCSRFToken();
HttpContext.Response.Cookies.Append("jwt",
jwtToken,
new CookieOptions() { HttpOnly = true });
return Ok();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment