In your Models/User folder - add another class called UserForLogin.cs.
This will be the same as our the register DTO we created earlier. We could use that here - but, we will be making changes later, so it's better to go ahead and have two.
Now we're finally ready to write our Login() method.
In this method, we don't need to validate the user's input. If their username and/or passwords don't match - we don't want to give them too much information about what was wrong. We'll just return Unauthorized().
[HttpPost("Login")]publicasyncTask<IActionResult> Login([FromBody] UserForLogin userForLogin){var userFromDb =await_authService.Login(userForLogin.Username.ToLower(),userForLogin.Password);if (userFromDb ==null)returnUnauthorized(); // GENERATE TOKENvar tokenHandler =newJwtSecurityTokenHandler();var key =newbyte[0]; // we'll add this after adding DI latervar tokenDescriptor =newSecurityTokenDescriptor// Describes information we want to include in our token { Subject =newClaimsIdentity(newClaim[] // Payload {newClaim(ClaimTypes.NameIdentifier,userFromDb.Id.ToString()),newClaim(ClaimTypes.Name,userFromDb.Username) }), Expires =DateTime.Now.AddDays(1), SigningCredentials =newSigningCredentials(newSymmetricSecurityKey(key),SecurityAlgorithms.HmacSha512Signature) };var token =tokenHandler.CreateToken(tokenDescriptor); // Create tokenvar tokenString =tokenHandler.WriteToken(token); // to string (from byte[])returnOk( new { tokenString }); // Return 200, passing along tokenString}
There is a lot going on here. Some comments have been added to help make it more clear what's going on.
We're getting the user from the database and checking if it's null -- if so, we return Unauthorized().
We're using a SecurityTokenDescriptor to format our token - right now we're giving our payload two pieces of information: the Id and username.
We're using JwtSecurityTokenHandler to actually create the token with the descriptor we made and also to write it to a string.
Register Authentication and Add Middleware in Startup Class
Now we need to register our key in our DI container and configure our middleware to use authentication.
In your Startup.cs class add the following to the ConfigureServices() method: