public async Task <string> LoginAuthenticate(LoginAuthenRequest request) { var user = await _userManager.FindByNameAsync(request.UserName); if (user == null) { return(null); } var result = await _signInManager .PasswordSignInAsync(user, request.PassWord, request.RememberMe, true); if (!result.Succeeded) { return(null); } var authClaim = new List <Claim> { new Claim(ClaimTypes.GivenName, user.LastName), new Claim(ClaimTypes.Surname, user.FirstName), new Claim(ClaimTypes.Email, user.Email), new Claim(ClaimTypes.MobilePhone, user.PhoneNumber), new Claim(ClaimTypes.Name, request.UserName), new Claim(ClaimTypes.Hash, request.PassWord) }; var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JWT:Key"])); var token = new JwtSecurityToken( issuer: _configuration["JWT:ValidIssuer"], audience: _configuration["JWT:ValidAudience"], expires: DateTime.Now.AddDays(1), claims: authClaim, signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256Signature) ); return(new JwtSecurityTokenHandler().WriteToken(token)); }
public async Task <IActionResult> Login(LoginAuthenRequest request) { if (!ModelState.IsValid) { return(View(request)); } else { // Goi den backend api var token = await _loginApi.Authen(request); if (string.IsNullOrEmpty(token)) { return(View()); } else { // Sau khi lấy được token, chúng ta sẽ giải mã token này bằng hàm giải mã var userPrincipal = this.ValidateToken(token); var authenProperties = new AuthenticationProperties { ExpiresUtc = DateTimeOffset.UtcNow.AddSeconds(30), IsPersistent = false }; HttpContext.Session.SetString("Token", token); await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, userPrincipal, authenProperties); return(RedirectToAction("Index", "Home")); } } }
public async Task <string> Authen(LoginAuthenRequest request) { var json = JsonConvert.SerializeObject(request); var client = _httpClientFactory.CreateClient(); var httpContext = new StringContent(json, Encoding.UTF8, "application/json"); client.BaseAddress = new Uri("https://localhost:5001"); var result = await client.PostAsync("/api/users/authenticate", httpContext); var token = await result.Content.ReadAsStringAsync(); return(token); }
public async Task <IActionResult> LoginAuthen([FromBody] LoginAuthenRequest request) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var resultToken = await _userService.LoginAuthenticate(request); if (string.IsNullOrEmpty(resultToken)) { return(BadRequest(resultToken)); } return(Ok(resultToken)); }