Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If User.IsInRole with string array?

Im trying to build a custom validation where I check if the role contains a user. 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 should I modify the check for User.IsInRole so it handles the array?

like image 499
Lasse Edsvik Avatar asked Nov 28 '22 20:11

Lasse Edsvik


1 Answers

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.)

like image 106
Anders Fjeldstad Avatar answered Dec 06 '22 05:12

Anders Fjeldstad