Last active
August 29, 2015 14:06
-
-
Save jiulongw/30567a899259bbee2ba8 to your computer and use it in GitHub Desktop.
Prompt user for name and password with windows cred API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private static NetworkCredential PromptForUserCredentials(string preferredUserName, Uri serverUri) | |
{ | |
Unmanaged.CREDUI_INFO uiInfo = new Unmanaged.CREDUI_INFO() | |
{ | |
cbSize = Marshal.SizeOf(typeof(Unmanaged.CREDUI_INFO)), | |
pszCaptionText = serverUri.Host, | |
pszMessageText = string.Format(Resources.DeployWebResources_CredentialPromptMessage, serverUri.Host) | |
}; | |
uint autoPackage = 0; | |
IntPtr outCredBuffer; | |
uint outCredSize; | |
bool save = false; | |
int CREDUIWIN_AUTHPACKAGE_ONLY = 0x10; | |
uint CRED_PACK_PROTECTED_CREDENTIALS = 0x1; | |
uint ret = Unmanaged.CredUIPromptForWindowsCredentials(ref uiInfo, 0, ref autoPackage, IntPtr.Zero, 0, out outCredBuffer, out outCredSize, ref save, CREDUIWIN_AUTHPACKAGE_ONLY); | |
if (ret == 0) | |
{ | |
// todo: call two times without hard-code value. | |
StringBuilder userName = new StringBuilder(256); | |
uint cchUserName = 256; | |
StringBuilder password = new StringBuilder(256); | |
uint cchPassword = 256; | |
StringBuilder domain = new StringBuilder(256); | |
uint cchDomain = 256; | |
ret = Unmanaged.CredUnPackAuthenticationBuffer(CRED_PACK_PROTECTED_CREDENTIALS, outCredBuffer, outCredSize, userName, ref cchUserName, domain, ref cchDomain, password, ref cchPassword); | |
if (ret != 0) | |
{ | |
userName.Length = (int)cchUserName; | |
password.Length = (int)cchPassword; | |
domain.Length = (int)cchDomain; | |
return new NetworkCredential(userName.ToString(), password.ToString(), domain.ToString()); | |
} | |
} | |
return null; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment