How to implement IIdentity for a user object in ASP.NET MVC?

In my ASP.NET MVC application, I am trying to create a custom HttpContent.User object. I started by creating a Member class that implements IPrincioal.

public class Member : IPrincipal { public string Id { get; set; } public IIdentity Identity { get; set; } public bool IsInRole(string role) { throw new NotImplementedException(); } ... } 

Then, during authentication, I set HttpContext.User to an instance of the Member class:

 FormsAuthentication.SetAuthCookie(email, false); HttpContext.User = member; 

Then later I want to check if the user is authenticated, for example:

 if (User.Identity.IsAuthenticated) { ... } 

Where I am stuck. I'm not sure what I need to do for the public IIdentity Identity in the member instance. . So I can use the HttpContext.User object something like this:

 IsAuthenticated = HttpContext.User.Identity.IsAuthenticated; ViewBag.IsAuthenticated = IsAuthenticated; if (IsAuthenticated) { CurrentMember = (Member)HttpContext.User; ViewBag.CurrentMember = CurrentMember; } 
+4
source share
1 answer

A Principal is not something you can ask once when writing a cookie and forget later. During subsequent requests, the auth cookie is read and the IPrincipal / IIdentity restored before the action method is executed. When this happens, trying to apply HttpContext.User to your custom Member type will throw an exception.

One option is to intercept in ActionFilter and simply wrap the standard implementation.

 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); } } 

Thus, you do not lose anything that goes out of the box with the standard implementations of IPrincipal and IIdentity . You can still call IsAuthenticated on IIdentity or even IsInRole(string) on IPrincipal . The only thing you get is the additional Id property in your custom IPrincipal implementation (although I'm not sure where it came from or why you need it).

+5
source

All Articles