Authenticating to the Keyfactor API

When you make a connection to the Keyfactor APIClosed 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:

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 forestClosed 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 endpointClosed An endpoint is a URL that enables the API to gain access to resources on a server.. For example:

https://my-keyidp-server.keyexample.com/realms/Keyfactor/protocol/openid-connect/token

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:

Copy
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:

Copy
$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.

Tip:  The built-in Windows Notepad application will display a maximum of 1024 characters on a line before wrapping even if word wrap is disabled. A tool such as the third-party Notepad++ is much less limited.

Figure 615: Access Token for the Keyfactor API Reference and Utility

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:

Copy
# 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:

Copy
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:

Copy
# 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:

  1. 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
  2. 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

  3. 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

  4. 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

Tip:  When using a token in the Keyfactor API Reference and Utility, you use the token value only. When you use a token to authenticate to the Keyfactor API other than through the Keyfactor API Reference and Utility, you need to precede the token value with Bearer. For example:
Copy
# Build the headers for the API request
$headers = @{
   "Authorization"="Bearer " + $TokenValue.access_token
   "Accept"="application/json"
   "x-keyfactor-requested-with"="APIClient"
}
Important:  Keyfactor highly recommends that you use strong passwords for any accounts or certificates related to Keyfactor Command and associated products, especially when these have elevated or administrative access. A strong password has at least 12 characters (more is better) and multiple character classes (lowercase letters, uppercase letters, numeral, and symbols). Ideally, each password would be randomly generated. Avoid password re-use.