Implementing the login functionality and generating a JWT

The GiveNTake application allows anonymous users to access and use some of the APIs, such as product search and product display. But other operations, such as sending and reading messages, are only allowed to registered users, which means that users will have to go through an authentication phase where the application will validate their credentials, such as their username and password, and give them the access token in the form of a JWT. Afterwards, the token will be validated with each request and the user details will be extracted. 

Adding login functionality to the GiveNTake application is done like this: 

  1. First, let's define the user login input, that is, their email and password, as a DTO that can be received in the HTTP request body:
    public class LoginUserDTO
{
public string Password { get; set; }
public string Email { get; set; }
}
  1. Now, continue with defining the successful login response — the JWT — as a DTO that will be returned in the HTTP response body:
    public class SuccessfulLoginResult
{
public string Token { get; set; }
}
  1. Now, add a login endpoint by adding the following method to the AccountController (note that we will define the JWT generation method afterwards):
    [AllowAnonymous]
[HttpPost("login")]
public async Task<ActionResult<SuccessfulLoginResult>>
Login([FromBody] LoginUserDTO login)
{
SignInResult result = await
_signInManager.PasswordSignInAsync(login.Email, login.Password,
isPersistent: false, lockoutOnFailure: false);
if (!result.Succeeded)
{
return Unauthorized();
}

User user = await _userManager.FindByEmailAsync(login.Email);
JwtSecurityToken token = await GenerateTokenAsync(user);
//defined
string serializedToken = new
JwtSecurityTokenHandler().WriteToken(token); //serialize the
token
return Ok(new SuccessfulLoginResult() { Token = serializedToken
});
}

The Login method accepts the user input and signs the user in with the help of the SignInManager, which securely validates that the password is correct for the specified username, and responds with an UnauthorizedResult  (status code 401) if not. Afterwards, the user's details are fetched from the database and the JWT generated and returned to the user.

  1. Now, define the JWT generation method that will create a JWT token with an expiration period:
    private async Task<JwtSecurityToken> GenerateTokenAsync(User  
user)
{
var claims = new List<Claim>();

// Loading the user Claims

var expirationDays = _configuration.GetValue<int>
("JWTConfiguration:TokenExpirationDays");
var siginingKey =
Encoding.UTF8.GetBytes(_configuration.GetValue<string>
("JWTConfiguration:SigningKey"));
var token = new JwtSecurityToken
(
issuer: _configuration.GetValue<string>
("JWTConfiguration:Issuer"),
audience: _configuration.GetValue<string>
("JWTConfiguration:Audience"),
claims: claims,
expires:
DateTime.UtcNow.Add(TimeSpan.FromDays(expirationDays)),
notBefore: DateTime.UtcNow,
signingCredentials: new SigningCredentials(new
SymmetricSecurityKey(siginingKey),
SecurityAlgorithms.HmacSha256)
);

return token;
}

The GenerateTokenAsync method accepts the user as input and creates a JwtSecurityToken instance that is configured with issuer, audience, and signingKey that are loaded from the application configuration. The created JWT is set to be valid from the creation time and to expire after the period of time specified in the application configuration. For now, I have left the claims collection empty, but soon, we will fill them with claims that describe the user and their permissions.

  1. Run the application and send an HTTP POST request to the endpoint at http://localhost:[port]/api/account/login with the username and password, as shown here:

The text in this image is not important; you may get different values. The purpose of this image is to show you what the structure of the request and response should look like in Postman.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.15.245.1