views:

254

answers:

4

Hello

Im tryint ot build a custom validation where I check if the user contains in a role. And I'm having problems with string array, what is best way to check if it contains a specific value?

    public string[] AuthRoles { get; set; }


    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {

        if (AuthRoles.Length > 0)
        {

            if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
            {

               RedirectToRoute(filterContext,
               new
               {
                   controller = "AdminLogin",
                   action = "AdminLogin"
               });

            }
            else
            {
                bool isAuthorized = filterContext.HttpContext.User.IsInRole(this.AuthRoles.??);

                if (!isAuthorized)
                    throw new UnauthorizedAccessException("You are not authorized to view this page");
            }
        }
        else
        {
            throw new InvalidOperationException("No Role Specified");
        }

How shall I modify the check for User.IsInRole so it handles the array? .Any, .Contains?

/M

+5  A: 

How about:

bool isAuthorized = 
    this.AuthRoles.Any(r => filterContext.HttpContext.User.IsInRole(r));

Edit: (Assuming that being member of any of the roles is enough to be authorized.)

Anders Fjeldstad
+5  A: 

If you want the user to have all the roles in the AuthRoles at the same time, you should:

bool isAuthorized =
         Array.TrueForAll(AuthRoles, filterContext.HttpContext.User.IsInRole);

If just being a member of at least one of the required roles is enough, use Any:

bool isAuthorized = AuthRoles.Any(filterContext.HttpContext.User.IsInRole);
Mehrdad Afshari
A: 

You need to check each string

bool isAuthorized = false;

foreach(string role in AuthRoles)
{
  if(filterContext.HttpContext.User.IsInRole(role))
    isAuthorized = true;
}
AaronLS
My solution only requires the user be member of one of the roles. So it depends on what you are wanting.
AaronLS
+1  A: 

You can do it with a simple linq expression:

bool isAuthorized = AuthRoles.All(filterContext.HttpContext.User.IsInRole);
klausbyskov