/// <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>empty credentials if target not found, else stored credentials</returns> public static NetworkCredential GetCredentials(string Target) { IntPtr nCredPtr; var username = String.Empty; var passwd = String.Empty; try { // Make the API call using the P/Invoke signature bool ret = NativeCode.CredRead(Target, NativeCode.CredentialType.Generic, 0, out nCredPtr); // If the API was successful then... if (ret) { using (CriticalCredentialHandle critCred = new CriticalCredentialHandle(nCredPtr)) { Credential cred = critCred.GetCredential(); passwd = cred.CredentialBlob; username = cred.UserName; } } } catch (Exception e) { log.error($"Could not get credentials for {Target}", e); } return new NetworkCredential(username, passwd, string.Empty); }
/// <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>empty credentials 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); // 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 code = NativeCode.CredUIParseUserName(user, userBuilder, int.MaxValue, domainBuilder, int.MaxValue); //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 (code == NativeCode.CredentialUIReturnCodes.InvalidAccountName) { userBuilder.Append(user); } username = userBuilder.ToString(); domain = domainBuilder.ToString(); } } return(new NetworkCredential(username, passwd, domain)); }