Caching Credentials Using JSON

When you need to cache logon credentials to a file, this is typically done by piping the credential to Export-Clixml which produces a rather lengthy XML file. With Import-Clixml, the cached credential can then be imported back into a script whenever you need it. PowerShell automatically uses the user and machine identity to encrypt the password (and it can only be read back by the same person on the same machine).

The same can be done in JSON format as well which produces less cluttered files. Just the password encryption part needs to be done manually.

This example prompts for logon credentials, then saves them to a “mycred.json” file on your desktop, and opens the file in the Notepad so you can view the content and make sure the password was encrypted:

$path = "$home\Desktop\mycred.json"

$cred = Get-Credential
$cred | 
  Select Username,@{n="Password"; e={$_.password | ConvertFrom-SecureString}} |
  ConvertTo-Json |
  Set-Content -Path $path -Encoding UTF8


notepad.exe $path 

To later reuse the file and import the credential, use this:
$path = "$home\Desktop\mycred.json"

$o = Get-Content -Path $path -Encoding UTF8 -Raw | ConvertFrom-Json 
$cred = New-Object -TypeName PSCredential $o.UserName, 
  ($o.Password | ConvertTo-SecureString)

# if you entered a valid user credentials, this line
# will start Notepad using the credentials retrieved from 
# the JSON file to prove that the credentials are
# working. 
Start-Process notepad -Credential $cred

To later reuse the file and import the credential, use this:

$path = "$home\Desktop\mycred.json"

$o = Get-Content -Path $path -Encoding UTF8 -Raw | ConvertFrom-Json 
$cred = New-Object -TypeName PSCredential $o.UserName, 
  ($o.Password | ConvertTo-SecureString)

# if you entered a valid user credentials, this line
# will start Notepad using the credentials retrieved from 
# the JSON file to prove that the credentials are
# working. 
Start-Process notepad -Credential $cred

Note that this example will use the credential stored in the JSON file to launch an instance of Notepad under these user credentials. This obviously fails if you entered invalid logon information when you created the JSON file in the first example script.

Note also that the password will be saved encrypted, using your user account and your machine as secrets. So the saved password is securely encrypted, but the technique shown here is only suitable for tasks where the same person (on the same machine) wants to later reuse the saved credential. One use case would be to save credentials for scripts you run frequently on your own machine.

Twitter This Tip! ReTweet this Tip!