ASP.NET Identity - Filter roles based on company

449 views Asked by At

I have a web application that holds data for multiple companies (like Multitenancy) but a user can have access to more than one company (point of difference from Multitenancy). Furthermore, a user may have different access rights for different companies.

For Example: User A has Admin access for Company A and only Basic access for Company B

To support this functionality I have added Company to the AspNetUserRoles table. What I want to do is filter the roles returned by Identity framework based on the Company selected for the user logging in.

The application uses FindByNameAsync method from the UserManager class to return the user object but I assume my tie in point is further back in the stack.

What is the best way to achieve this functionality and where is the best tie in point?

Any help would be appreciated.

1

There are 1 answers

1
ManP On

You can achieve this functionality by:

  1. Adding multiple roles for one company for e.g. CompanyA_Admin, CompanyA_Basic, CompanyB_Admin, CompanyB_Basic in aspnet_Roles table
  2. Then further get all roles for a given user by System.Web.Security.Roles.GetRolesForUser()
  3. To get all the companies for the user:

    string[] CompaniesForUser()
    {
    
    //Change to commented version for production   
    string[] roles = new string[] { "CompanyA_Admin", "CompanyB_Admin", "CompanyA_Basic", "CompanyB_Basic" };  //System.Web.Security.Roles.GetRolesForUser();
    string[] companies = new string[100];
    int index = 0;
    
    foreach(string role in roles)
    {
        string cName =  role.Split('_')[0];
    
        //Only add new companies
        if (!companies.Contains(cName))
        {
            companies[index] = cName;
    
            //Testing
            Response.Write("Index : " + index + " - " + cName + "<br>");
    
            index++;
        }
    }
    
    return companies;
    

    }