WCF模拟不是冒充管理员

时间:2010-10-07 16:54:50

标签: c# wcf uac impersonation

我正在尝试使用WCF来做一些远程用户管理事情。我重复使用我在服务器2003机箱上的一些代码并且工作正常,但是当我检查调用该函数的用户是否为管理员时,在我的Windows 7测试框中,它说它不是。

[OperationBehavior(Impersonation=ImpersonationOption.Required)]
public string SetPassword(string username)
{
    WindowsPrincipal principal = new WindowsPrincipal(OperationContext.Current.ServiceSecurityContext.WindowsIdentity);
    System.Diagnostics.Debug.Print(WindowsIdentity.GetCurrent().Name);
    System.Diagnostics.Debug.Print(principal.Identity.Name);
    if (principal.IsInRole(WindowsBuiltInRole.Administrator))
    {
        //try
        {
            lock (Watchdog.m_principalContext)
            {
                using (UserPrincipal up = UserPrincipal.FindByIdentity(Watchdog.m_principalContext, username))
                {
                    string newpassword = CreateRandomPassword();
                    up.SetPassword(newpassword);
                    up.Save();
                    return newpassword;
                }
            }
        }
        //catch
        {
            return null;
        }
    }
    else 
        throw new System.Security.SecurityException("User not administrator");
}

principal.IsInRole(WindowsBuiltInRole.Administrator)每次都返回false。我当前的身份和principal.idenity都是被模仿的正确用户。该用户是管理员用户组的成员。

我认为它与在Windows Vista中实现的UAC有关。这将是一个问题,因为这将是一个win2k8-r2盒生产机器。

有关该怎么做的任何建议?

2 个答案:

答案 0 :(得分:3)

在“使用Windows Vista处理”一节中查看此article,这是一篇关于UAC的非常好的文章,并以编程方式检查管理员权限。

答案 1 :(得分:0)

由于我不想完成所有工作(来自RandomNoob的帖子)以检查用户是否是管理员并且服务已经在管理上下文中运行,我决定放弃模拟。我创建了一个名为WCFUsers的新用户组,任何将使用该服务的用户都被添加到该组中。它现在在其自己的上下文中执行System.DirectoryServices.AccountManagement操作。

[OperationBehavior(Impersonation=ImpersonationOption.NotAllowed)]
public string SetPassword(string username)
{
    WindowsPrincipal principal = new WindowsPrincipal(OperationContext.Current.ServiceSecurityContext.WindowsIdentity);
    if (principal.IsInRole("WCFUsers"))
    {
        try
        {
            lock (Watchdog.m_principalContext)
            {
                using (UserPrincipal up = UserPrincipal.FindByIdentity(Watchdog.m_principalContext, username))
                {
                    string newpassword = CreateRandomPassword();
                    up.SetPassword(newpassword);
                    up.Save();
                    return newpassword;
                }
            }
        }
        catch
        {
            return null;
        }
    }
    else
        return null;
}
相关问题