Adding claims that can be used for authorization

JWT allows you to set whatever key-value you wish as a claim. We can leverage this fact to store user permissions so that we can later retrieve them and use them for authorization. The ASP.NET Core authorization infrastructure provides us with an easy way to add claims to the user and store them in the database by giving us the AddClaimsAsync method that's provided by the UserManager class. For example, I modified the GiveNTake user registration logic to add the registration date as a claim:

[AllowAnonymous]
[HttpPost("register")]
public async Task<IActionResult> Register([FromBody] RegisterUserDTO registration)
{
...

user = await _userManager.FindByEmailAsync(registration.Email);
await _userManager.AddClaimAsync(user,
new Claim("registration-date", DateTime.UtcNow.ToString("yy-MM-dd")));

...
}

The user registration date is now stored in the database as a claim, and when the user logs in, we will load it (and all other claims) by using the UserManager GetClaimsAsync method and adding it to the generated token:

private async Task<JwtSecurityToken> GenerateTokenAsync(User user)
{
var claims = new List<Claim>() { ... };

var userClaims = await _userManager.GetClaimsAsync(user);
claims.AddRange(userClaims);

var token = new JwtSecurityToken
(
claims: claims,
...
);

return token;
}

Now, when running the application and sending an HTTP POST request to the login API, the returned token includes the registration date claim.

..................Content has been hidden....................

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