示例#1
0
        /// <summary>
        /// This fuction calls CredUIParseUserName() to parse the user name.
        /// </summary>
        /// <param name="username">The username name to pass.</param>
        /// <param name="user">The user part of the username.</param>
        /// <param name="domain">The domain part of the username.</param>
        /// <returns>Returns true if it successfully parsed the username.</returns>
        private static bool ParseUsername(string username, out string user, out string domain)
        {
            user   = string.Empty;
            domain = string.Empty;

            if (string.IsNullOrEmpty(username))
            {
                return(false);
            }

            bool successfullyParsed = true;

            StringBuilder strUser   = new StringBuilder(Convert.ToInt32(CredUI.CREDUI_MAX_USERNAME_LENGTH));
            StringBuilder strDomain = new StringBuilder(Convert.ToInt32(CredUI.CREDUI_MAX_DOMAIN_TARGET_LENGTH));

            // Call the OS API to do the parsing.
            CredUI.CredUIReturnCodes result = CredUI.CredUIParseUserName(username,
                                                                         strUser,
                                                                         CredUI.CREDUI_MAX_USERNAME_LENGTH,
                                                                         strDomain,
                                                                         CredUI.CREDUI_MAX_DOMAIN_TARGET_LENGTH);

            successfullyParsed = (result == CredUI.CredUIReturnCodes.NO_ERROR);

            if (successfullyParsed)
            {
                user   = strUser.ToString();
                domain = strDomain.ToString();
            }

            return(successfullyParsed);
        }
        protected override void ProcessRecord()
        {
            IntPtr credPtr;
            var    type = (CredUI.CredentialType)Enum.Parse(typeof(CredUI.CredentialType), Type);

            // Make the API call using the P/Invoke signature
            bool isSuccess = CredUI.CredRead(Target, type, 0, out credPtr);

            if (!isSuccess)
            {
                var lastError = Marshal.GetLastWin32Error();
                if (lastError == (int)CredUI.CredentialUIReturnCodes.NotFound)
                {
                    WriteObject(null);
                }
                else
                {
                    throw new Exception(String.Format("'CredRead' call throw an error (Error code: {0})", lastError));
                }
            }

            using (var critCred = new CredentialHandle(credPtr))
            {
                WriteObject(critCred.GetCredential());
            }
        }
 private void Init(CredUI.CredPackFlags flags, SafeCoTaskMemString pUserName, SafeCoTaskMemString pPassword)
 {
     if (!CredUI.CredPackAuthenticationBuffer(flags, (IntPtr)pUserName, (IntPtr)pPassword, IntPtr.Zero, ref bufferSize) && Marshal.GetLastWin32Error() == 122)             /*ERROR_INSUFFICIENT_BUFFER*/
     {
         buffer = Marshal.AllocCoTaskMem(bufferSize);
         if (!CredUI.CredPackAuthenticationBuffer(flags, (IntPtr)pUserName, (IntPtr)pPassword, buffer, ref bufferSize))
         {
             throw new Win32Exception();
         }
     }
     else
     {
         throw new Win32Exception();
     }
 }
        public void UnPack(bool decryptProtectedCredentials, out SecureString userName, out SecureString domainName, out SecureString password)
        {
            var pUserName      = new SafeCoTaskMemString(CredUI.CRED_MAX_USERNAME_LENGTH);
            var pDomainName    = new SafeCoTaskMemString(CredUI.CRED_MAX_USERNAME_LENGTH);
            var pPassword      = new SafeCoTaskMemString(CredUI.CREDUI_MAX_PASSWORD_LENGTH);
            int userNameSize   = pUserName.Size;
            int domainNameSize = pDomainName.Size;
            int passwordSize   = pPassword.Size;

            if (!CredUI.CredUnPackAuthenticationBuffer(decryptProtectedCredentials ? 0x1 : 0x0, buffer, bufferSize,
                                                       (IntPtr)pUserName, ref userNameSize, (IntPtr)pDomainName, ref domainNameSize, (IntPtr)pPassword, ref passwordSize))
            {
                throw new Win32Exception();
            }

            userName   = pUserName.DangerousGetHandle().ToSecureString();
            domainName = pDomainName.DangerousGetHandle().ToSecureString();
            password   = pPassword.DangerousGetHandle().ToSecureString();
        }
        public void UnPack(bool decryptProtectedCredentials, out string userName, out string domainName, out string password)
        {
            var pUserName      = new StringBuilder(CredUI.CRED_MAX_USERNAME_LENGTH);
            var pDomainName    = new StringBuilder(CredUI.CRED_MAX_USERNAME_LENGTH);
            var pPassword      = new StringBuilder(CredUI.CREDUI_MAX_PASSWORD_LENGTH);
            int userNameSize   = pUserName.Capacity;
            int domainNameSize = pDomainName.Capacity;
            int passwordSize   = pPassword.Capacity;

            if (!CredUI.CredUnPackAuthenticationBuffer(decryptProtectedCredentials ? 0x1 : 0x0, buffer, bufferSize,
                                                       pUserName, ref userNameSize, pDomainName, ref domainNameSize, pPassword, ref passwordSize))
            {
                throw new Win32Exception();
            }

            userName   = pUserName.ToString();
            domainName = pDomainName.ToString();
            password   = pPassword.ToString();
        }
