(API version 4)
Below are examples of managing Passwords with Pleasant Password Server through a RESTful API. These have been accumulated over time in collaboration with our customers, and provided as a starting point.
The examples below are for API Version 4. Version 5 introduces some improvements.
Notes:
- This section is still in progress!
- These examples are provided as-is; if you do find an error or an improvement, please let us know so they can be updated.
Sections:
GET: https://server_name:port/api/v4/rest/credentialgroup/root
Returns: Id of Root Folder
POST: https://server_name:port/api/v4/rest/credentialgroup
Content:
{
Name: "API Folder",
ParentId: "<Parent Folder Id>",
}
Returns: Id of Created Folder
PUT: https://server_name:port/api/v4/rest/credentialgroup/Folder_Id
Content:
{
Id: "<Folder Id>",
Name: "New API Folder",
ParentId: "<Parent Folder Id>",
Notes: "It has notes now"
}
Returns: Nothing
POST: https://server_name:port/api/v4/rest/credential
Content:
{
Name: "API Credential",
GroupId: <Parent Folder Id>,
Username: "SteveCarlsberg",
Password: "12345"
}
Returns: Id of Created Entry
PUT: https://server_name:port/api/v4/rest/credential/Entry_Id
Content:
{
Id: "<Entry Id>",
Name: "API Credential Name Changed",
GroupId: "<Parent Folder ID>",
Username: "SteveCarlsberg",
Password: "678910"
}
People often like to use curl commands to execute API URL's, and so here are some brief setup and examples, which might get you started.
This provides an authentication, valid for a period of time, other
curl --insecure -X POST -H "Content-Type: application/x-www-form-urlencoded" -d "grant_type=password&username=admin&password=admin" https://localhost:10001/oauth2/token
Once you aquire an access token, a header parameter "Authorization" must be set to the authorization token for all subsequent API calls. See:
https://localhost:10001/api/v4/rest/credentialgroup/root
$PasswordServerURL = "https://
localhost
:10001"
$Cred = Get-Credential -Message "Enter your credentials to access Password Server"
$tokenParams = @
{ grant_type='password'; username=$Cred.UserName; password=$Cred.GetNetworkCredential().password;}
# Request a security token for the specified user that will be used to authenticate when requesting a password
$JSON = Invoke-WebRequest -Uri "$
PasswordServerURL
/OAuth2/Token" -Method POST -Body $tokenParams -ContentType "application/x-www-form-urlencoded"
# The RESTful API returns a JSON object. Convert that to a PowerShell object and extract just the access_token
$Token = (ConvertFrom-Json $JSON.Content).access_token
$headers = @
{ "Accept" = "application/json" "Authorization" = "$Token"}
$Credential = @
{ Id: "00000000-0000-0000-0000-000000000000", Name: "<name>", Username: "<username>", Password: "<password>", Url: "<url>", Notes: "<notes>", GroupId: "<Id of parent folder>", Created: "<current date/time in this format: 2015-06-01T13:26:12.336084-06:00>", Modified: "<current date/time in this format: 2015-06-01T13:26:12.336084-06:00>", Expires: null, UsageComment: null}
[string]$NewId = Invoke-WebRequest -Uri "$
PasswordServerURL
/api/v4/rest/credential" -Headers $headers -Method Post -Body $Credential
Get an Entry.
curl
--insecure
-i -X GET -H "Authorization: Bearer sfpiaufohdfhefohfopaoeff03988fahf......asfsdfosyfopafshf" -H "Content-Type: application/json" -H "Cache-Control: no-cache""https://
localhost:10001
/api/v4/rest/credential/
0e35bab3-4ef8-4947-9d61-cf17e15da0c7
"
Updating an Entry.
curl
--insecure
-i -X PUT -H "Authorization: Bearer sfpiaufohdfhefohfopaoeff03988fahf......asfsdfosyfopafshf" -H "Content-Type: application/json" -H "Cache-Control: no-cache" -d '{ "Id": "
0e35bab3-4ef8-4947-9d61-cf17e15da0c7",
"Name": "Test", "Username": "Testuser", "Password": "abcd123", "GroupId": "g998r9b9-b2cf-4ac1-8a33-5f5e43cd3eb0", "Notes": "Test Note"}' "https://
localhost:10001
/api/v4/rest/credential/
0e35bab3-4ef8-4947-9d61-cf17e15da0c7
"
API v5:
Instead use the Entry PATCH command in API v5, which allows update of a single field.
API v4:
{ "ID" = $CredentialID "password" = 'RestAPITest123' }
curl
--insecure
-i -X GET -H "Authorization: Bearer sfpiaufohdfhefohfopaoeff03988fahf......asfsdfosyfopafshf" -H "Content-Type: application/json" -H "Cache-Control: no-cache""https://
localhost:10001
/api/v4/rest/credential/
0e35bab3-4ef8-4947-9d61-cf17e15da0c7
"
https://
localhost:10001
/api/v4/rest/credential/EntryId
echo '{ Search : "prod_app_ceonline" }' | curl --insecure -d @ -H 'Authorization: <valid auth token here>' -H 'Content-Type: application/json' https://localhost:10001/api/v4/rest/search
Some of these scripts may require PowerShell version 5.
Also note, that PowerShell version 6, provides additional features, and function parameters that you may find helpful in your development environment, for example, using the -SkipCertificateCheck parameter mentioned below.
See Handling Trust Warnings (below) for more information.
Provided by: Andy Viar, Mary Greeley Medical Center. Used with permission.
# URL of Pleasant Password Server
$PasswordServerURL = "https://localhost:10001"
# Prompt for a credential
$Cred = Get-Credential -Message "Enter your credentials to access Pleasant Solutions Password Server" -UserName MyUserName
# Create OAuth2 token params
$tokenParams = @{
grant_type='password';
username=$Cred.UserName;
password=$Cred.GetNetworkCredential().password;}
# Authenticate to Pleasant Password Server
$JSON = Invoke-WebRequest -Uri "$PasswordServerURL/OAuth2/Token" -Method POST -Body $tokenParams -ContentType "application/x-www-form-urlencoded"
# Generate JSON token
$Token = (ConvertFrom-Json $JSON.Content).access_token
# Prep JSON headers
$headers = @{
"Accept" = "application/json"
"Authorization" = "$Token"
}
# Prep JSON body
$body = @{
"Id" = "00000000-0000-0000-0000-000000000000"
"Name" = "test-title"
"Password" = "test-password"
"Username" = "test-user"
"Url" = "test-url"
"Notes" = "test-notes"
"GroupId" = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
"Created" = "2018-01-22T12:00:00:00"
"Modified" = "2018-01-22T12:00:00:00"
}
# GroupId = The GUID of the folder this Credential belongs to
# Created = DateTimeOffset
# Modified = DateTimeOffset
# Execute command
$Results = Invoke-RestMethod -method post -Uri "$PasswordServerURL/api/v4/rest/credential" -body (ConvertTo-Json $body) -Headers $headers -ContentType 'application/json'
# Output results to the screen
ForEach($Result in $Results.credentials)
{
$Result
}
Provided by: Andy Viar, Mary Greeley Medical Center. Used with permission.
# URL of Pleasant Password Server
$PasswordServerURL = "https://localhost:10001"
# Prompt for a credential
$Cred = Get-Credential -Message "Enter your credentials to access Password Server" -UserName MyUserName
# Create OAuth2 token params
$tokenParams = @{
grant_type='password';
username=$Cred.UserName;
password=$Cred.GetNetworkCredential().password;}
# Authenticate to Pleasant Password Server
$JSON = Invoke-WebRequest -Uri "$PasswordServerURL/OAuth2/Token" -Method POST -Body $tokenParams -ContentType "application/x-www-form-urlencoded"
# Generate JSON token
$Token = (ConvertFrom-Json $JSON.Content).access_token
# Prep JSON headers
$headers = @{
"Accept" = "application/json"
"Authorization" = "$Token"
}
# Define job to focus on user input box
# Without this, the user must first manually click the input box
$null = [Reflection.Assembly]::LoadWithPartialName("Microsoft.VisualBasic")
$activateWindow = {
$null = [Reflection.Assembly]::LoadWithPartialName("Microsoft.VisualBasic")
$isWindowFound = $false
while(-not $isWindowFound) {
try {
[Microsoft.VisualBasic.Interaction]::AppActivate($args[0])
$isWindowFound = $true
}
catch {
sleep -Milliseconds 100
}
}
}
# Start job to focus on user input box
$job = Start-Job $activateWindow -ArgumentList "Output Password Info"
# Prompt for search credential
[void][Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic')
$title = 'Output Password Info'
$msg = 'Find display information for which user:'
$username = [Microsoft.VisualBasic.Interaction]::InputBox($msg, $title)
# Remove job to focus on user input box
Remove-Job $job -Force
# Prep JSON body
$body = @{
"search" = "$username"
}
# Execute command
$Results = Invoke-RestMethod -method post -Uri "$PasswordServerURL/api/v4/rest/search" -body (ConvertTo-Json $body) -Headers $headers -ContentType 'application/json'
# Output results to the screen
ForEach($Result in $Results.credentials)
{
$Result
$CredentialID = $Result.id
New-Object pscustomobject -Property @{'Name'=$Result.name;'Password' = (Invoke-WebRequest -Uri "$PasswordServerURL/api/v4/rest/credential/$CredentialID/password" -Headers $headers -Method Get)}
}
Provided by: Charles Delroy, SmartOdds. Used with permission.
# Generates the token for adding it to the database, where $PasswordServerURL is the URL of the Pleasant Server. Function GenerateKeepassToken { [System.Reflection.Assembly]::LoadWithPartialName(‘Microsoft.VisualBasic’) | Out-Null $Cred = Get-Credential -UserName XXXXXXXXX -Message “Enter your Credentials to access Password Server” $tokenParams = @ { grant_type=’password’; username=$Cred.UserName; password=$Cred.GetNetworkCredential().password; } $JSON = Invoke-WebRequest -Uri “$PasswordServerURL
/OAuth2/Token” -Method POST -Body $tokenParams -ContentType “application/x-www-form-urlencoded” -UseBasicParsing $Token = (ConvertFrom-Json $JSON.Content).access_token $Global:headers = @ { “Accept” = “application/json” “Authorization” = “$Token” } }# Inputs the created parameters (elsewhere in the script) and adds them into the database.
Function AddToKeePass {
$GroupID = $Global:GroupID
$date = [System.DateTimeOffset]::Now
$postParams = @
{Name=$Global:Description; Username=$Global:FirstName;Password=$Global:password;GroupId=$GroupID;Created="$Date";Modified="$Date"}
$JsonPOST = ConvertTo-Json -InputObject $postParams
$URI = " $PasswordServerURL/api/v4/rest/credential/"
Invoke-RestMethod -ContentType application/json -Method POST -Headers $Global:Headers -Uri $URI -Body $JsonPOST
}
You may receive a Certificate Trust error in your Development environment, due to only using the default placeholder Certificate. The FQDN will not match your server URL. So the recommendation for your Dev environment only, would be to either:
add-type @" using System.Net; using System.Security.Cryptography.X509Certificates; public class TrustAllCertsPolicy : ICertificatePolicy { public bool CheckValidationResult( ServicePoint srvPoint, X509Certificate certificate, WebRequest request, int certificateProblem) { return true; } } "@ $AllProtocols = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12' [System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols [System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy
Provided by: Florian Rossmark, Accriva Diagnostics. Linked with permission.
External Link:
Description:
One of the challenges in most daily IT operations is onboarding of workstations and servers (respective domain join). Over the years I came across and tried many ways to accomplish this. Today I wanted to share a script and solution others might find helpful, but first lets get down to some theory and background.
The Goals and Challenges:
1.) Simple domain join after a system was imaged
2.) Systems should have a local admin account ... with an individual password
The PowerShell script below will do the following for you:
1.) Prompt for system name
2.) Prompt for Password Server credentials
3.) Prompt for credentials to join the system to the domain
4.) Create a local admin user account
5.) Generate a password
6.) Check for an existing Entry in Password Server
7.) Otherwise, create a new entry with:
machine name, username, password, manufacturer, model, serial number / service tag,
UEFI BIOS Windows license key, MAC addresses of all network cards Windows knows about
8.) Join the domain putting the system into the defined AD/LDAP OU
Simple script for creating a new random string.
External Link:
Provided by: Florian Rossmark, Accriva Diagnostics. Linked with permission.
Provided by: Justin Harris, Capture Technologie-PC911. Used with permission.
A simple class in Python to access the API with a method that gets an authorization token and another to get a password.
from urllib import request import json class PPS: def _init_(self, host='https://localhost:1001'): self.host = host self.token = None self.auth_header = None def get_token(self, user, passwd): url = f' {self.host}/oauth2/token' headers = {'Content-Type': 'application/x-www-form-urlencoded'} data = f'grant_type=password&username={user}&password={passwd}' req = request.Request(url, data.encode(), headers) res = request.urlopen(req) self.token = json.loads(res.readlines()[0].decode())['access_token'] self.auth_header = {'Authorization': f'Bearer {self.token}'} def get_credential(self, id): url = f'{self.host} /api/v4/rest/credential/ {id} /password' headers = {**self.auth_header, 'Content-Type': 'application/json', 'Cache-Control': 'no-cache'} req = request.Request(url, None, headers) res = request.urlopen(req).readlines()[0].decode().strip('"') return res