public async Task <IActionResult> Login(CustomerForLoginDto customerForLoginDto) { var customerFromRepo = await _repo.Login(customerForLoginDto.Customername.ToLower(), customerForLoginDto.Password); if (customerFromRepo == null) { return(Unauthorized()); } var claims = new[] { new Claim(ClaimTypes.NameIdentifier, customerFromRepo.CustomerId.ToString()), new Claim(ClaimTypes.Name, customerFromRepo.Customername) }; var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config.GetSection("AppSettings:Token").Value)); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(claims), Expires = DateTime.Now.AddDays(1), SigningCredentials = creds }; var tokenHandler = new JwtSecurityTokenHandler(); var token = tokenHandler.CreateToken(tokenDescriptor); return(Ok(new { token = tokenHandler.WriteToken(token) })); }
public async Task <IActionResult> Login(CustomerForLoginDto customerForLoginDto) { var customer = await _iCustomerManager.Login(customerForLoginDto.Email, customerForLoginDto.Password); if (customer == null) { return(BadRequest(new { message = "Username or password incorrect" })); } else if (customer.Token == null) { return(Unauthorized()); } else { return(Ok(new { token = customer.Token })); } }
public async Task <IActionResult> Login(CustomerForLoginDto customerForLoginDto) { // Makes username lowercase customerForLoginDto.Username = customerForLoginDto.Username.ToLower(); // Get logged in customer, null if failed var loggedInCustomer = await repo.Login(customerForLoginDto.Username.ToLower(), customerForLoginDto.Password); if (loggedInCustomer == null) { return(Unauthorized()); } // Ensure customer id and user match with pulled customer var claims = new[] { new Claim(ClaimTypes.NameIdentifier, loggedInCustomer.CustomerId.ToString()), new Claim(ClaimTypes.Name, loggedInCustomer.CustFirstName), }; // Creates a key from token signature defined in app settings var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(config.GetSection("AppSettings:Token").Value)); // Creates new credentials using key and encryption algorithm var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature); // Creates the token descriptor using our claims, credentials, and expires from 6 hours var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(claims), Expires = DateTime.Now.AddDays(1), SigningCredentials = creds }; // Creates token using the above var tokenHandler = new JwtSecurityTokenHandler(); var token = tokenHandler.CreateToken(tokenDescriptor); IdentityModelEventSource.ShowPII = true; // returns the token if login successful return(Ok(new { token = tokenHandler.WriteToken(token) })); }