Authorizing users by their role

Many times, users of your application will be assigned roles to define their allowed behavior in the application. For example, your application administrators will likely see areas of the application that other users won't be allowed to see, and will be able to perform administrative tasks such as adding categories. 

To add authorization that is based on roles, we don't need to change the claims infrastructure that we have used so far. Instead, we will use the standard role claim and add it for each role a user possesses.

ASP.NET Core provides the RoleManager<TRole> class that resides in the Microsoft.AspNetCore.Identity namespace. RoleManager provides an API for managing the roles that exist in your application and the way they are made persistent in the database.

Here are the steps I took to add roles support to the GiveNTake application:

  1. I've added the following code, as part of the application's DbContext, to add the Administrator role if it doesn't yet exist:
    public async Task SeedRolesAsync(RoleManager<IdentityRole> 
roleManager)
{
if (!await roleManager.RoleExistsAsync("Admin"))
{
var admin = new IdentityRole("Admin");
await roleManager.CreateAsync(admin);
}
}
  1. When the application starts, I execute the SeedRolesAsync method in the same way as I've shown in Chapter 5Persisting Data with Entity Framework, when I added the initial data to the application data model:
    public static void Main(string[] args)
{
var host = BuildWebHost(args);
using (var scope = host.Services.CreateScope())
{
var services = scope.ServiceProvider;
var context = services.GetService<GiveNTakeContext>();
var roleManager =
services.GetService<RoleManager<IdentityRole>>();

try
{
context.Database.Migrate();
context.SeedData();
context.SeedRolesAsync(roleManager).Wait();
}
catch (Exception ex)
{
var logger =
services.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "An error occurred while seeding
the GiveNTake Database.");
throw;
}
}

host.Run();
}
  1. Now that we have an admin role in place, we need to assign it to users. For the sake of demonstration purposes, I've added the following logic to the GiveNTake registration method, where users with an email that contains the word "admin" will be added as administrators:
    public async Task<IActionResult> Register([FromBody] 
RegisterUserDTO registration)
{
...

user = await _userManager.FindByEmailAsync(registration.Email);

if (registration.Email.Contains("admin"))
{
await _userManager.AddToRoleAsync(user, "Admin");
}

...

}

  1. When the user logs in to the application, I add the role as a claim to the JWT:
    var roles = await _userManager.GetRolesAsync(user);
foreach (var role in roles)
{
claims.Add(new Claim(ClaimTypes.Role, role));
}
  1. The final step is to check that a user has the required role in order to use the controller actions. This is done by the required role in the Authorization attribute:
    [Authorize(Roles = "Admin")]
[HttpPost("categories")]
public Task<ActionResult> AddCategory([FromBody] NewCategoryDTO
newCategory)
{
...
}

Roles can be very handy for creating separation inside your application, but there are times when you need a more powerful mechanism to determine if a user can or can't use some functionality by performing more complex logic. In cases where the authorization needs to include more logic, the ASP.NET Core Authorization Policies should be your preferred choice.

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

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