Skip to content

Instantly share code, notes, and snippets.

@depuits
Last active October 6, 2020 11:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save depuits/8ae37a2db0a44abea6bfc30c72349f27 to your computer and use it in GitHub Desktop.
Save depuits/8ae37a2db0a44abea6bfc30c72349f27 to your computer and use it in GitHub Desktop.
PrincipalExtensions for checking user roles
using System.Linq;
using System.Security.Principal;
public static class PrincipalExtensions
{
public static bool IsInAllRoles (this IPrincipal principal, params string[] roles)
{
return roles.All (r1 => r1.Split (',').All (r2 => principal.IsInRole (r2.Trim())));
}
public static bool IsInAnyRoles (this IPrincipal principal, params string[] roles)
{
return roles.Any (r1 => r1.Split (',').Any (r2 => principal.IsInRole (r2.Trim())));
}
}
@jkrizan
Copy link

jkrizan commented Mar 18, 2019

If you change "r2 => principal.IsInRole (r2)" to "r2 => principal.IsInRole (r2.Trim())", it will work for "admin, user, manager" ...

@GinCanhViet
Copy link

Not working on razor view

@depuits
Copy link
Author

depuits commented Oct 6, 2020

Not working on razor view

What exactly isn't working? Do you get any errors?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment