如何在凭据对话框中显示域名(使用CredUIPromptForWindowsCredentials)?

时间:2019-11-25 06:54:21

标签: c# credentials windows-security

我使用CredUIPromptForWindowsCredentials来获取用户凭据,但是如果用户像这样 mydomain \ UserName UserName@mydomain.local 这样写登录名,则凭据对话框不会显示域名。如何在凭据对话框中显示域名,如图所示?

credential dialog picture

public static NetworkCredential ShowCredDialog(string caption, string message, NetworkCredential defaultCreds = null)
{
    var credui = new CREDUI_INFO
    {
        pszCaptionText = caption,
        pszMessageText = message,
    };
    credui.cbSize = Marshal.SizeOf(credui);

    uint authPackage = 0;
    var save = false;

    CreateInAuthBuffer(defaultCreds, out var inAuthBuffer, out var inAuthSize);

    var result = CredUIPromptForWindowsCredentials(
        ref credui,
        0,
        ref authPackage,
        inAuthBuffer,
        (uint)inAuthSize,
        out var outCredBuffer,
        out var outCredSize,
        ref save,
        1 /* Generic */);

    if (result != 0)
    {
        return null;
    }

    var maxUserName = 100;
    var maxDomain = 100;
    var maxPassword = 100;
    var usernameBuf = new StringBuilder(maxUserName);
    var domainBuf = new StringBuilder(maxDomain);
    var passwordBuf = new StringBuilder(maxPassword);

    var packAuthRes = CredUnPackAuthenticationBuffer(0, outCredBuffer, outCredSize,
        usernameBuf, ref maxUserName,
        domainBuf, ref maxDomain,
        passwordBuf, ref maxPassword);

    var userName = usernameBuf.ToString();
    var domain = domainBuf.ToString();
    var password = passwordBuf.ToString();

    CoTaskMemFree(outCredBuffer);

    return new NetworkCredential
    {
        UserName = userName,
        Domain = domain,
        Password = password,
    };
}

[DllImport("credui.dll", CharSet = CharSet.Auto)]
private static extern int CredUIPromptForWindowsCredentials(ref CREDUI_INFO notUsedHere,
    int authError,
    ref uint authPackage,
    IntPtr InAuthBuffer,
    uint InAuthBufferSize,
    out IntPtr refOutAuthBuffer,
    out uint refOutAuthBufferSize,
    ref bool fSave,
    int flags);

1 个答案:

答案 0 :(得分:0)

我需要更改参数: -在 CredUIPromptForWindowsCredentials 中将 dwFlags 设置为0x10 CREDUIWIN_AUTHPACKAGE_ONLY CredUIPromptForWindowsCredentials function disctiption -在 CredUnPackAuthenticationBuffer 中将 dwFlags 设置为0x01(解密)CredUnPackAuthenticationBuffer function disctiption

...
var result = CredUIPromptForWindowsCredentials(
                ref credui,
                0,
                ref authPackage,
                inAuthBuffer,
                (uint)inAuthSize,
                out var outCredBuffer,
                out var outCredSize,
                ref save,
                0x10/*CREDUIWIN_AUTHPACKAGE_ONLY*/);
...
var packAuthRes = CredUnPackAuthenticationBuffer(
                1, outCredBuffer, outCredSize,
                usernameBuf, ref maxUserName,
                domainBuf, ref maxDomain,
                passwordBuf, ref maxPassword);
...