public async Task <IActionResult> UserLogin(LoginVm login, string ReturnUrl = "/User") { if (!ModelState.IsValid) { return(View(login)); } LoginUserVm user = await _authServices.UserExist(login.UserPhoneNumber, login.Password); if (user != null) { var claims = new List <Claim>() { new Claim(ClaimTypes.NameIdentifier, user.Fullname), new Claim(ClaimTypes.Name, user.Username) }; var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme); var principal = new ClaimsPrincipal(identity); var properties = new AuthenticationProperties { IsPersistent = login.RememberMe }; await HttpContext.SignInAsync(principal, properties); return(Redirect(ReturnUrl)); } ModelState.AddModelError("UserPhoneNumber", "کاربری با مشخصات وارد شده یافت نشد"); return(View(login)); }
public IActionResult Login([FromForm] LoginUserVm applicationUser) { if (string.IsNullOrWhiteSpace(applicationUser.Login) || string.IsNullOrWhiteSpace(applicationUser.Password) || !ModelState.IsValid) { _logger.LogInformation( $"Login or password are empty or invalid."); return(BadRequest("Invalid credentials")); } var result = _signInManager .PasswordSignInAsync(applicationUser.Login, applicationUser.Password, true, false).Result; if (result.Succeeded == false) { _logger.LogInformation( $"Invalid username ({applicationUser.Login}) or password ({applicationUser.Password})"); return(BadRequest("Invalid credentials")); } var tokenExpirationMinutes = 20; var claims = new[] { new Claim("username", applicationUser.Login), new Claim(JwtRegisteredClaimNames.Nbf, new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds().ToString()), new Claim(JwtRegisteredClaimNames.Exp, ((long)((DateTime.Now.AddMinutes(tokenExpirationMinutes) - new DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds)).ToString()) }; var claimsIdentity = new ClaimsIdentity(claims, "Token"); var user = _dbContext.Users.FirstOrDefault(u => u.UserName == applicationUser.Login); if (user == null) { return(StatusCode(500, "Given user does not exist in the database.")); } var roles = _userManager.GetRolesAsync(user).Result; claimsIdentity.AddClaims(roles.Select(role => new Claim(ClaimTypes.Role, role))); var token = new JwtSecurityToken ( _jwtOptions.Issuer, _jwtOptions.Issuer, claimsIdentity.Claims, expires: DateTime.Now.AddMinutes(tokenExpirationMinutes), notBefore: DateTime.Now, signingCredentials: new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtOptions.SecretKey)), SecurityAlgorithms.HmacSha256) ); var encodedJwt = new JwtSecurityTokenHandler().WriteToken(token); var response = new { access_token = encodedJwt, expires_in = token.ValidTo.ToString("yyyy-MM-ddTHH:mm:ss") }; var json = JsonConvert.SerializeObject(response, _serializerSettings); return(new OkObjectResult(json)); }
public async Task <IActionResult> Login([FromBody] LoginUserVm user) { if (ModelState.IsValid) { var existingUser = await _userManager.FindByEmailAsync(user.UserName) ?? await _userManager.FindByNameAsync(user.UserName); if (existingUser == null) { return(BadRequest(new AuthResultVm() { Errors = new List <string>() { "Ugyldig bruker eller passord" } })); } var passwordIsCorrect = await _userManager.CheckPasswordAsync(existingUser, user.Password); if (!passwordIsCorrect) { return(BadRequest(new AuthResultVm() { Errors = new List <string>() { "Ugyldig bruker eller passord" } })); } var jwtToken = await GenerateJwtToken(existingUser); return(Ok(jwtToken)); } return(BadRequest(new AuthResultVm() { Errors = new List <string>() { "Ugyldig data innsendt" } })); }
public async Task <IActionResult> Login([FromForm] LoginUserVm applicationUser) { var identity = await _tokenProviderMiddleware.GetClaimsIdentity(applicationUser); if (identity == null) { _logger.LogInformation( $"Invalid username ({applicationUser.Email}) or password ({applicationUser.Password})"); return(BadRequest("Invalid credentials")); } var claims = new[] { new Claim(JwtRegisteredClaimNames.Sub, applicationUser.Email), new Claim(JwtRegisteredClaimNames.Jti, await _jwtOptions.JtiGenerator()), new Claim(JwtRegisteredClaimNames.Iat, _tokenProviderMiddleware.ToUnixEpochDate(_jwtOptions.IssuedAt).ToString(), ClaimValueTypes.Integer64), identity.FindFirst("IdentityUser") }; // Create the JWT security token and encode it. var jwt = new JwtSecurityToken( issuer: _jwtOptions.Issuer, audience: _jwtOptions.Audience, claims: claims, notBefore: _jwtOptions.NotBefore, expires: _jwtOptions.Expiration, signingCredentials: _jwtOptions.SigningCredentials); var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt); // Serialize and return the response var response = new { access_token = encodedJwt, expires_in = (int)_jwtOptions.ValidFor.TotalSeconds }; var json = JsonConvert.SerializeObject(response, _serializerSettings); return(new OkObjectResult(json)); }
public Task <ClaimsIdentity> GetClaimsIdentity(LoginUserVm dto) { var user = _uow.Repository <User>().Get(u => u.Email == dto.Email, false); if (user != null) { SignInResult result = null; result = _signInManager.PasswordSignInAsync(user.UserName, dto.Password, true, false).Result; if (result.Succeeded) { return(Task.FromResult(new ClaimsIdentity(new GenericIdentity(user.UserName, "Token"), new[] { new Claim("IdentityUser", "User") }))); } } return(Task.FromResult <ClaimsIdentity>(null)); }