Search code examples
asp.net-mvcauthenticationasp.net-identity

ASP.NET MVC Authentication cast to IIdentity from IdentityUser


I am trying to implement authentication in my MVC project. The issue is that I have implemented ASP.NET Identity OWIN. I can successfully authenticate and everything looks good.

The issue is that there are other Projects (such as a Service Layer) that retrieves the authenticated user via System.Threading.Thread.CurrentPrincipal.Identity

In this service layer the value is casted to a custom class as following:

public MyCompanyIdentity Identity
    {
        get { return System.Threading.Thread.CurrentPrincipal.Identity as MyCompanyIdentity ; }
    }

The content of the MyCompanyIdentity class is as Follows:

public class MyCompanyIdentity : IIdentity
    {
        public MyCompanyIdentity ();

        public string EndUserName { get; set; }
        public string Exception { get; set; }
        public string Ticket { get; set; }
        public string Company { get; set; }
        public string Fullname { get; set; }
        public string Email { get; set; }
        public bool IsAuthenticated { get; }
        public string Name { get; }
        public string AuthenticationType { get; }
    }

In my controller class I set the authentication as follow:

var userStore = new UserStore<DemoApplicationUser>(new PeopleSaaIdentityContext());
var userManager = new UserManager<DemoApplicationUser>(userStore);
var user = userManager.Find(username, password);

if (user != null)
{
    var authManager = HttpContext.Current.GetOwinContext().Authentication;
    ClaimsIdentity userIdentity = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
    authManager.SignIn(new Microsoft.Owin.Security.AuthenticationProperties() { IsPersistent = true }, userIdentity);
    //How do I cast/convert the System.Threading.Thread.CurrentPrincipal.Identity to a MyCompanyIdentity?                                              
 }

Since I can't change the MyCompanyIdentity to implement IdentityUser as I don't have access to the source code.

How do I "cast/convert" to IIdenityUser? I would like to resuse the same class as it used literally everywhere in the application.

I really hope it makes sense else let me know and I would try to explain further.


Solution

  • It had no choice other than rewritting the logic from scratch.