Beispiel #1
0
        internal static void GetCredentialsVistaAndUp(string ServerName, string DisplayMessage, out NetworkCredential networkCredential)
        {
            CREDUI_INFO credui = new CREDUI_INFO();

            credui.pszCaptionText = "Please enter the credentials for " + ServerName;
            credui.pszMessageText = DisplayMessage;
            credui.cbSize         = Marshal.SizeOf(credui);
            uint            authPackage   = 0;
            IntPtr          outCredBuffer = new IntPtr();
            uint            outCredSize;
            bool            save   = false;
            CREDUIWIN_FLAGS flags  = CREDUIWIN_FLAGS.GENERIC;
            int             result = CredUIPromptForWindowsCredentials(ref credui,
                                                                       0,
                                                                       ref authPackage,
                                                                       IntPtr.Zero,
                                                                       0,
                                                                       out outCredBuffer,
                                                                       out outCredSize,
                                                                       ref save,
                                                                       (int)flags);

            var usernameBuf = new StringBuilder(100);
            var passwordBuf = new StringBuilder(100);
            var domainBuf   = new StringBuilder(100);

            int maxUserName = 100;
            int maxDomain   = 100;
            int maxPassword = 100;

            if (result == 0)
            {
                if (CredUnPackAuthenticationBuffer(0, outCredBuffer, outCredSize, usernameBuf, ref maxUserName,
                                                   domainBuf, ref maxDomain, passwordBuf, ref maxPassword))
                {
                    //TODO: ms documentation says we should call this but i can't get it to work
                    //SecureZeroMem(outCredBuffer, outCredSize);

                    //clear the memory allocated by CredUIPromptForWindowsCredentials
                    CoTaskMemFree(outCredBuffer);
                    networkCredential = new NetworkCredential()
                    {
                        UserName = usernameBuf.ToString(),
                        Password = passwordBuf.ToString(),
                        Domain   = domainBuf.ToString()
                    };
                    return;
                }
            }

            networkCredential = null;
        }
        private static extern int CredUIPromptForWindowsCredentials(
			ref CREDUI_INFO notUsedHere,
			int authError,
			ref int authPackage,
			IntPtr InAuthBuffer,
			int InAuthBufferSize,
			out IntPtr refOutAuthBuffer,
			out int refOutAuthBufferSize,
			[MarshalAs(UnmanagedType.Bool)] ref bool fSave,
			CREDUIWIN_FLAGS flags);