Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OverrideAuthorization attribute in .NETCore

In the controller code below, only users who are in the "Administrator" role can access the GetData() action method, because of the controller-level AuthorizeAttribute. But I also want users who only are in "Manager" role to have access to the GetData() action method.

[Authorize(Roles = "Administrator")]
Public class AdminController : Controller
{
    [Authorize(Roles = "Administrator, Manager")]
    public IActionResult GetData()
    {
    }
}

Is there an option like OverrideAuthorization attribute available in .NET Core framework to achieve this requirement?

like image 848
Pravin Avatar asked Nov 30 '17 10:11

Pravin


People also ask

What is authorization attribute in ASP NET Core web API?

Authorization is a basic requirement while the application is used by multiple & multilevel users. While developing APIs, it's also important to provide basic authorization to handle security. Here we will see how to implement the authorization attribute in ASP. Net Core web API.

How to override the onauthorization method of a custom authorization filter?

Right-click on the solution and add a new class. Enter the class name and click on Add. Next Inherite Attribute, IAuthorizationFilter to CustomAuthorization class which has overridden the OnAuthorization method. public void OnAuthorization (AuthorizationFilterContext filterContext)

What is role-based authorization in ASP NET Core?

Role-based authorization in ASP.NET Core. When an identity is created it may belong to one or more roles. For example, Tracy may belong to the Administrator and User roles whilst Scott may only belong to the User role. How these roles are created and managed depends on the backing store of the authorization process.

How do I apply the authorizeattribute to a razor page?

For Razor Pages, the AuthorizeAttribute can be applied by either: Filter attributes, including AuthorizeAttribute, can only be applied to PageModel and cannot be applied to specific page handler methods.


1 Answers

All above is right, i just want to give a full example easy for all My case is Asp.Net Core 3.1

Startup.js (ConfigureServices):

            services.AddIdentity<ApplicationUser, IdentityRole>(config =>
            {
                config.User.RequireUniqueEmail = false;    // óíèêàëüíûé email
                config.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 -._@+"; 
                config.SignIn.RequireConfirmedEmail = false;
            })
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddUserManager<UserManager<ApplicationUser>>()
                .AddRoleManager<RoleManager<IdentityRole>>()
                .AddDefaultTokenProviders();

            services.AddAuthorization(options =>
            {
                options.AddPolicy("User", policy => {
                    policy.RequireClaim("User");
                });
                options.AddPolicy("Admin", policy => {
                    policy.RequireRole("Admin");
                });
            });

services.AddScoped<IAuthorizationHandler, RolesAuthorizationHandler>();

Startup.js (Configure):

    app.UseAuthentication();
    app.UseAuthorization();

Controller:

[Authorize(Policy = "Admin")]
public class RoleController : Controller

Handler-Example:

 public class RolesAuthorizationHandler : AuthorizationHandler<RolesAuthorizationRequirement>, IAuthorizationHandler
    {

        private readonly RoleManager<IdentityRole> _roleManager;
        private readonly UserManager<ApplicationUser> _userManager;
        public RolesAuthorizationHandler(RoleManager<IdentityRole> roleManager, UserManager<ApplicationUser> userManager)
        {
            _roleManager = roleManager;
            _userManager = userManager;
        }

        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context,
                                                       RolesAuthorizationRequirement requirement)
        {
            if (context.User == null || !context.User.Identity.IsAuthenticated)
            {
                context.Fail();
                return Task.CompletedTask;
            }

            var validRole = false;
            if (requirement.AllowedRoles == null ||
                requirement.AllowedRoles.Any() == false)
            {
                validRole = true;
            }
            else
            {
                var claims = context.User.Claims;
                //var userName = claims.FirstOrDefault(c => c.Type == "UserName").Value;
                var allowedRoles = requirement.AllowedRoles;

                var loggedInUserTask = _userManager.GetUserAsync(context.User);
                loggedInUserTask.Wait();
                var user = loggedInUserTask.Result;
                var roles = _userManager.GetRolesAsync(user);
                roles.Wait();
                var roleList = roles.Result;

                validRole = roleList.Where(p => allowedRoles.Contains(p.ToString())).Any();
            }

            if (validRole)
            {
                context.Succeed(requirement);
            }
            else
            {
                context.Fail();
            }
            return Task.CompletedTask;
        }
    }

