问题
So, what is the purpose for existence of both IIdentity
and IPrincipal
, and not some IIdentityMergedWithPrincipal
? When is it not enough to implement both in same class?
Also, to understand purpose, I'd like to know where this concept comes from:
- It is originated in .Net
- There is concept of Identity/Principal as design pattern, which
System.Security.Principal
implemented in those interfaces - It is originated somewhere else and supported for compatibility
Therefore, does UserPrincipal
from System.DirectoryServices
act similarly to IPrincipal
but not implement it by accident or by intention?
P.S. I'm looking for reasoning behind idea, not benefits/controversies comparison, so please try not to start opinion-based discussion
回答1:
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.
回答2:
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.
回答3:
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
回答4:
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;
}
}
来源:https://stackoverflow.com/questions/27107848/what-is-the-idea-behind-iidentity-and-iprincipal-in-net