Store passwords securely on Windows with the Credential Manager

Many applications need to remember a password, an API token or some other secret between launches. Writing these into a preferences file or a database field is not a good idea. On macOS you have the keychain, and with our KeychainMBS class you can use it from Xojo for a long time already. For Windows we now added the matching functionality: in version 26.5 of the MBS Xojo Plugins you find the new WindowsCredentialsMBS module together with the WindowsCredentialMBS and WindowsCredentialAttributeMBS classes in the MBS Xojo Win Plugin.

These give you access to the Windows Credential Manager, the secure store Windows uses for its own saved passwords. You can see the entries in the Control Panel under Credential Manager (“Windows Credentials”). The functions work in Desktop, Console and Web applications on Windows. For Web you can only access credentials on the server side.

The building blocks

  • WindowsCredentialsMBS is a module with the functions to work with the store: Write, Read, Delete, List, FindBestCredential and GetSessionTypes. If something fails, check the LastError and LastErrorMessage properties.
  • WindowsCredentialMBS holds the values for one credential: the TargetName, the UserName, the secret in CredentialBlob, a Comment, the Type, the Persist mode, some Flags and the LastWritten date.
  • WindowsCredentialAttributeMBS is an optional keyword-value pair you can attach to a credential to store extra information your application defines.

Write a credential

To store a secret, create a new WindowsCredentialMBS object, fill in the properties and pass it to Write:

// write a sample credential
Var c As New WindowsCredentialMBS
c.Comment = "Xojo test"
c.TargetName = "MyApp_Login"
c.UserName = "John"
c.CredentialBlob = "Secret"
c.Type = c.TypeGeneric
c.Persist = c.PersistLocalMachine

If WindowsCredentialsMBS.Write(c) Then
  MessageBox "saved"
Else
  MessageBox WindowsCredentialsMBS.LastErrorMessage
End If

The TargetName together with the Type identifies the credential. If you write again with the same name and type, the existing entry is updated. For your own application you normally use TypeGeneric. Microsoft recommends to prefix the target name with your company or application name, so it does not clash with other software.

For TypeGeneric the content of CredentialBlob is up to you. It’s a MemoryBlock, so you can store text or binary data. Just make sure you read it back the same way you wrote it. If another application reads the same entry, you need to match its format. For example to store a password for a FileMaker database, you would use UTF-16 text:

// Write a password for a FileMaker database
Var c As New WindowsCredentialMBS
c.Type = WindowsCredentialMBS.TypeGeneric
c.Persist = WindowsCredentialMBS.PersistLocalMachine
c.TargetName = "FMP: Assets"
c.UserName = "Admin"
c.Comment = "FileMaker Pro password"
c.CredentialBlob = ConvertEncoding("test", Encodings.UTF16)

Var r As Boolean = WindowsCredentialsMBS.Write(c)
If r Then
  MessageBox "Password saved"
Else
  MessageBox WindowsCredentialsMBS.LastErrorMessage
End If

If you want to update the other fields of an existing credential without touching the stored secret, pass WindowsCredentialsMBS.FlagsPreserveCredentialBlob as flags to Write.

Choose the persistence

The Persist property decides how long and where the credential lives:

Constant Meaning
PersistSession Lives only for the current logon session. Gone after the user logs off.
PersistLocalMachine Stays on this computer for all future logon sessions of this user.
PersistEnterprise Like local machine, but also roams to other computers if the user has a roaming profile.

Not every logon session allows every level. With GetSessionTypes you can query the maximum persistence supported for each credential type:

Var values() As Integer = WindowsCredentialsMBS.GetSessionTypes

If values = Nil Then
  MessageBox WindowsCredentialsMBS.LastErrorMessage
Else
  Var value As Integer = values(WindowsCredentialMBS.TypeGeneric)
  Select Case value
  Case WindowsCredentialMBS.PersistEnterprise
    MessageBox "We can store generic credentials with enterprise persistence." // highest level
  Case WindowsCredentialMBS.PersistLocalMachine
    MessageBox "We can store generic credentials on local machine."
  Case WindowsCredentialMBS.PersistSession
    MessageBox "We can store generic credentials in session."
  End Select
