2009-05-04 78 views
0

我在冒充用户时遇到了麻烦。我宣布这样的方法:声明式安全要求 - SecurityAction.Demand是否缓存?

[PrincipalPermission(SecurityAction.Demand, [email protected]"DJPITER-PC\Test", Role="LocalTestGroup")] 
static void LocalTestGroupOnly() 
{ 
    Console.WriteLine("Inside LocalTestGroupOnly() - {0}", 
     WindowsIdentity.GetCurrent().Name); 
} 

调用代码:

WindowsImpersonationContext context = 
     WindowsIdentity.Impersonate(token); 

    Console.WriteLine("Calling LocalTestGroupOnly() as {0}", 
     WindowsIdentity.GetCurrent().Name); 
    LocalTestGroupOnly(); 

    context.Undo(); 

    try 
    { 
     // Reverted user is displayed properly 
     Console.WriteLine("Calling LocalTestGroupOnly() as {0}", 
      WindowsIdentity.GetCurrent().Name); 

     // This method should fail but if succeeds 
     LocalTestGroupOnly(); 
    } 
    catch (SecurityException ex) 
    { 
     Console.WriteLine("Your account lacks permission to that function."); 
    } 

默认用户是不是LocalTestGroup的成员。 由LocalTestGroup的标记IS成员指示的用户。

问题:

第一次调用LocalTestGroupOnly()成功,因为用户令牌指示IS LocalTestGroup的构件。对LocalTestGroupOnly()的第二个调用(默认用户)应该失败,因为默认用户不是“Test”,并且它不属于LocalTestGroup。问题是这种方法也成功了。

如果我单独运行程序 - 有和没有模拟,我们的行为是正确的:它在冒充“测试”时成功,在作为默认用户调用时失败。

这里有什么问题?

回答

1

您能否检查Thread.CurrentPrincipal.Identity而不是WindowsIdentity.GetCurrent()PrincipalPermission.Demand()使用第一个。

要更改Thread.CurrentPrincipal(或HttpContext.User),似乎必须在模拟后或撤消后明确设置它们。检查here有类似的问题。

+0

事实上:在context.Undo()之后,我必须添加Thread.CurrentPrincipal = new WindowsPrincipal(WindowsIdentity.GetCurrent()); 为什么没有Undo()方法做到这一点?看起来我没有完全理解Thread.CurrentPrincipal和WindowsImpersonationContext ... – pkolodziej 2009-05-05 06:21:58