Created
May 20, 2020 17:53
-
-
Save marcosdeaguiar/dadfe9c798cf368df7df9cc415948b8f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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