簡體   English   中英

如何從用戶名和密碼獲取WindowsPrincipal

[英]How to get WindowsPrincipal from username and password

我正在使用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();

我正在努力尋找一種使用用戶名和密碼驗證該成員是特定組的一部分的好方法。 做這個的最好方式是什么? 我在這里先向您的幫助表示感謝。

實際上我認為您應該使用WindowsIdentity而不是WindowsPrincipal來獲取該信息。

要獲取/模擬用戶,您必須從advapi32.dll調用LogonUser():

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

考慮到上述內容屬於“Native”類,冒充用戶將如下:

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!
} 

您可以在此處找到有關本機調用的其他信息: http//msdn.microsoft.com/en-us/library/windows/desktop/aa378184%28v=vs.85%29.aspx

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM