public NetworkCredential ToNetworkCredential()
        {
            if (!string.IsNullOrEmpty(UserName))
            {
                var userBuilder   = new StringBuilder(UserName.Length + 2);
                var domainBuilder = new StringBuilder(UserName.Length + 2);

                var returnCode = NativeCode.CredUIParseUserName(UserName, userBuilder, userBuilder.Capacity, domainBuilder, domainBuilder.Capacity);
                var lastError  = Marshal.GetLastWin32Error();

                //assuming invalid account name to be not meeting condition for CredUIParseUserName
                //"The name must be in UPN or down-level format, or a certificate"
                if (returnCode == NativeCode.CredentialUIReturnCodes.InvalidAccountName)
                {
                    userBuilder.Append(UserName);
                }
                else if (returnCode != 0)
                {
                    throw new CredentialAPIException($"Unable to Parse UserName", "CredUIParseUserName", lastError);
                }

                return(new NetworkCredential(userBuilder.ToString(), this.CredentialBlob, domainBuilder.ToString()));
            }
            else
            {
                return(new NetworkCredential(UserName, this.CredentialBlob));
            }
        }
        /// <summary>
        /// Extract the stored credential from Windows Credential store
        /// </summary>
        /// <param name="Target">Name of the application/Url where the credential is used for</param>
        /// <returns>null if target not found, else stored credentials</returns>
        public static NetworkCredential GetCredentials(string Target, CredentialType type = CredentialType.Generic)
        {
            IntPtr nCredPtr;
            var    username = String.Empty;
            var    passwd   = String.Empty;
            var    domain   = String.Empty;

            // Make the API call using the P/Invoke signature

            bool ret       = NativeCode.CredRead(Target, (NativeCode.CredentialType)type, 0, out nCredPtr);
            int  lastError = Marshal.GetLastWin32Error();

            if (!ret)
            {
                throw new Win32Exception(lastError, "CredDelete throw an error");
            }
            // If the API was successful then...
            if (ret)
            {
                try
                {
                    using (CriticalCredentialHandle critCred = new CriticalCredentialHandle(nCredPtr))
                    {
                        Credential cred = critCred.GetCredential();
                        passwd = cred.CredentialBlob;
                        if (!String.IsNullOrEmpty(cred.UserName))
                        {
                            var           user          = cred.UserName;
                            StringBuilder userBuilder   = new StringBuilder(cred.UserName.Length + 2);
                            StringBuilder domainBuilder = new StringBuilder(cred.UserName.Length + 2);

                            var ret1 = NativeCode.CredUIParseUserName(user, userBuilder, userBuilder.Capacity, domainBuilder, domainBuilder.Capacity);
                            lastError = Marshal.GetLastWin32Error();

                            //assuming invalid account name to be not meeting condition for CredUIParseUserName
                            //"The name must be in UPN or down-level format, or a certificate"
                            if (ret1 == NativeCode.CredentialUIReturnCodes.InvalidAccountName)
                            {
                                userBuilder.Append(user);
                            }
                            else if ((uint)ret1 > 0)
                            {
                                throw new Win32Exception(lastError, "CredUIParseUserName throw an error");
                            }

                            username = userBuilder.ToString();
                            domain   = domainBuilder.ToString();
                        }
                        return(new NetworkCredential(username, passwd, domain));
                    }
                }
                catch (Exception e)
                {
                    return(null);
                }
            }
            return(null);
        }
        /// <summary>
        /// Extract the stored credential from Windows Credential store
        /// </summary>
        /// <param name="target">Name of the application/Url where the credential is used for</param>
        /// <param name="type">Credential type</param>
        /// <returns>return the credentials if success, null if target not found, throw if failed to read stored credentials</returns>
        public static NetworkCredential GetCredentials(string target, CredentialType type = CredentialType.Generic)
        {
            IntPtr nCredPtr;
            var    username = String.Empty;
            var    passwd   = String.Empty;
            var    domain   = String.Empty;

            // Make the API call using the P/Invoke signature
            bool isSuccess = NativeCode.CredRead(target, (NativeCode.CredentialType)type, 0, out nCredPtr);

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

            try
            {
                using (var critCred = new CriticalCredentialHandle(nCredPtr))
                {
                    Credential cred = critCred.GetCredential();
                    passwd = cred.CredentialBlob;
                    if (!String.IsNullOrEmpty(cred.UserName))
                    {
                        var           user          = cred.UserName;
                        StringBuilder userBuilder   = new StringBuilder(cred.UserName.Length + 2);
                        StringBuilder domainBuilder = new StringBuilder(cred.UserName.Length + 2);

                        var returnCode = NativeCode.CredUIParseUserName(user, userBuilder, userBuilder.Capacity, domainBuilder, domainBuilder.Capacity);
                        var lastError  = Marshal.GetLastWin32Error();

                        //assuming invalid account name to be not meeting condition for CredUIParseUserName
                        //"The name must be in UPN or down-level format, or a certificate"
                        if (returnCode == NativeCode.CredentialUIReturnCodes.InvalidAccountName)
                        {
                            userBuilder.Append(user);
                        }
                        else if (returnCode != 0)
                        {
                            throw new Win32Exception(lastError, String.Format("CredUIParseUserName throw an error (Error code: {0})", lastError));
                        }

                        username = userBuilder.ToString();
                        domain   = domainBuilder.ToString();
                    }
                    return(new NetworkCredential(username, passwd, domain));
                }
            }
            catch (Exception)
            {
                return(null);
            }
        }
