What is the idea behind IIdentity and IPrincipal in .NET

女生的网名这么多〃 提交于 2019-12-02 17:25:45

IIdentity is just used for the user's authenticated identity, regardless of what roles they may have.

IPrincipal is used to combine a user's identity with the authorized roles they have in a given security context.

For example, you can use a third-party login provider, like Facebook or Google, to get the user's identity, but you will not get a principal from those providers, as they don't provide any roles. You can use your own application or a third-party role-based authorization provider to apply roles to, say, a FacebookIdentity or GoogleIdentity. A different application can expect a different principal, with its own roles, but still use the same identity as in another application.

Kevin

A principal is the security context of a user.

In the case of .NET, a principal supports the concept of having more than one identity (This has nothing to do with claims yet). This is particularly important when it comes to semantics that developers need to deal with when it comes to user identity. You may be called on as a developer to support multiple identities coming from different sources (identity providers IdPs), for example: Twitter, Google, whatever.

So what's the different between a IPrincipal and IIDentity? IPrincipal is the security context (for a single thread), and the IIDentity is the set of attributes associated with that user coming from a specific identity provider / authority.

As MSDN site says:

The identity object encapsulates information about the user or entity being validated. At their most basic level, identity objects contain a name and an authentication type.

whereas

The principal object represents the security context under which code is running.

Refer to the above link for a lot more info.

HTH

user7743682
public class HBPrincipal : IPrincipal
{
     private HBIdentity _identity;

     public HBPrincipal(HBIdentity identity)
    {
        _identity = identity;
    }

    public IIdentity Identity
    {
        get
        {
            return _identity;
        }
    }

    public bool IsInRole(string role)
    {
        // TODO implement roles
        return false;
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!