Authorization - NeoSOFT-Technologies/rest-dot-net-core GitHub Wiki

Description

Authorization is the process of checking privileges for a user to access specific modules in an application. Simply it is the process of determining whether a user has access to a resource after authentication based on their identity and check the user has sufficient rights to access the requested resources. Resources can be ASP.NET web page, media files, Compressed file, etc.

We have used JWT(JSON Web Token) Role-based Authorization. Authorizing based on roles is available out-of-the-box with ASP.NET Identity. As long as the bearer token used for authentication contains a roles element, ASP.NET Core’s JWT bearer authentication middleware will use that data to populate roles for the user.

So, a roles-based authorization attribute (like [Authorize(Roles = "Administrator")] to limit access to admins) can be added to APIs and work immediately.

Code Snippet

First of all, we have created a class named RoleConfiguration.cs in Configurations folder of Identity layer. It defines two user's role named Viewer and Administrator as shown below,

public class RoleConfiguration : IEntityTypeConfiguration<IdentityRole>
    {
        public void Configure(EntityTypeBuilder<IdentityRole> builder)
        {
            builder.HasData(
                new IdentityRole
                {
                    Name = "Viewer",
                    NormalizedName = "VIEWER"
                },
                new IdentityRole
                {
                    Name = "Administrator",
                    NormalizedName = "ADMINISTRATOR"
                }
            );
        }
    }

First user data in UserCreator class in Seed folder of Identity layer.

public static class UserCreator
    {
        public static async Task SeedAsync(UserManager<ApplicationUser> userManager)
        {
            var applicationUser = new ApplicationUser
            {
                FirstName = "John",
                LastName = "Smith",
                UserName = "johnsmith",
                Email = "[email protected]",
                EmailConfirmed = true
            };

            var user = await userManager.FindByEmailAsync(applicationUser.Email);
            if (user == null)
            {
                await userManager.CreateAsync(applicationUser, "User123!@#");
                await userManager.AddToRoleAsync(applicationUser, "Administrator");
            }
        }
    }

The controller actions are secured with JWT using the [Authorize] attribute. In this scenario we likely need to do some additional validation of the user to ensure we have the right user for specific operations.

To set up up Role specific restrictions we can use the Roles parameter as shown below,

Authorization2

[Authorize(Roles = "Administrator")]

To enable the Authorization on our project we need to add the code snippet below in our Startup.cs under configure method.

Authorization1