检测C#中的管理员权限 [英] Detect admin rights in C#

查看:174
本文介绍了检测C#中的管理员权限的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检查登录用户是否具有管理员权限。

我在ASP.NET 4.5.2,C#,Visual Studio 2015中开发控制台应用程序。



我以域用户身份登录,拥有管理员权限。



我尝试了什么:



尝试了几个谷歌上可用的代码示例,但似乎都没有。下面是几个样本。



//样本#1



返回WindowsIdentity.GetCurrent()。 Owner.IsWellKnown(WellknownSidType.BuiltinAdministratorsSid);



//样本#2

WindowsIdentity identity = WindowsIdentity.GetCurrent();

WindowsPrinciipal principal = new WindowsPrincipal(identity);

return princiapl.IsInRole(WindowsBuiltInRole.Administrator);



以上代码返回true,仅当Visual Studio 2015以管理员身份运行时才会返回false。



我希望应用程序返回true,如果登录用户具有管理员权限,尽管VS 2015以管理员身份运行或不运行..

I want to check whether logged in user have admin rights.
I am developing console application in ASP.NET 4.5.2, C#, Visual Studio 2015.

I log in as Domain user, having Admin rights.

What I have tried:

Tried several code samples available on google, but none seems to work. Below are couple of samples.

//Sample # 1

return WindowsIdentity.GetCurrent().Owner.IsWellKnown(WellknownSidType.BuiltinAdministratorsSid);

//Sample # 2
WindowsIdentity identity = WindowsIdentity.GetCurrent();
WindowsPrinciipal principal = new WindowsPrincipal(identity);
return princiapl.IsInRole(WindowsBuiltInRole.Administrator);

Above code returns true, only if Visual Studio 2015 is run as administrator else it will always return false.

I want application to return true, if logged in user have admin rights, despite of fact VS 2015 run as administrator or not..

推荐答案

我建​​议阅读:如何:在ASP.NET 2.0中使用Windows身份验证 [ ^ ]和:解释:ASP.NET中的Windows身份验证2.0 [ ^ ]
I'd suggest to read this: How To: Use Windows Authentication in ASP.NET 2.0[^] and this: Explained: Windows Authentication in ASP.NET 2.0[^]


这是我能找到的最简单的解决方案。

This is the simplest solution that I can find.
using System.DirectoryServices.AccountManagement; // in reference dll

public bool UserIsAdmin(string userSamAccountName, string adminSamAccountName)
{
 PrincipalContext context =  new PricipalContext(ContextType.Domain);
 GroupPrincipal adminGroup = new GroupPricipal(context, adminSamAccountName);
 UserPrincipal user = UserPrincipal.FindByIdentity(context, userSamAccountName);
 return user.IsMemberOf(adminGroup);
}





编辑:现在要小心,你不想留下域管理员组的samAccount名称如果它正面向互联网,则躺在服务器上。



now be carefull, you don't want to leave the samAccount name of your domain admin group just lying about on the server if it is facing the internet.


这篇关于检测C#中的管理员权限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