Set Authentication & Authorize in the controller to dynamically based on User Identity roles

591 Views Asked by At

I have a controller that authorizes logged in users based on roles.

now we have a generic website that allows users from different companies to login, how do I dynamically restrict the controllers based on roles.

Here is my code

[Authorize(Roles = "CompanyA")]   ///how can I dyanmicaly set the Roles e.g CompanyB, CompanyC etc
public ActionResult Index()
{
  your code
}

UPDATE BASED ON @MISHA130 Advise

Problem now is how to I get the authenticated user and which roles he/she has ? thanks

public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
        {
            // Go to the database, check your user role compare if the user can do it.
            // do all your logic here
           

            var xx = HttpContext.User.Identity.Name;
            var a = User.Identity.GetUserId();
            var x = HttpContext.Current.User.Identity.Name;
            var userId = User.FindFirstValue(ClaimTypes.NameIdentifier); // will give the user's userId
            var userNames = User.FindFirstValue(ClaimTypes.Name); // will give the user's userName


            string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
            isAuthorized = await _userManager.IsInRoleAsync(userName, "RSA Test");
            if (!isAuthorized)
            {
                context.Result = new ForbidResult();
            }
        }
1

There are 1 best solutions below

4
misha130 On

You can add an authorization filter and do your own logic there:

public class DynamicRoleFilterAttribute : Attribute, IAsyncAuthorizationFilter
{
    public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
    {
        // Go to the database, check your user role compare if the user can do it.
        // do all your logic here

        if (!isAuthorized)
        {
            context.Result = new ForbidResult();
        }
    }
}

Afterwards apply it to your actions as need be

[DynamicRoleFilter]
public ActionResult Index()
{
   // your code
}

Or you can globally add it to all your actions by adding it in your Startup.cs:

services.AddControllers(options =>
                options.Filters.Add<DynamicRoleFilterAttribute >())