示例#1
0
        /// <summary>
        /// Enumerate the specified stored credentials in the Windows Credential store
        /// </summary>
        /// <param name="target">Name of the application or URL for which the credential is used</param>
        /// <returns>Return a <see cref="List{ICredential}"/> if success, null if target not found, throw if failed to read stored credentials</returns>
        public static List <ICredential> EnumerateICredentials(string target = null)
        {
            IntPtr pCredentials = IntPtr.Zero;
            uint   count        = 0;

            var success = NativeCode.CredEnumerate(target, 0, out count, out pCredentials);

            if (!success)
            {
                var lastError = Marshal.GetLastWin32Error();
                if (lastError == (int)NativeCode.CredentialUIReturnCodes.NotFound)
                {
                    return(null);
                }

                throw new CredentialAPIException($"Unable to Enumerate Credential store", "CredEnumerate", lastError);
            }

            List <NetworkCredential> networkCredentials = new List <NetworkCredential>();

            Credential[] credentials;

            try
            {
                using var criticalSection = new CriticalCredentialHandle(pCredentials);
                credentials = criticalSection.EnumerateCredentials(count);
            }
            catch (Exception)
            {
                return(null);
            }

            return(credentials.Select(c => c as ICredential).ToList());
        }
示例#2
0
        /// <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 ICredential if success, null if target not found, throw if failed to read stored credentials</returns>
        public static ICredential GetICredential(string target, CredentialType type = CredentialType.Generic)
        {
            IntPtr nCredPtr;

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

            if (!isSuccess)
            {
                var lastError = Marshal.GetLastWin32Error();
                if (lastError == (int)NativeCode.CredentialUIReturnCodes.NotFound)
                {
                    return(null);
                }
                throw new CredentialAPIException($"Unable to Read Credential", "CredRead", lastError);
            }

            try
            {
                using var critCred = new CriticalCredentialHandle(nCredPtr);
                Credential cred = critCred.GetCredential();
                return(cred);
            }
            catch (Exception)
            {
                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();

                    return(cred.ToNetworkCredential());
                }
            }
            catch (Exception)
            {
                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>
        /// <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);
            }
        }
        /// <summary>
        /// Enumerate the specified stored credentials in the Windows Credential store
        /// </summary>
        /// <param name="target">Name of the application or URL for which the credential is used</param>
        /// <returns>Return a <see cref="List{NetworkCredential}"/> if success, null if target not found, throw if failed to read stored credentials</returns>
        public static List <NetworkCredential> EnumerateCredentials(string target = null)
        {
            IntPtr pCredentials = IntPtr.Zero;
            uint   count        = 0;

            var success = NativeCode.CredEnumerate(target, 0, out count, out pCredentials);

            if (!success)
            {
                var lastError = Marshal.GetLastWin32Error();
                if (lastError == (int)NativeCode.CredentialUIReturnCodes.NotFound)
                {
                    return(null);
                }

                throw new Win32Exception(lastError,
                                         string.Format("'CredEnumerate' call throw an error (Error code: {0})", lastError));
            }

            List <NetworkCredential> networkCredentials = new List <NetworkCredential>();

            Credential[] credentials;

            try
            {
                using (var criticalSection = new CriticalCredentialHandle(pCredentials))
                {
                    credentials = criticalSection.EnumerateCredentials(count);
                }
            }
            catch (Exception)
            {
                return(null);
            }

            return(credentials.Select(c => c.ToNetworkCredential()).ToList());
        }
        /// <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)
        {
            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.Generic, 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 )
            {
                using ( CriticalCredentialHandle critCred = new CriticalCredentialHandle (nCredPtr) )
                {
                    Credential cred = critCred.GetCredential ();
                    passwd = cred.CredentialBlob;
                    var user = cred.UserName;
                    StringBuilder userBuilder = new StringBuilder ();
                    StringBuilder domainBuilder = new StringBuilder ();
                    var ret1 = NativeCode.CredUIParseUserName (user, userBuilder, int.MaxValue, domainBuilder, int.MaxValue);
                    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);
                }
            }
            return null;
        }