ASP.NET Core 2.2 REST API #11 — User Login
Up Next: User Specific Content with JWT Claims
The users are already saved at the database, so we are ready to issue tokens at log-in as well.
Just make another login endpoint, with the LoginRequest
, LoginSuccessResponse
and LoginFailResponse
contracts, as well as a new method on our IdentityService
called — you guessed it — LoginAsync
, returning a Task<AuthenticationResult>
as well.
For starters, we can just refactor all of the token issuing logic:
All we need to do really is:
- Check if the user exists
- Check if the password hashed after salting matches
This is really, really easy, now that we have set everything up:
We can check that this works as expected:
There is one extra thing we can do to spice up our user handling. That would be to add the [EmailAddress]
attribute on our UserRegistrationRequest
. That enforces correct email validation for the registration. We are going to look into FluentValidator in a later video.
Then, on our registration endpoint, we can just return BadRequest()
if (!ModelState.IsValid)
. This model state validation is driven by many things, including this attribute we just added.
The list of errors is accessible by ModelState.Values.Select(x => x.Errors.Select(xx => xx.ErrorMessage))
, to add to our AuthFailedResponse
contract.
Code is available on Github and the instructional videos are located on YouTube.
Keep Coding