ASP.NET Identity - Filter Roles Based on Company

I have a web application that stores data for multiple companies (e.g. Multitenancy), but a user can access multiple companies (point of difference from Multitenancy). In addition, the user can 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 added the company to the table AspNetUserRoles

. What I want to do is filter the roles returned by the Identity framework based on the company selected for the user's login.

The app uses a method FindByNameAsync

from the class UserManager

to return a user object, but I am assuming my binding at point is on the stack again.

What is the best way to achieve this functionality and where is the best fit?

Any help would be appreciated.

+3


source to share


1 answer


You can achieve this functionality using



  • Adding multiple roles for one company, for example. CompanyA_Admin, CompanyA_Basic, CompanyB_Admin, CompanyB_Basic in the aspnet_Roles table.
  • Then additionally get all roles for a given user using System.Web.Security.Roles.GetRolesForUser ()
  • To get all companies for a 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;
    
          

    }

0


source







All Articles