Kirschi Kirschi - 1 month ago 25
C# Question

Retrieve Credentials from Windows Credentials Store using C#

I simply want to query the Credentials Store (or Vault as it is called in Win8) and get the login data. The MSDN is really unhelpful in this case and I also do not want any C++ pInvoke approaches.

I know that similar questions have been asked here a few times, but none of those solutions work in my case. I do not use Metro App programming so things like

are (as it looks) not available. I just create a simple C# WPF Desktop application.

Ideally it should work in several Windows versions, but Win8 is prefered.

More specifically I want to query the stored data from the CRM plugin for Outlook to automatically have my app log in to the CRM Server without having the User to ask for his Credentials. That means, if this is even possible...

So how do I access the Windows Credentials Store?


There is a Nuget library that I've been using called CredentialManagement

The usage is pretty simple. I wrapped it a little but probably didn't need to:

public static class CredentialUtil
    public static UserPass GetCredential(string target)
        var cm = new Credential {Target = target};
        if (!cm.Load())
            return null;

        //UserPass is just a class with two string properties for user and pass
        return new UserPass(cm.Username, cm.Password);

    public static bool SetCredentials(
         string target, string username, string password, PersistanceType persistenceType)
       return new Credential {Target = target, Username = username, 
               Password = password, PersistanceType =  PersistanceType.Enterprise}.Save();

    public static bool RemoveCredentials(string target)
        return new Credential { Target = target }.Delete();

Sample usage:

CredentialUtil.SetCredentials("FOO", "john", "1234", PersistanceType.LocalComputer);
var userpass = CredentialUtil.GetCredential("FOO");
Console.WriteLine($"User: {userpass.Username} Password: {userpass.Password}");
Debug.Assert(CredentialUtil.GetCredential("FOO") == null);

If you're interested in implementing it yourself, browse the source:

The trick is that there is no C# API into the Credential Manager. This library wraps the other .dll entry points nicely. :-)