I have developed a simple IIdentity
and IPrincipal
for my MVC project and I would like to override the User
and User.Identity
to return the value with the right type
Here is my custom Identity:
public class MyIdentity : IIdentity
{
public MyIdentity(string name, string authenticationType, bool isAuthenticated, Guid userId)
{
Name = name;
AuthenticationType = authenticationType;
IsAuthenticated = isAuthenticated;
UserId = userId;
}
#region IIdentity
public string Name { get; private set; }
public string AuthenticationType { get; private set; }
public bool IsAuthenticated { get; private set; }
#endregion
public Guid UserId { get; private set; }
}
Here is my custom Principal:
public class MyPrincipal : IPrincipal
{
public MyPrincipal(IIdentity identity)
{
Identity = identity;
}
#region IPrincipal
public bool IsInRole(string role)
{
throw new NotImplementedException();
}
public IIdentity Identity { get; private set; }
#endregion
}
Here is my custom controller, I successfully updated the User
property to return my custom principal type:
public abstract class BaseController : Controller
{
protected new virtual MyPrincipal User
{
get { return HttpContext == null ? null : HttpContext.User as MyPrincipal; }
}
}
How can I do it the same way for User.Identity
to return my custom identity type?
You can explicitly implement IPrincipal
in your MyPrincipal
class, and add your own Identity
property of type MyIdentity
.
public class MyPrincipal : IPrincipal
{
public MyPrincipal(MyIdentity identity)
{
Identity = identity;
}
public MyIdentity Identity {get; private set; }
IIdentity IPrincipal.Identity { get { return this.Identity; } }
public bool IsInRole(string role)
{
throw new NotImplementedException();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With