在 C# 中获取 NT 身份验证的用户名






4.80/5 (29投票s)
2002 年 5 月 20 日
2分钟阅读

514098

2701
通过 .NET Framework,您可以轻松获取当前用户名进行身份验证。
引言
我们部门最近开始将我们所有的客户端/服务器应用程序通过 Active Directory 迁移到 Windows NT 身份验证。 我们之前的应用程序为每个用户使用 SQL Server 登录名。 当为公司范围内的应用程序设置用户时,这会变得非常乏味。 在没有对用户进行身份验证的情况下,也存在固有的安全风险。 我想分享以下有关 .NET 中安全性的代码,希望它能帮助其他人。我们的应用程序是用 Visual Basic 完成的,所以我们当然需要调用 Windows API,我们在其中定义了以下函数
旧的 VB6 Windows API 方法调用
Declare Function GetUserName Lib "advapi32.dll" Alias _
"GetUserNameA" (ByVal lpBuffer As String, nSize As Long) As Long
这并不难,但我最近一直在使用 C#,我想知道如何在托管代码中做到这一点。
我的第一个想法是导入上面提到的 advapi32.dll
以及我们将用于获取用户名的方法。 Code Project 上有很多其他示例,用户通过现有的 .dll
导入了方法,所以希望其中一些内容看起来很熟悉。 我试图记录这里发生的事情,即使它相当简单。 以下代码还需要您添加 using 语句。
可能的新 C# 托管方法
//====================================================
//Include at the top, above the namespace declaration.
using System.Runtime.InteropServices;
//=====================================================
//Defines the .dll file to import as well as the method
//to use.
[DllImport("Advapi32.dll", EntryPoint="GetUserName",
ExactSpelling=false, SetLastError=true)]
//====================================================
//This specifies the exact method we are going to call
//from within our imported .dll
static extern bool GetUserName(
[MarshalAs(UnmanagedType.LPArray)] byte[] lpBuffer,
[MarshalAs(UnmanagedType.LPArray)] Int32[] nSize );
//===================================================
//The following is the implementation of our imported
//method.
byte[] str=new byte[256];
Int32[] len=new Int32[1];
len[0]=256;
GetUserName(str,len);
MessageBox.Show(System.Text.Encoding.ASCII.GetString(str));
我最初认为的快速解决方案实际上让我更加深入地思考了最初的问题。 必须有一种比调用旧的 Windows API 更好的方法来获取用户名。 经过一番研究,我得出的结论是,微软的家伙们确实设法将它无缝地包含到了 .NET Framework 中。 当我发现它非常简单时,我感到非常震惊。 您只需要以下内容
最合理的 C# 方法
//=======================================================
//Place this at the top, above your namespace declaration
using System.Security.Principal;
//=======================================================
//In a specific event, place the following.
string a;
a = System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString();
MessageBox.Show(a.ToString());
System.Security.Principal.WindowsIdentity.GetCurrent()
部分向我们开放的不仅仅是当前用户。 查找时,您会在此 .NET Framework 部分中找到以下其他方法/属性AuthenticationType
- 获取用于验证用户的身份验证类型。Impersonates
- 模拟对象表示的用户。IsAnonymous
- 指示系统是否将用户帐户识别为匿名帐户。IsAuthenticated
- 确定用户是否已通过 Windows 身份验证。IsGuest
- 指示系统是否将帐户定义为来宾帐户。IsSystem
- 指示系统是否将帐户定义为系统帐户。
.dll
的任何丑陋的导入。 希望这对某人有帮助,我发现它非常有趣。