示例#6
0
        /// <summary>
        /// This function calls the OS dialog to prompt user for credential.
        /// </summary>
        /// <param name="hwdOwner">The parent for the dialog.</param>
        /// <param name="targetUri">
        /// The credential target. It is displayed in the prompt dialog and is
        /// used for credential storage.
        /// </param>
        /// <param name="isWindowsAuthentication"></param>
        /// <param name="realm"></param>
        /// <param name="userName">The username supplied by the user.</param>
        /// <param name="password">The password supplied by the user.</param>
        /// <returns>
        /// DialogResult.OK = if Successfully prompted user for credentials.
        /// DialogResult.Cancel = if user cancelled the prompt dialog.
        /// </returns>
        private static DialogResult ShowOSCredentialDialog(IntPtr hwdOwner, Uri targetUri, bool isWindowsAuthentication, string realm, out string userName, out string password)
        {
            DialogResult retValue = DialogResult.Cancel;

            userName = string.Empty;
            password = string.Empty;

            string titleFormat = "Enter credentials...";
            string description = String.Format("Enter a user name and password with access to {0}", targetUri.GetLeftPart(UriPartial.Path));

            string target = targetUri.Host;

            // Create the CREDUI_INFO structure.
            CredUI.CREDUI_INFO info = new CredUI.CREDUI_INFO();
            info.pszCaptionText      = titleFormat;
            info.pszMessageText      = description;
            info.hwndParentCERParent = hwdOwner;
            info.hbmBannerCERHandle  = IntPtr.Zero;
            info.cbSize = Marshal.SizeOf(info);

            // We specify CRED_TYPE_SERVER_CREDENTIAL flag as the stored credentials appear in the
            // "Control Panel->Stored Usernames and Password". It is how IE stores and retrieve
            // credentials. By using the CRED_TYPE_SERVER_CREDENTIAL flag allows IE and VS to
            // share credentials.
            // We dont specify the CREDUI_FLAGS_EXPECT_CONFIRMATION as the VS proxy service consumers
            // dont call back into the service to confirm that the call succeeded.
            CredUI.CREDUI_FLAGS flags = CredUI.CREDUI_FLAGS.SERVER_CREDENTIAL |
                                        CredUI.CREDUI_FLAGS.GENERIC_CREDENTIALS |
                                        CredUI.CREDUI_FLAGS.ALWAYS_SHOW_UI |
                                        CredUI.CREDUI_FLAGS.SHOW_SAVE_CHECK_BOX |
                                        CredUI.CREDUI_FLAGS.EXCLUDE_CERTIFICATES;

            if (isWindowsAuthentication)
            {
                flags |= CredUI.CREDUI_FLAGS.COMPLETE_USERNAME;
            }

            StringBuilder user            = new StringBuilder(Convert.ToInt32(CredUI.CREDUI_MAX_USERNAME_LENGTH));
            StringBuilder pwd             = new StringBuilder(Convert.ToInt32(CredUI.CREDUI_MAX_PASSWORD_LENGTH));
            int           saveCredentials = 0;
            // Ensures that CredUPPromptForCredentials results in a prompt.
            int netError = CredUI.ERROR_LOGON_FAILURE;

            // Call the OS API to prompt for credentials.
            CredUI.CredUIReturnCodes result = CredUI.CredUIPromptForCredentials(
                info,
                target,
                IntPtr.Zero,
                netError,
                user,
                CredUI.CREDUI_MAX_USERNAME_LENGTH,
                pwd,
                CredUI.CREDUI_MAX_PASSWORD_LENGTH,
                ref saveCredentials,
                flags);


            if (result == CredUI.CredUIReturnCodes.NO_ERROR)
            {
                userName = user.ToString();
                password = pwd.ToString();

                retValue = DialogResult.OK;
            }
            else
            {
                Debug.Assert(result == CredUI.CredUIReturnCodes.ERROR_CANCELLED);
                retValue = DialogResult.Cancel;
            }

            return(retValue);
        }