I While updating a project that used to exist, I moved the old user table to the user table in the new identity database. Later, I defined roles at the table level for them, and with the RoleManager I wrote in this way, I left his next administration to the step. Quite successful. In my case, many people probably updated their old projects. However, I did not have such a post and wanted to share it. The following section is for them:

public class RoleAssignViewModel
    {
        public string RoleId { get; set; }
        public string RoleName { get; set; }
        public bool HasAssign { get; set; }
    }

    public class RoleViewModel
    {
        [Required(ErrorMessage = "Fill the role.")]
        [Display(Name = "Role Name")]
        public string Name { get; set; }
    }

    [Authorize(Policy = "Admin")]
    public class RoleController : Controller
    {
        private readonly RoleManager<IdentityRole> _roleManager;
        private readonly UserManager<ApplicationUser> _userManager;
        public RoleController(RoleManager<IdentityRole> roleManager, UserManager<ApplicationUser> userManager)
        {
            _roleManager = roleManager;
            _userManager = userManager;
        }
        public async Task<IActionResult> RoleAssign(string id)
        {
            ApplicationUser user = await _userManager.FindByIdAsync(id);
            List<IdentityRole> allRoles = _roleManager.Roles.ToList();
            List<string> userRoles = await _userManager.GetRolesAsync(user) as List<string>;
            List<RoleAssignViewModel> assignRoles = new List<RoleAssignViewModel>();
            allRoles.ForEach(role => assignRoles.Add(new RoleAssignViewModel
            {
                HasAssign = userRoles.Contains(role.Name),
                RoleId = role.Id,
                RoleName = role.Name
            }));

            return View(assignRoles);
        }
        [HttpPost]
        public async Task<ActionResult> RoleAssign(List<RoleAssignViewModel> modelList, string id)
        {
            ApplicationUser user = await _userManager.FindByIdAsync(id);
            foreach (RoleAssignViewModel role in modelList)
            {
                if (role.HasAssign)
                    await _userManager.AddToRoleAsync(user, role.RoleName);
                else
                    await _userManager.RemoveFromRoleAsync(user, role.RoleName);
            }
            return RedirectToAction("Index", "User");
        }
        public IActionResult RoleList()
        {
            return View(_roleManager.Roles.ToList());
        }
        public async Task<IActionResult> DeleteRole(string id)
        {
            IdentityRole role = await _roleManager.FindByIdAsync(id);
            IdentityResult result = await _roleManager.DeleteAsync(role);
            if (result.Succeeded)
            {
                //Başarılı...
            }
            return RedirectToAction("Index");
        }
        public async Task<IActionResult> CreateRole(string id)
        {
            if (id != null)
            {
                IdentityRole role = await _roleManager.FindByIdAsync(id);

                return View(new RoleViewModel
                {
                    Name = role.Name
                });
            }
            return View();
        }
        [HttpPost]
        public async Task<IActionResult> CreateRole(RoleViewModel model, string id)
        {
            IdentityResult result = null;
            if (id != null)
            {
                IdentityRole role = await _roleManager.FindByIdAsync(id);
                role.Name = model.Name;
                result = await _roleManager.UpdateAsync(role);
            }
            else
                result = await _roleManager.CreateAsync(new IdentityRole { Name = model.Name });

            if (result.Succeeded)
            {
                //Başarılı...
            }
            return View();
        }

        //[Authorize]
        public IActionResult UserRoleList()
        {
            return View(_userManager.Users);
        }

    }
like image 142
Hamit YILDIRIM Avatar answered Sep 29 '22 01:09

Hamit YILDIRIM