Search code examples
c#.netasp.net-mvc-5asp.net-identity

IIdentity, IPrincipal or IUser: what's the difference?


I'm trying to implement simple role based authentication + authorization in an MVC5 application, but I'm getting some headache trying to understand all the parts involved in Identity framework

I'm reading several tutorials and guides, but I stil haven't a clear idea.

In particular: which is the difference among IIdentity, IPrincipal or IUser interfaces? Which of them should I implement?


Solution

  • 'IPrincipal' is a .Net framework's interface:

    public interface IPrincipal {
        // Retrieve the identity object
        IIdentity Identity { get; }
    
        // Perform a check for a specific role
        bool IsInRole (string role);
    }
    

    This interface defines the basic functionality of logged in user. Object implementing this interface represents the security context under which your code is running. You can get different flavors of IPrincipal in .Net: ClaimsPrincipal, WindowsPrincipal and others - all depends on the framework you are using. If you are working with Asp.Net Identity framework, you'll be dealing with ClaimsPrincipal. Usually you don't need to implement this interface.

    IIdentity represents user's permissions. For Asp.Net Identity framework you'll be dealing with ClaimsIdentity. Again, this is something you don't need to implement.

    Here is more documentation about the IPrincipal and IIDentity.

    IUser is part of Asp.Net Identity framework. If you are using Entity Framework part of Identity, you'll be provided with IdentityUser class that you can inherit and extend. This is a model for you to implement.

    Basically IdentityUser is a POCO that is preserved into a database. And when user is logged in, information from IdentityUser will be transformed into ClaimsPrincipal and ClaimsIdentity by the framework. And when you access HttpContext.Current.User you will be given ClaimsPrincipal.

    Hope this clears things up for you.