Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override the IIdentity property of User

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?

like image 545
JuChom Avatar asked Oct 05 '22 22:10

JuChom


1 Answers

You can explicitly implement IPrincipal in your MyPrincipalclass, 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();
    }
}
like image 127
Joe Avatar answered Oct 13 '22 09:10

Joe