0

I have users in membership and one user can have one or more than one roles assigned. I want to check for specific roles of a page for example:

Role1, Role2, Role3, Role4, Role5

Users who have access of Role2 and Role3 can access Page1.aspx and Also if user who have access of Role1 and Role2 also can access because Role2 is there available.

I have implemented membership and have list of user's roles string array with the help of

string[] roles = Roles.GetRolesForUser(User.Identity.Name);

How can I check against multiple roles? May I need to do one by one check with using Roles.IsUserInRole function?

I have used; It returns 0 count because of Partner in capital. How can I do ignore case? And is below is right way to check array against array?

string[] userroles = { "Partner", "testsetsr" };
 string[] requiredroles = { "contractor", "customer", "sims", "nonclientau", "partner" };
        var countInRoles = userroles.Intersect(requiredroles).Count();
k-s
  • 2,192
  • 11
  • 39
  • 73

1 Answers1

0

You would have to implement your own Authorization Filter Attribure. To do that you can create a class extending 'AuthorizationAttribute', then override OnAuthorization where you can specify your required role-checks.

A small example on how to do that would be here in Nimesh's .Net Blog

The example is not a solution to your personal problem, but should give you the idea about what you need to do.

Edit: The same goes for your applications role-provider, extend it and override IsUserInRole (or maybe better even add a new method) to provide the checks you need in order to have Roles.IsUserInRole work the way you want.

To your 2nd question: if you have 2 arrays and want to count how many members of 1st array are members of the 2nd while ignoring case you can do that using linq

var countInRoles = userroles.Select(u => u.ToLower()).Count(u => requiredroles.Select(r => r.ToLower()).Contains(u));

On the other hand, lets vice versa the lists if you have a list of required roles to access some action you can also check if a user has all required roles using linq (again with ignoring case)

string[] requiredroles = { "Partner", "testsetsr" };
string[] userroles = { "contractor", "testsetsr", "customer", "sims", "nonclientau", "partner" };
var userHasAllRequiredRoles = requiredroles.Select(r => r.ToLower()).All(r => userroles.Select(u => u.ToLower()).Contains(r));
Ingo
  • 1,805
  • 18
  • 31