Exemple #4
0
        internal static bool ParseUserName(string usernameBuf, int maxUserName, int maxDomain, out string user, out string domain)
        {
            var userBuilder   = new StringBuilder(maxUserName);
            var domainBuilder = new StringBuilder(maxDomain);

            user   = String.Empty;
            domain = String.Empty;

            var returnCode = NativeCode.CredUIParseUserName(usernameBuf, userBuilder, maxUserName, domainBuilder, maxDomain);

            Debug.WriteLine(returnCode);
            switch (returnCode)
            {
            case NativeCode.CredentialUIReturnCodes.Success:     // The username is valid.
                user   = userBuilder.ToString();
                domain = domainBuilder.ToString();
                return(true);
            }
            return(false);
        }
        /// <summary>
        /// Accepts credentials in a console window
        /// </summary>
        /// <param name="Target">A descriptive text for where teh credentials being asked are used for</param>
        /// <returns>NetworkCredential object containing the user name, </returns>
        public static NetworkCredential PromptForCredentialsConsole(string target)
        {
            var user     = String.Empty;
            var password = String.Empty;
            var domain   = String.Empty;

            // Setup the flags and variables
            StringBuilder userPassword = new StringBuilder(), userID = new StringBuilder();
            bool          save = true;

            NativeCode.CredentialUIFlags flags = NativeCode.CredentialUIFlags.CompleteUsername | NativeCode.CredentialUIFlags.ExcludeCertificates | NativeCode.CredentialUIFlags.GenericCredentials;

            // Prompt the user
            NativeCode.CredentialUIReturnCodes returnCode = NativeCode.CredUICmdLinePromptForCredentials(target, IntPtr.Zero, 0, userID, 100, userPassword, 100, ref save, flags);

            password = userPassword.ToString();

            StringBuilder userBuilder   = new StringBuilder();
            StringBuilder domainBuilder = new StringBuilder();

            returnCode = NativeCode.CredUIParseUserName(userID.ToString(), userBuilder, int.MaxValue, domainBuilder, int.MaxValue);
            switch (returnCode)
            {
            case NativeCode.CredentialUIReturnCodes.Success:     // The username is valid.
                user   = userBuilder.ToString();
                domain = domainBuilder.ToString();
                break;

            case NativeCode.CredentialUIReturnCodes.InvalidAccountName:     // The username is not valid.
                user   = userID.ToString();
                domain = null;
                break;

            case NativeCode.CredentialUIReturnCodes.InsufficientBuffer:     // One of the buffers is too small.
                throw new OutOfMemoryException();

            case NativeCode.CredentialUIReturnCodes.InvalidParameter:     // ulUserMaxChars or ulDomainMaxChars is zero OR userName, user, or domain is NULL.
                throw new ArgumentNullException("userName");
            }
            return(new NetworkCredential(user, password, domain));
        }
Exemple #6
0
        internal static NetworkCredential ToNetworkCredential(this Credential cred)
        {
            if (cred == null)
            {
                return(null);
            }

            string username = string.Empty;
            string domain   = string.Empty;

            var passwd = cred.CredentialBlob;

            if (!string.IsNullOrEmpty(cred.UserName))
            {
                var user          = cred.UserName;
                var userBuilder   = new StringBuilder(cred.UserName.Length + 2);
                var domainBuilder = new StringBuilder(cred.UserName.Length + 2);

                var returnCode = NativeCode.CredUIParseUserName(user, userBuilder, userBuilder.Capacity, domainBuilder, domainBuilder.Capacity);
                var lastError  = Marshal.GetLastWin32Error();

                //assuming invalid account name to be not meeting condition for CredUIParseUserName
                //"The name must be in UPN or down-level format, or a certificate"
                if (returnCode == NativeCode.CredentialUIReturnCodes.InvalidAccountName)
                {
                    userBuilder.Append(user);
                }
                else if (returnCode != 0)
                {
                    throw new Win32Exception(lastError, String.Format("CredUIParseUserName throw an error (Error code: {0})", lastError));
                }

                username = userBuilder.ToString();
                domain   = domainBuilder.ToString();
            }
            return(new NetworkCredential(username, passwd, domain));
        }