如何从用户名和密码获取WindowsPrincipal

r2_*_*118 3 c# basic-authentication

我正在使用WebAPI并将其与Katana托管在一起。我现在正在编写一些用于身份验证和授权的中间件。我必须对SSL使用基本身份验证,因为请求可能来自各种平台。目前还不能选择OAuth。中间件需要使用基本身份验证提供的用户名和密码,并验证用户是否是本地Windows组的成员。

现在,我正在尝试弄清楚如何创建WindowsPrincipal。如果我能弄清楚如何使用用户名和密码创建WindowsPrincipal,那么我会做其余的事情。这就是我现在所拥有的。

    //TODO
    WindowsPrincipal userPrincipal = null; //This is where I need to take the username and password and create a WindowsPrincipal
    Thread.CurrentPrincipal = userPrincipal;

    AppDomain.CurrentDomain.SetPrincipalPolicy(System.Security.Principal.PrincipalPolicy.WindowsPrincipal);
    PrincipalPermission permission = new PrincipalPermission(null, "Local Group Name");
    permission.Demand();
Run Code Online (Sandbox Code Playgroud)

我正在努力寻找一种使用用户名和密码来验证该成员是否属于特定组的好方法。做这个的最好方式是什么?我在这里先向您的帮助表示感谢。

pys*_*o68 5

实际上,我认为您应该使用WindowsIdentity而不是WindowsPrincipal来获取该信息。

要获取/模拟用户,您必须从advapi32.dll p /调用LogonUser():

[DllImport("advapi32.dll", SetLastError = true)]
public static extern bool LogonUser(
        string lpszUsername,
        string lpszDomain,
        string lpszPassword,
        int dwLogonType,
        int dwLogonProvider,
        out IntPtr phToken);
Run Code Online (Sandbox Code Playgroud)

考虑到以上内容在“本机”类中,因此冒充用户的方法如下:

var userToken = IntPtr.Zero;

var success = Native.LogonUser(
  "username", 
  "domain", 
  "password", 
  2, // LOGON32_LOGON_INTERACTIVE
  0, // LOGON32_PROVIDER_DEFAULT
  out userToken);

if (!success)
{
  throw new SecurityException("User logon failed");
}

var identity = new WindowsIdentity(userToken);

if(identity.Groups.Any(x => x.Value == "Group ID")) 
{
    // seems to be in the group!
} 
Run Code Online (Sandbox Code Playgroud)

您可以在此处找到有关本机呼叫的其他信息:http : //msdn.microsoft.com/zh-cn/library/windows/desktop/aa378184%28v=vs.85%29.aspx