End If

Read a credential

To get your secret back, call Read with the target name. The type defaults to TypeGeneric. You get back a WindowsCredentialMBS object, or nil if the entry was not found or another error happened:

Var credential As WindowsCredentialMBS = WindowsCredentialsMBS.Read("MyApp_Login")

If credential = Nil Then
  If WindowsCredentialsMBS.LastError = WindowsCredentialsMBS.ErrorNotFound Then
    MessageBox "No password saved yet."
  Else
    MessageBox WindowsCredentialsMBS.LastErrorMessage
  End If
Else
  Var password As String = credential.CredentialBlob
  MessageBox credential.TargetName + EndOfLine + credential.UserName + EndOfLine + password
End If

Please note that TargetName is case-insensitive. And for the domain types (TypeDomainPassword, TypeDomainCertificate) the secret can only be read by the Windows authentication packages, not by your application.

List credentials

The List function enumerates the credentials of the current user. Pass a filter with a name prefix followed by an asterisk to only get your own entries, e.g. “MyApp*”. Without filter you get all of them:

Var credentials() As WindowsCredentialMBS = WindowsCredentialsMBS.List("MyApp*")

If credentials = Nil Then
  MessageBox WindowsCredentialsMBS.LastErrorMessage
Else
  For Each credential As WindowsCredentialMBS In credentials
    MessageBox credential.TargetName + EndOfLine + credential.Comment + EndOfLine + credential.UserName
  Next
End If

If you don’t know the exact name, FindBestCredential searches the generic credentials of the current logon session for the one that best matches a given target name.

Delete a credential

When the user logs out of your service or wants the application to forget the password, call Delete with the target name and type:

// delete a password for a FileMaker database
Var type As Integer = WindowsCredentialMBS.TypeGeneric
Var r As Boolean = WindowsCredentialsMBS.Delete("FMP: Assets", type)

If r Then
  MessageBox "deleted"
Else
  MessageBox WindowsCredentialsMBS.LastErrorMessage
End If

Attributes for extra data

Sometimes you want to store a few more values with the credential, like an account ID or a server URL. For this each credential can have attributes. An attribute has a Keyword and a Value as MemoryBlock. For text you can simply use the Text property, which reads and writes the value as Unicode string. Microsoft suggests keywords in the form CompanyName_Name, up to 256 characters.

Call CredentialAttributes to get the array and add your attributes to it before you write:

Var c As New WindowsCredentialMBS
c.Comment = "Xojo test"
c.TargetName = "MyApp_Login"
c.UserName = "John"
c.CredentialBlob = "Secret"
c.Type = c.TypeGeneric
c.Persist = c.PersistLocalMachine

Var attr As New WindowsCredentialAttributeMBS
attr.Keyword = "id"
attr.Text = "1234"

Var attrs() As WindowsCredentialAttributeMBS = c.CredentialAttributes
attrs.Add attr

If WindowsCredentialsMBS.Write(c) Then
  MessageBox "saved"
Else
  MessageBox WindowsCredentialsMBS.LastErrorMessage
End If

When you read the credential later, AttributeCount tells you how many attributes are there and CredentialAttributes returns them. (The method is named CredentialAttributes because Xojo doesn’t allow a method named Attributes.)

Error handling

All functions set the LastError and LastErrorMessage properties of the module. Functions returning an object or array return nil on failure, and Write and Delete return false. The module has constants for the common error codes, e.g. ErrorNotFound if no credential exists with the given name, ErrorBadUserName for an invalid user name, or ErrorInvalidParameter if you try to change a protected field of an existing credential. For certificate credentials you may also see the smart card errors like ErrorSCardNoSmartCard or ErrorSCardWrongCHV.

Cross-platform

If your application runs on both platforms, use KeychainMBS on macOS and the new WindowsCredentialsMBS module on Windows, and wrap both in a small class with Save/Load/Delete methods. That way the rest of your code doesn’t need to know where the secret is stored.

The new classes are included in the MBS Xojo Win Plugin in version 26.5. Please try them and let us know how they work for you.

1 Like