.NET 中的 Principal 到底是什么?

What is really a Principal in .NET?

在谈论 .NET 中的身份时,我们有 Principal. There's the interface IPrincipal and together with it the implementation ClaimsPrincipal. We can even access one instance of an implementation of that interface any time using Thread.CurrentPrincipal 的想法。

现在,我一直不明白这个校长到底是什么。确实,起初我以为它是代表当前用户身份的东西。但事实并非如此,事实上还有另一个接口IIdentity together with implementation ClaimsIdentity。稍微搜索一下,我在 MSDN 上发现了以下内容:

A principal object represents the security context of the user on whose behalf the code is running, including that user's identity (IIdentity) and any roles to which they belong.

但是 代码代表 运行 的用户的安全上下文究竟意味着什么?我想我还没有明白这应该代表什么。

授权访问资源或运行 某些代码的能力时,仅知道哪个用户正在授权该操作是不够的,但他们是在什么角色下授权的。

认为这大致等同于提升 shell:shell 现在 运行 在不同的主体下(具有更多权限),即使主体的身份仍然相同(您的用户帐户)。

IIdentity 类型主要围绕 身份验证 问题,即确定系统已知的身份实际上属于想要以该身份行事的代理.这是授权任何事情的必要先决条件,但不是全部。

主体是封装身份和角色的抽象事物,因此它是代码 运行 所在的安全上下文。这可以是 Windows 身份(即 Windows 或 Active Directory 用户帐户)和 Windows "role"、a.k.a。 "group",或者它可以是独立于 Windows 用户和角色但仍可跨多个应用程序使用的 identity/role。第三,它也可以是仅在您的应用程序中定义的身份和角色的自定义概念。

安全上下文不是静态的;它可以通过调整委托人的角色来改变,从而在安全上下文下为身份(用户)和应用程序提供更多或更少的特权 运行。

这里是了解更多相关信息的好起点:https://msdn.microsoft.com/en-us/library/z164t8hs.aspx

描述是这么说的,主体就是身份加角色。

其实很简单

public interface IPrincipal 
{
    IIdentity Identity { get; }
    bool IsInRole( string role );
}

抽象它的想法非常重要。虽然最初只有少数实现(包括 WindowsPrincipalRolePrincipalGenericPrincipal),但后来引入了其他实现(例如 ClaimsPrincipal)。许多遗留代码可以无缝升级到新的实现,在不改变任何其他东西的情况下获得所有好处。

A principal represents the identity and role of a user and acts on the user's behalf.

来源:https://docs.microsoft.com/en-us/dotnet/standard/security/key-security-concepts