2

I have implemented a custom Principle for ASP.Net identity, however when I try to get my custom principle from HttpContext.Current.User I receive the following exception:

Unable to cast object of type 'System.Security.Principal.GenericPrincipal' to type 'VenuePortal.Business.ICustomPrincipal'.

My implementation is:

public interface ICustomPrincipal : IPrincipal
{
    int UserID { get; set; }
    string UserName { get; set; }
    string Email { get; set; }
    string AuthCode { get; set; }
    string Title { get; set; }
}

public class CustomPrincipal : ICustomPrincipal
{
    public int UserID { get; set; }
    public string UserName { get; set; }
    public string Email { get; set; }
    public string AuthCode { get; set; }
    public string Title { get; set; }
    public IIdentity Identity { get; private set; }
    public bool IsInRole(string role) { return false; }
    public CustomPrincipal(string email)
    {
        Identity = new GenericIdentity(email);
    }
}

The error throws in this Ninject binding:

kernel.Bind<ICustomPrincipal>().ToMethod(context => (ICustomPrincipal)HttpContext.Current.User).InRequestScope();

I have this same solution working in another (older) project so I'm guessing there is some kind of framework change affecting this? HttpContext.Current.User still seems to return an IPrinciple so shouldn't this all work?

Any help much appreciated.

Simon
  • 6,062
  • 13
  • 60
  • 97

2 Answers2

0

HttpContext.Current.User is indeed implements IPrincipal and the object behind this is usually GenericPrincipal if you are using Asp.Net Identity framework. And GenericPrincipal is part of .Net framework and it can't implement your ICustomPrincipal interface.

If you are looking to do extension methods on User object to pull extra data out there are few different approaches (using claims is one of them). But creating your own CustomPrincipal is a thing of a past now there are easier ways to do that.

trailmax
  • 34,305
  • 22
  • 140
  • 234
0

I have discovered that this is caused when the user is not logged in. I have found two solutions to this:

  1. Do not try to inject the current user when they are not logged in (quite simple in this instance as I just removed the property from my LoginController.
  2. Inject a factory class which handles returning the current user. Ninject is always able to instantiate and inject this, regardless of whether the user is logged in or not. The factory class handles dealing with any null exceptions etc.

I hope this helps someone else.

Simon
  • 6,062
  • 13
  • 60
  • 97