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?
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With