If User.IsInRole with a string array?

I am trying to create a custom check, where I check if the role contains a user role. And I have problems with a string array, what is the 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 do I change the check for User.IsInRole so that it processes the array?

+4
source share
4 answers

What about:

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

Edit: (Assuming being a member of any of the roles is enough for authorization.)

+12
source

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

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

If it’s enough to be a member of at least one of the required roles, use Any :

 bool isAuthorized = AuthRoles.Any(filterContext.HttpContext.User.IsInRole); 
+8
source

You can do this with a simple linq expression:

 bool isAuthorized = AuthRoles.All(filterContext.HttpContext.User.IsInRole); 
+2
source

You need to check every line

 bool isAuthorized = false; foreach(string role in AuthRoles) { if(filterContext.HttpContext.User.IsInRole(role)) isAuthorized = true; } 
+1
source

Source: https://habr.com/ru/post/1299930/


All Articles