Authenticating to the Keyfactor API
When you make a connection to the Keyfactor API An API is a set of functions to allow creation of applications. Keyfactor offers the Keyfactor API, which allows third-party software to integrate with the advanced certificate enrollment and management features of Keyfactor Command., authentication is required.
Authentication using Active Directory as an Identity Provider
If you’re using Active Directory as an identity provider, you have the choice to authenticate to Keyfactor Command using Basic authentication or Windows integrated authentication. Any users who have already authenticated to Keyfactor Command before opening the Keyfactor API Reference and Utility (Swagger) in the same browser session will be seamlessly authenticated to the Keyfactor API Reference and Utility automatically, and will not need to re-authenticate. The need to intentionally provide authentication for the Keyfactor API comes into play in situations such as:
- You are developing or running an application or script that leverages the Keyfactor API.
- You are running a workflow
A workflow is a series of steps necessary to complete a process. In Keyfactor Command, it refers to the workflow builder, which allows you to automate event-driven tasks such as when a certificate is requested, revoked or found in a certificate store. step of type Invoke REST Request.
- You are using the Keyfactor API Reference and Utility and have not authenticated to Keyfactor Command within the same browser session.
In many of these cases, you will probably want to make the API requests not as an individual user, but as a service account. With Active Directory as an identity provider, a standard Active Directory service account in the primary Keyfactor Command server forest An Active Directory forest (AD forest) is the top most logical container in an Active Directory configuration that contains domains, and objects such as users and computers. can be used.
This service account needs to be granted appropriate permissions in Keyfactor Command to complete the API requests that will be run as this service account.
Authentication using OAuth Identity Providers
If you’re using an OAuth identity provider, the API primarily supports the client credentials grant type for authentication, where the client (using a client ID and secret) requests an access token. This is the most common flow. Alternatively, the password grant type can be used in test or development scenarios or when a large user base exists, and building a dedicated client base for the API is impractical. The password grant flow requires both user credentials (username and password) and client credentials (client ID and secret) to request an access token.
The user who will make use of the API must have the client ID, client secret, and the token URL of your identity provider’s token endpoint An endpoint is a URL that enables the API to gain access to resources on a server.. For example:
This client needs to be granted appropriate permissions in Keyfactor Command to complete the API requests that will be run as this client.
For Keyfactor Identity Provider, the client should have Client authentication and Service account roles enabled (see Service Accounts). The token URL is included among the information that can be found on the OpenID Endpoint Configuration page, a link to which can be found on the Realm Settings page (see Configuring Keyfactor Identity Provider and Collecting Data for the Keyfactor Command Installation).
Figure 614: Client Secret for Keyfactor API in Keyfactor Identity Provider
Acquire a Token to Authenticate to the Keyfactor API
If you’re using the Keyfactor API either directly or through the Keyfactor API Reference and Utility (Swagger) with an OAuth identity provider, you'll need to first acquire a token from your identity provider. Ensure you have the following information about your client:
-
Client ID
-
Client Secret
-
Token URL
There are a number of approaches to acquiring a token. Here we provide a couple of examples.
You can acquire the token using curl on a Linux server:
curl --request POST \
--url https://appsrvr18.keyexample.com:1443/realms/Keyfactor/protocol/openid-connect/token \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data client_secret=MyAPIUserClientSecret \
--data client_id=Keyfactor-API-User \
--data grant_type=client_credentials
Or in PowerShell, you can use the following script:
$Body = @{
grant_type = "client_credentials"
client_id = "Keyfactor-API-User"
client_secret = "MyAPIUserClientSecret"
}
$Headers = @{
'Content-Type' = 'application/x-www-form-urlencoded'
}
$TokenResults = Invoke-RestMethod -Method Post -Uri https://appsrvr18.keyexample.com:1443/realms/Keyfactor/protocol/openid-connect/token -Headers $Headers -Body $Body
# Output the token string to a file to avoid CR/LFs
$MyToken = $TokenResults.access_token
Set-Content -Value $MyToken -Path C:\Stuff\MyTokenOutFile.txt
In both cases, the response will contain an access_token. If using PowerShell, the token will be saved to a file to ensure that it is copied without any formatting issues (such as CR/LFs) that might cause problems in API calls. Ensure the token is copied as a single line when using it in API requests.
Using Basic Authentication Credentials in API Requests
When you want to use the Keyfactor API with an Active Directory identity provider, you’ll need to authenticate using either Basic or Windows integrated authentication. In most cases, API applications will use Basic authentication of these choices. For this purpose, you will need:
-
Active Directory domain name for the service account user.
-
Usernameof the service account in Active Directory that will be used for API requests.
-
Password of the service account user.
For example, to make a GET request in PowerShell using Basic authentication:
# Basic auth Credentials to authenticate to the Keyfactor API
$user = 'keyexample\APIUser1'
$pass = 'MySuperSecretAPIUserPassword'
$pair = "$($user):$($pass)"
# Encode credentials (assumes the Keyfactor API is using Basic authentication)
$encodedCreds = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($pair))
$basicAuthValue = "Basic $encodedCreds"
# Options
$APIServer = "keyfactor.keyexample.com"
$query = "&QueryString=CN%20-contains%20%22appsrvr23.keyexample.com%22%20"
$queryextras = "includeLocations=false&includeMetadata=false&includeHasPrivateKey=true&verbose=0"
# Set request headers
$headers = @{
"Authorization"=$basicAuthValue
"Accept"="application/json"
"x-keyfactor-requested-with"="APIClient"
}
# Make the request
$responseCert = Invoke-WebRequest -Uri "https://$APIServer/KeyfactorAPI/Certificates?$queryextras$query" -Method:Get -Headers $headers -ContentType "application/json" -ErrorAction:Stop -TimeoutSec 300
# Convert the response to formatted JSON
$jsonDataCert = $responseCert.Content | ConvertTo-Json -Depth 10 -Compress
Using Token Authentication in API Requests
Once you’ve obtained the token, you can use it to make requests to the Keyfactor API and in the Keyfactor API Reference and Utility.
For example, to make a GET request from a Linux server using curl:
curl -X 'GET' \
'https://keyfactor.keyexample.com/KeyfactorAPI/Certificates/<Your cert ID here>?includeLocations=false&includeMetadata=false&collectionId=0' \
-H 'accept: text/plain' \
-H 'x-keyfactor-requested-with: APIClient' \
-H 'Authorization: Bearer <Your token here>'
Or in PowerShell:
# Step 1: Obtain OAuth token
$Body = @{
grant_type = "client_credentials"
client_id = "Keyfactor-API-User"
client_secret = "MyAPIUserClientSecret"
}
$Headers = @{
'Content-Type' = 'application/x-www-form-urlencoded'
}
$TokenResults = Invoke-RestMethod -Method Post -Uri "https://appsrvr18.keyexample.com:1443/realms/Keyfactor/protocol/openid-connect/token" -Headers $Headers -Body $Body
$MyToken = $TokenResults.access_token
# Optionally, output the token string to a file to avoid CR/LFs
Set-Content -Value $MyToken -Path C:\Stuff\MyTokenOutFile.txt
# Step 2: Use OAuth token to make a GET request to the Keyfactor API
# Options
$APIServer = "keyfactor.keyexample.com"
$query = "&QueryString=CN%20-contains%20%22appsrvr23.keyexample.com%22%20"
$queryextras = "includeLocations=false&includeMetadata=false&includeHasPrivateKey=true&verbose=0"
# Set request headers
$headers = @{
"Authorization"="Bearer $MyToken"
"Accept"="application/json"
"x-keyfactor-requested-with"="APIClient"
}
# Make the request
$responseCert = Invoke-WebRequest -Uri "https://$APIServer/KeyfactorAPI/Certificates?$queryextras$query" -Method:Get -Headers $headers -ContentType "application/json" -ErrorAction:Stop -TimeoutSec 300
# Convert the response to formatted JSON
$jsonDataCert = $responseCert.Content | ConvertTo-Json -Depth 10 -Compress
Or in the Keyfactor API Reference and Utility:
-
Copy the access token value only with no spaces or CR/LFs. For example:
eyJhbGciOi JSUzI1NiIsI nR5cCIgOiAiS ldUIiwia2lkI iA6ICJmYU04Nj Q5UHAzREl1NWN BWkk4a3NYSV [portion removed for display ] KmIoPWfTu_APh MltlbXnnO8NCic2T faF_IrVjlc95EK4b6I aEbWcbCIg_896f5bOxrXed ouGP12dbRHOqB2jffD1glDveTB2XL 4WnbTVuSbgc2NsI SoNzGZB-HGXIW llo4l-PXK42nY5Y Ur7k0lf2W39HSojk yJRuwrpBjeV UmeDVQ_njCQ1ru fxrDK1ZkAnbw3r YiJKGzsVJzAl NwTFiM6-9pHPz6 8Nc1rPwviPyAmQ -
In the Keyfactor API Reference and Utility click either the Authorize button at the top or one of the padlock authorization icons on each endpoint to open the authorization dialog.
Figure 616: Keyfactor API Reference and Utility Authorize Options
-
In the Available authorizations dialog, paste in your access token value and click Authorize.
Figure 617: Enter Access Token in the Keyfactor API Reference and Utility
-
If authorization is successful, the Authorize button will change to Logout, and the padlocks will change to locked.
Figure 618: Successful Authorization in the Keyfactor API Reference and Utility
# Build the headers for the API request
$headers = @{
"Authorization"="Bearer " + $TokenValue.access_token
"Accept"="application/json"
"x-keyfactor-requested-with"="APIClient"
}