设置线程标识

Dun*_*can 24 .net c# multithreading iidentity

在C#中,如何设置线程的标识?

例如,如果我已经启动了Thread MyThread,我可以更改MyThread的身份吗?

或者这不可能吗?

Mar*_*own 29

您可以通过创建新的Principal来设置线程的标识.您可以使用从System.Security.Principal.IIdentity继承的任何标识,但是您需要一个继承自System.Security.Principal.IPrincipal的类,该类采用您正在使用的标识类型.
为简单起见,.Net框架提供了GenericPrincipalGenericIdentity类,可以像这样使用:

 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身份验证.

  • 我修改了.NET 4.5中的代码,使其工作GenericIdentity identity = new GenericIdentity("user1","Forms"); Thread.CurrentPrincipal = new GenericPrincipal(identity,new string [] {"role1"}); 您可以使用此代码更新有用的帖子,再次感谢您. (2认同)