[英]What is the best way to get the current user's SID?
先决条件详细信息
问题
获取当前用户 SID 的最佳方法是什么? 我不是在谈论正在执行应用程序的身份,而是正在访问界面的用户。 在后台应用程序和基于桌面的应用程序中,这应该是实际执行应用程序的身份,但在 ASP.Net(没有模拟)中,这应该是 HttpContext.Current.User SID。
目前的方法
这就是我现在所拥有的。 只是好像……错了。 这很讨厌。 有没有更好的方法来做到这一点,或者有一些内置的 class 可以为您做到这一点?
public static SecurityIdentifier SID
{
get
{
WindowsIdentity identity = null;
if (HttpContext.Current == null)
{
identity = WindowsIdentity.GetCurrent();
}
else
{
identity = HttpContext.Current.User.Identity as WindowsIdentity;
}
return identity.User;
}
}
我不认为有更好的方法来获取这些信息 - 你必须以某种方式获得WindowsPrincipal和.NET相当干净的API摘要,这些信息在User对象后面。 我只是把它放在一个方法中,然后把它称为一天。
嗯,好吧,你应该做的一件事(除非你的网络用户总是成为WindowsIdentity),这将是检查空身份并根据你拥有的任何规则处理它。
WindowsIdentity类是“为您完成的内置类”。 只要你有一个有效的WindowsIdentity可以使用,你就可以得到一个简单的解决方案。
或者,如果您有相关用户的用户名并且希望直接从AD获取SID,则可以构建自己的库以使用DirectoryServices命名空间并为您的用户检索DirectoryEntry(这是一个相当复杂的过程,如DirectoryServices很棘手)。 如果有需要,您甚至可以使用LDAP来获取它。
不使用第三方库如果用户更改了用户名,则此代码将给出正确的结果。
String SID = "";
string currentUserName = System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString();
RegistryKey regDir = Registry.LocalMachine;
using (RegistryKey regKey = regDir.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Authentication\LogonUI\SessionData", true))
{
if (regKey != null)
{
string[] valueNames = regKey.GetSubKeyNames();
for (int i = 0; i < valueNames.Length; i++)
{
using (RegistryKey key = regKey.OpenSubKey(valueNames[i], true))
{
string[] names = key.GetValueNames();
for (int e = 0; e < names.Length; e++)
{
if (names[e] == "LoggedOnSAMUser")
{
if (key.GetValue(names[e]).ToString() == currentUserName)
SID = key.GetValue("LoggedOnUserSID").ToString();
}
}
}
}
}
}MessageBox.Show(SID);
//当前用户
WindowsIdentity.GetCurrent().Owner
以 SDDL 格式返回安全标识符 (SID),您知道它们是S-1-5-9 。
WindowsIdentity.GetCurrent().Owner.ToString()
返回帐户域安全标识符 (SID) 如果 SID 不代表 Windows 帐户 SID,则此属性返回 null
WindowsIdentity.GetCurrent().Owner.AccountDomainSid
您可以将其用作:
_pipeSecurity = new PipeSecurity();
var sid = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, WindowsIdentity.GetCurrent().Owner);
var audid = new PipeAuditRule(sid, PipeAccessRights.FullControl, AuditFlags.Failure | AuditFlags.Success);
var access = new PipeAccessRule(sid, PipeAccessRights.ReadWrite, AccessControlType.Allow);
_pipeSecurity.AddAuditRule(audid);
_pipeSecurity.AddAccessRule(access);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.