Mar*_*own 29
您可以通过创建新的Principal来设置线程的标识.您可以使用从System.Security.Principal.IIdentity继承的任何标识,但是您需要一个继承自System.Security.Principal.IPrincipal的类,该类采用您正在使用的标识类型.
为简单起见,.Net框架提供了GenericPrincipal和GenericIdentity类,可以像这样使用:
using System.Security.Principal;
// ...
GenericIdentity identity = new GenericIdentity("M.Brown");
identity.IsAuthenticated = true;
// ...
System.Threading.Thread.CurrentPrincipal =
new GenericPrincipal(
identity,
new string[] { "Role1", "Roll2" }
);
//...
if (!System.Threading.Thread.CurrentPrincipal.IsInRole("Roll1"))
{
Console.WriteLine("Permission denied");
return;
}
Run Code Online (Sandbox Code Playgroud)
但是,这不会授予您使用新标识的窗口权限.但是,如果您正在开发一个网站并希望创建自己的用户管理,它会很有用.
如果您想伪装成与当前使用的帐户不同的Windows用户,则需要使用模拟.有关如何执行此操作的示例,请参阅System.Security.Principal.WindowsIdentity.Impersonate()的帮助.您运行的帐户可以模拟哪些帐户存在限制.
在某些情况下,.Net框架会为您进行模拟.发生这种情况的一个示例是,如果您正在开发ASP.Net网站,并且已为正在运行的虚拟目录或站点启用了集成Windows身份验证.