2012-10-25 174 views
0

在研究SQL CLR存储过程时,我遇到以下链接Link for SQL Bulk Copy in CLR。 在这个环节用户都在使用 WindowsIdentity currentIdentity = SqlContext.WindowsIdentity; WindowsImpersonationContext impersonatedIdentity = currentIdentity.Impersonate(); 什么是WindowsIdentity的含义

我无法理解有什么用WindowsImpersonationContext。没有的它的使用,我能跑我code.Can有人告诉我这是什么身份假冒的确切使用。

回答

0

E.g.如果你想运行在相同的上下文中进程中的线程,你可以做一些类似这样:

private void ImpersonateThread() 
    { 
     new Thread(() => 
     { 
      Thread.CurrentPrincipal = new WindowsPrincipal(WindowsIdentity.GetCurrent()); 
      //Do the work... 
     }).Start(); 
    } 

这是如果运行的网站(在MS-IIS),其中应用程序池是非常有用的作为一个用户运行,认证模式设置为Windows认证。那么你可能会希望线程作为访问该网站的用户来运行。

UPDATE:

我只是想澄清这一点。行:

Thread.CurrentPrincipal = new WindowsPrincipal(WindowsIdentity.GetCurrent()); 

刚刚转会的用户(用户仍然不能冒充该线程还)给线程,因此其它部件可能会看到用户是谁,以及在必要时使用这些信息,例如像这样:

 System.Security.Principal.WindowsImpersonationContext impersonationContext; 
     impersonationContext = 
      ((System.Security.Principal.WindowsIdentity)System.Threading.Thread.CurrentPrincipal.Identity).Impersonate(); 
      //Do the work that you want within the impersonated users context. 
     impersonationContext.Undo(); 

在模拟和撤消之间,用户被模拟并且所有代码都以该用户的身份运行。我知道用户在这个示例中是一样的,但想象一下,该线程使用户完全不同于运行该进程的用户(用户输入的内容或类似内容)。希望这有助于:-)