Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>A Principal is not something you can just set once when writing the auth cookie and forget later. During subsequent requests, the auth cookie is read and the <code>IPrincipal</code> / <code>IIdentity</code> is reconstructed before executing an action method. When that happens, trying to cast the <code>HttpContext.User</code> to your custom <code>Member</code> type will throw an exception.</p> <p>One option would be to intercept in an <code>ActionFilter</code>, and just wrap the standard implementation.</p> <pre><code>public class UsesCustomPrincipalAttribute : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { var systemPrincipal = filterContext.HttpContext.User; var customPrincipal = new Member(systemPrincipal) { Id = "not sure where this comes from", }; filterContext.HttpContext.User = customPrincipal; } } public class Member : IPrincipal { private readonly IPrincipal _systemPrincipal; public Member(IPrincipal principal) { if (principal == null) throw new ArgumentNullException("principal"); _systemPrincipal = principal; } public string Id { get; set; } public IIdentity Identity { get { return _systemPrincipal.Identity; } } public bool IsInRole(string role) { return _systemPrincipal.IsInRole(role); } } </code></pre> <p>This way, you're not losing anything that comes out of the box with the default <code>IPrincipal</code> and <code>IIdentity</code> implementations. You can still invoke <code>IsAuthenticated</code> on the <code>IIdentity</code>, or even <code>IsInRole(string)</code> on the <code>IPrincipal</code>. The only thing you're gaining is the extra <code>Id</code> property on your custom <code>IPrincipal</code> implementation (though I'm not sure where this comes from or why you need it).</p>
 

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