Identity对象
Identity对象是实现了IIdentity接口的类的实例。IIdentity接口包括三个只读属性:
string AuthenticationType {get;} 获取所使用的身份验证的类型 bool IsAuthenticated {get;} 获取布尔值,该值指出登陆用户是否经过验证 string Name {get;} 获取当前用户的名称
.NET中实现了接口的有以下四个类:
1、GenericIdentity 用来表示一般性的用户,可以用于自定义登陆验证的情况。
2、WindowsIdentity 用来表示登陆Windows系统成功的普通Windows用户。
3、FormsIdentity 用来表示ASP.NET应用程序中使用Forms身份验证的用户。
4、PassportIdentity 用来表示在使用Passport的应用程序中的用户。不过要注意必须要安装了Passport SDK才能使用这个类。
因为在当前的具体开发中使用得最多的是前三个,而FormsIdentity类将在后文专门讲到,所以下面我们将详细讨论前两个类
GenericIdentity类
GenericIdentity类其实相当简单,它并不与任何特定的验证协议相关联。因此,它往往被用在采用了自定义登陆机制的场合。比如一个程序可以自己提示用户输入用户名和密码,然后到自定义的用户数据库中去查询。如果用户名和密码有效,那么程序就会创建一个基于数据库中的匹配记录的principal和(对应的)identity对象。
GenericIdentity类除了三个IIdentity接口定义的属性之外没有更多的东西了。不过,GenericIdentity类提供了两个构造函数。一个构造函数接受一个字符串参数,该参数指定的是用户名;另一个构造函数接受两个参数:第一个是用户名字符串,第二个是给定的验证类型字符串。
public GenericIdentity(string name); public GenericIdentity(string name, string type); |
现在我们不过多地讲述使用GenericIdentity类的细节问题,在后面我们将会看到在一个实际的程序当中是如何使用GenericIdentity对象的。
WindowsIdentity类
作为实现了IIdentity接口的派生类,WindowsIdentity类主要用于表示登陆Windows成功的用户。下面我们依次来看看WindowsIdentity类的构造函数,属性和方法。
在构造函数中会用到IntPtr类型的参数,我们先来看看这种数据类型,IntPtr类型通常用来表示与平台相关的数据类型,比如一个内存指针或者是一个句柄。在我们使用的情况下,IntPtr参数通常用来代表一个Win32句柄,而这个句柄指向的是一个32位的用户的帐号标记(account token)。这个标记一般是通过调用非托管的Win32 API获得的。
public WindowsIdentity(IntPtr userToken); public WindowsIdentity(IntPtr userToken, string authType); public WindowsIdentity(IntPtr userToken, string authType, WindowsAccountType acctType); public WindowsIdentity(IntPtr userToken, string authType, WindowsAccountType acctType, bool isAuthenticated); |
每一个构造函数都带有相同的IntPtr参数,后面跟着一些带有其他信息的参数:验证类型,Windows帐号类型以及验证状态。要注意WindowsAccountType参数必须要使用下列枚举值之一:Anonymous,Guest,Normal,System。
理所当然的,WindowsIdentity类也具有IIdentity接口的三个只读属性: AuthenticationType,IsAuthenticated和Name。另外,WindowsIdentity类还有自身特有的属性:IsAnonymous,IsGuest和IsSystem,有了这三个属性可以更好的确定用户帐号。
接着再来看看WindowsIdentity类的方法。除了继承于Object类的方法之外,WindowsIdentity类还有这样三个方法:GetAnonymous,GetCurrent和Impersonate。
1、GetAnonymous方法返回的是一个表示匿名用户的WindowsIdentity对象。
2、GetCurrent方法返回的是一个表示当前用户的WindowsIdentity对象。
3、Impersonate方法可以让你的代码临时模拟出一个用户。
GetAnonymous和GetCurrent方法都返回一个WindowsIdentity对象,使用也很简单,我们需要注意的是Impersonate方法,该方法有两个版本:实例版本(instance version)和静态版本(static version)。实例版本的方法不带参数,返回一个基于被调用WindowsIdentity对象的WindowsImpersonationContext对象(WindowsImpersonationContext类表示模拟操作之前的 Windows 用户);静态版本则需要一个IntPtr参数。这种模拟操作对于服务器程序来说是很有用的,它可以降低客户端访问服务器所用用户帐号的权限,从而在一定程度上提高了安全性。下面是上述方法的具体语法:
public static WindowsIdentity GetAnonymous(); public static WindowsIdentity GetCurrent(); public virtual WindowsImpersonationContext Impersonate(); public static WindowsImpersonationContext Impersonate(IntPtr userToken); |
|
|