Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>To add to CalebHC's code and answer ssmith's question about handling users who have multiple roles...</p> <p>Our custom security principal returns a string array representing all the groups/roles that a user is in. So first we have to convert all the strings in the array that match items in the enum. Finally, we look for any match - if so, then the user is authorized.</p> <p>Note that we're also redirecting an unauthorized user to a custom "NotAuthorized" view.</p> <p>The whole class looks like this:</p> <pre><code>[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)] public class CustomAuthorizeAttribute : AuthorizeAttribute { /// &lt;summary&gt; /// Add the allowed roles to this property. /// &lt;/summary&gt; public Roles Is { get; set; } /// &lt;summary&gt; /// Checks to see if the user is authenticated and has the /// correct role to access a particular view. /// &lt;/summary&gt; /// &lt;param name="httpContext"&gt;&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; protected override bool AuthorizeCore(HttpContextBase httpContext) { if (httpContext == null) throw new ArgumentNullException("httpContext"); if (!httpContext.User.Identity.IsAuthenticated) return false; var iCustomPrincipal = (ICustomPrincipal) httpContext.User; var roles = iCustomPrincipal.CustomIdentity .GetGroups() .Select(s =&gt; Enum.Parse(typeof (Roles), s)) .ToArray(); if (Is != 0 &amp;&amp; !roles.Cast&lt;Roles&gt;().Any(role =&gt; ((Is &amp; role) == role))) { return false; } return true; } protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { if (filterContext == null) throw new ArgumentNullException("filterContext"); filterContext.Result = new ViewResult { ViewName = "NotAuthorized" }; } } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload