安全性的两个基本支柱是身份验证和授权。身份验证是标识用户的过程,授权在验证了所标识用户是否可以访问特性资源之后进行。本节介绍如何使用标识符和principals获得用户的信息。
1. 使用Windows标识
使用标识可以验证运行应用程序的用户。WindowsIndentity类表示一个Windows用户。如果没有用Windows账户标识用户,也可以使用实现了IIdentity接口的其他类。通过这个接口可以访问用户名、该用户是否通过身份验证,以及验证类型等信息。
principal是一个包含用户的标识和用户的所属角色的对象。IPrincipal接口定义了Identity属性和IsInRole()方法,Identity属性返回IIdentity对象;在IsInRole()方法中,可以验证用户是否是指定角色的一个成员。角色是有相同安全权限的用户集合,同时它是用户的管理单元。角色可以是Windows组或自己定义的一个字符串集合。
.NET中的Principal类有WindowsPrincipal、GenericPrincipal和RolePrincipal。从.NET 4.5开始,这些Principal类型派生于基类ClaimsPrincipal。还可以创建实现了IPrincipal接口或派生于ClaimsPrincapal的自定义Principal类。
示例代码仅运行在Windows上,使用如下依赖项和名称空间:
依赖项
System.Security.Principal.Windows
名称空间
System
System.Collections.Generic
System.Security.Claims
System.Security.Principal
下面创建一个控制台应用程序(.NET Core),它可以访问某个应用程序中的主体,以便允许用户访问底层的Windows账户。这里需要导入System.Security.Principal和System.Security.Claims名称空间。Main()方法调用方法ShowIdentityInformation()把WindowsIdentity的信息写到控制台,调用ShowPrincipal写入可用于principals的额外信息,调用ShowClaims写入声称信息:
static void Main(string[] args)
{
WindowsIdentity identity = ShowIdentityInformation();
WindowsPrincipal principal = ShowPrincipal(identity);
ShowClaims(principal.Claims);
}
ShowIndentityInformation()方法通过调用WindowsIndentity的静态方法GetCurrent,创建一个WindowsIdentity对象,并访问其属性,来显示身份类型、名称、身份验证类型和其他值:
public static WindowsIdentity ShowIndentityInformation()
{
WindowsIdentity identity = WindowsIdentity.GetCurrent();
if (identity == null)
{
Console.WriteLine("not a Windows Identity");
return null;
}
Console.WriteLine($"IdentityType: {identity}");
Console.WriteLine($"Name: {identity.Name}");
Console.WriteLine($"Authenticated: {identity.IsAuthenticated}");
Console.WriteLine($"Authentication Type: {identity.AuthenticationType}");