2012-06-28 37 views
0

我想做一个函数来确定一个用户,其ID是通过参数传递的是一个管理员。我能为当前登录做到这一点与用户 -看看用户是否是Windows 7中的管理员?

 public static bool IsAuthorizedUser() 
    { 

     WindowsIdentity identity = WindowsIdentity.GetCurrent(); 
     WindowsPrincipal principal = new WindowsPrincipal(identity); 
     return principal.IsInRole(WindowsBuiltInRole.Administrator); 
    } 

,但我想检查中传递的任何用户因此签名会变为

public static bool IsAuthorizedUser(string username_to_check) 

我怎样才能做到这一点?任何帮助表示赞赏。

+0

你显然需要知道有问题的用户的密码,看看这个:http://blogs.msdn.com/b/saurabhkv/archive/2008/05/29/windowsidentity-impersonation - 使用-C-code.aspx –

+0

和这一个了http://msdn.microsoft.com/en-us/library/w070t6ka.aspx –

+0

有什么办法来解决呢?这就是我想要的。我只是想检查用户是否是管理员。我不明白为什么我不得不知道他们的密码.. – Sterling

回答

1

我能得到它的工作我如何想与UserPrincipal尝试。感谢所有的反馈。

public static bool IsAuthorizedUser(string userId) 
{ 
    PrincipalContext ctx = new PrincipalContext(ContextType.Machine); 
    UserPrincipal usr = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, userId); 

    bool result = false; 
    if(usr == null) 
    { 
     Console.WriteLine("usr is null"); 
    } 
    else 
    { 
     foreach (Principal p in usr.GetAuthorizationGroups()) 
     { 
      if (p.ToString() == "Administrators") 
      { 
       result = true; 
      } 
     } 
     } 
     return result; 
    } 
0

这样看来,你需要考虑的WindowsIdentity的声明,看看是否有一些方法来检索它的字符串名称的用户身份。

+0

它有一个构造函数。它会为我的用户名返回true,但每当我在管理员中创建一个新用户并运行代码时,它总是与消息一起崩溃“引用的帐户当前被锁定并且可能未登录。” – Sterling

+0

@Sterling我认为你需要使用有问题的用户的密码。 –

+0

normaly,即用户通过认证后,我们属性角色的身份,和我们重视CurrentThread应用 –

0

你可以用这个代码

if(principal.Identity.IsAuthenticated) 
{ 
    //Passed 
} 
+0

这会可能返回TRUE;对于被登录的所有用户,对不对? – Joey

+0

正是在这种情况下,认证和授权之间的区别,我认为英镑要验证此服务认证 –

+0

我认为OP希望能够判断一个特定的用户,不一定登录的用户是的成员管理员小组。 –

相关问题