Context:
The Endpoint Credential Manager (ECM) Software Development Kit for BeyondTrust Privileged Remote Access (PRA) and Remote Support (RS) allows developers to leverage a Credential Provider other than the one included (Vault) to allow Users to inject credentials when for accessing a Jump Client, a Web Jump, etc. This guide covers a specific example: CyberArk Self-Hosted aka on-premises, Cloud. This guide also shows how to create a Custom Source to manage the configuration and credentials needed for the Plugin to authenticate to PRA and RS on one side, and to CyberArk on the other side.

Note: Secure Remote Access (SRA) is used to refer to both PRA and RS.
IMPORTANT: The example ECM Plugin covered in this tutorial has not been tested yet against a live instance of CyberArk Self-Hosted or Cloud, and is based on documentation only for the CyberArk Cloud REST API found here: https://docs.cyberark.com/privilege-cloud-shared-services/latest/en/content/webservices/managing%20accounts.htm
And here for Self-Hosted or on-premises: https://docs.cyberark.com/pam-self-hosted/14.2/en/content/webservices/implementing%20privileged%20account%20security%20web%20services%20.htm
Note: The Authentication Response for 2nd Gen API is:
{ "<session token>"}
However for 1st Gen API it is:
{ "CyberArkLogonResult":"<session token>"}
Since the 2nd Gen API response included in documentation is invalid JSON, it is assumed that there is a typo in the documentation, so we will use the 1st Gen API response.
Disclaimer
The Endpoint Credential Manager (ECM) Software Development Kit
Allows developers to create Custom ECM Plugins. The SDK comes with a Plugin example, which has been used as a starting point to create a new Plugin.
Any sample or proof of concept code (“Code”) provided on the Community is provided “as is” and without any express or implied warranties. This means that we do not promise that it will work for your specific needs or that it is error-free. Such Code is community supported and not supported directly by BeyondTrust, and it is not intended to be used in a production environment. BeyondTrust and its contributors are not liable for any damage you or others might experience from using the Code, including but not limited to, loss of data, loss of profits, or any interruptions to your business, no matter what the cause is, even if advised of the possibility of such damage.
Capabilities
- List secrets from CyberArk
- Inject the selected secret into a Jump session
- Optional: Use Environment Variables for the Configuration for a deployment via Jenkins or another CI/CD automation solution.
Configure CyberArk
For CyberArk Cloud, see: https://docs.cyberark.com/privilege-cloud-shared-services/latest/en/content/webservices/managing%20accounts.htm
For CyberArk Self-Hosted, see: https://docs.cyberark.com/pam-self-hosted/latest/en/content/hometileslps/lp-tile4.htm
Note: A CyberArk Self-Hosted and Cloud simulator has been used to test this ECM Plugin example.
Note: A CyberArk Cloud simulator has been used to test this ECM Plugin example.
Obtain and deploy the ECM Runtime and ECM SDK Example Plugin
The documentation for the ECM SDK is available here:
https://www.beyondtrust.com/docs/privileged-remote-access/how-to/integrations/ecm-sdk/index.htm



Here is a quick list of packages that need to be added:
- Json.NET (Newtonsoft.Json);
- Microsoft.Bcl.AsyncInterfaces;
- Microsoft.Bcl.Cryptography;
- System.Formats.Asn1;
- System.ComponentModel.Composition;
- Microsoft.Extensions.Hosting;
- Microsoft.Extensions.Hosting.Abstractions;
- Microsoft.Extensions.Hosting.WindowsServices;
- Microsoft.Extensions.Logging;
- System.Configuration.ConfigurationManager;
- System.DirectoryServices;
- System.Runtime.Caching;
- System.Security.Cryptography.Pkcs;
- System.Security.Cryptography.ProtectedData;
- System.ServiceModel.Primitives;
- System.ServiceProcess.ServiceController .

namespace MyCompany.Integrations.ExamplePlugin
{
/// <summary>
/// Represents a simple POCO that defines the config values necessary for the plugin to operate
/// These are simply examples of the types of items which might be required for your implementation
/// </summary>
public sealed record ExamplePluginConfig
{
public required string ApiBaseUrl { get; init; }
public required string OAuthClientId { get; init; }
public required string OAuthClientSecret { get; init; }
public required string Safe { get; init; }
public string isCloud { get; init; } = "false";
}
}

{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"ECMConfig": {
"SRASiteHostname": "",
"SRAClientId": "",
"SRAClientSecret": ""
},
"ExamplePluginConfig": {
"ApiBaseUrl": "https://test.mycompany.com/path/to/api",
"OAuthClientId": "MyClientId-12345-asdfasdf",
"OAuthClientSecret": "super-secret-client-secret",
"Safe": "mySafe",
"isCloud": "false"
}
}

Note: While it is still possible to leverage appsettings.json for config values, the option to use Environment Variables is covered in this guide, with the use of a CI/CD Solution like Jenkins in mind, to deploy the plugin as a Container, e.g. using for example a Microsoft provided Docker image.
See for example: https://learn.microsoft.com/en-us/dotnet/architecture/microservices/net-core-net-framework-containers/official-net-docker-images

//***** Custom Source - Environment Variables - BEGIN
ExamplePluginConfig ExamplePluginConfig = new ExamplePluginConfig
{
ApiBaseUrl = Environment.GetEnvironmentVariable("ApiBaseUrl"),
OAuthClientId = Environment.GetEnvironmentVariable("OAuthClientId"),
OAuthClientSecret = Environment.GetEnvironmentVariable("OAuthClientSecret"),
Safe = Environment.GetEnvironmentVariable("Safe"),
isCloud = Environment.GetEnvironmentVariable("isCloud")
};
builder.Services.Configure<ExamplePluginConfig>(builder.Configuration);
//***** Custom Source - Environment Variables - END

//***** Custom Source - Environment Variables - BEGIN
ECMConfig ECMConfig = new ECMConfig {
SRASiteHostname = Environment.GetEnvironmentVariable("SRASiteHostName"),
SRAClientId = Environment.GetEnvironmentVariable("SRAClientId"),
SRAClientSecret = Environment.GetEnvironmentVariable("SRAClientSecret")
};
builder.Services.Configure<ECMConfig>(builder.Configuration);
//***** Custom Source - Environment Variables – END

// Custom Code - START
private static async Task<string> GetAuthToken(string ApiUrl, string CLIENT_ID, string CLIENT_SECRET)
{
try
{
var httpClient = new HttpClient
{
DefaultRequestHeaders = {
{ "User-Agent", "BeyondTrust Secure Remote Access" }
}
};
var content = new FormUrlEncodedContent(new Dictionary<string, string>
{
{"grant_type", "client_credentials"} ,
{"client_id", CLIENT_ID} ,
{"client_secret", CLIENT_SECRET}
}
);
HttpResponseMessage message = httpClient.PostAsync(ApiUrl + "/oauth2/platformtoken", content).Result;
string result = await message.Content.ReadAsStringAsync();
if (message.IsSuccessStatusCode)
{
return result;
}
else
{
throw new Exception("Failed to Authenticate " + result);
}
}
catch (Exception ex)
{
Console.Write("####### Error in method = " + ex.ToString());
throw new Exception("Failed to Authenticate " + ex.ToString());
}
}
private static async Task<string> GetAuthTokenBasic(string ApiUrl, string USERNAME, string PASSWD)
{
try
{
var httpClient = new HttpClient
{
DefaultRequestHeaders = {
{ "User-Agent", "BeyondTrust Secure Remote Access" }
}
};
string myJson = "{\"username\":\"" + USERNAME + "\",\"password\":\"" + PASSWD + "\"}";
var httpContent = new StringContent(myJson, Encoding.UTF8, "application/json");
HttpResponseMessage message = httpClient.PostAsync(ApiUrl + "/PasswordVault/API/auth/Cyberark/Logon", httpContent).Result;
string result = await message.Content.ReadAsStringAsync();
if (message.IsSuccessStatusCode)
{
return result;
}
else
{
throw new Exception("Failed to Authenticate " + result);
}
}
catch (Exception ex)
{
Console.Write("####### Error in method = " + ex.ToString());
throw new Exception("Failed to Authenticate " + ex.ToString());
}
}
private static async Task<string> GetAccounts(string ApiUrl, string BEARER_TOKEN, string Safe, string isCloud)
{
try
{
var httpClient = new HttpClient();
if (isCloud == "true")
{
httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", BEARER_TOKEN);
} else
{
httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(BEARER_TOKEN);
}
HttpResponseMessage message = httpClient.GetAsync(ApiUrl + "/PasswordVault/API/Accounts?filter=safeName%20eq%20" + Safe).Result;
string result = await message.Content.ReadAsStringAsync();
if (message.IsSuccessStatusCode)
{
return result;
}
else
{
throw new Exception("Failed to Discover Safe Accounts " + result);
}
}
catch (Exception ex)
{
Console.Write("####### Error in method = " + ex.ToString());
throw new Exception("Failed to Discover Safe Accounts " + ex.ToString());
}
}
private static async Task<string> GetAccount(string ApiUrl, string BEARER_TOKEN, string AccountId, string isCloud)
{
try
{
var httpClient = new HttpClient();
if (isCloud == "true")
{
httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", BEARER_TOKEN);
}
else
{
httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(BEARER_TOKEN);
}
HttpResponseMessage message = httpClient.GetAsync(ApiUrl + "/PasswordVault/API/Accounts/" + AccountId).Result;
string result = await message.Content.ReadAsStringAsync();
if (message.IsSuccessStatusCode)
{
return result;
}
else
{
throw new Exception("Failed to Get Account " + result);
}
}
catch (Exception ex)
{
Console.Write("####### Error in method = " + ex.ToString());
throw new Exception("Failed to Get Account " + ex.ToString());
}
}
private static async Task<string> GetSecret(string ApiUrl, string BEARER_TOKEN, string AccountId, string isCloud)
{
try
{
var httpClient = new HttpClient();
if (isCloud == "true")
{
httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", BEARER_TOKEN);
}
else
{
httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(BEARER_TOKEN);
}
string myJson = "{\"reason\":\"SRA ECM Plugin\",\"ActionType\":\"show\"}";
Console.Write("####### myJson = " + myJson + "\n");
var httpContent = new StringContent(myJson, Encoding.UTF8, "application/json");
HttpResponseMessage message = httpClient.PostAsync(ApiUrl + "/PasswordVault/API/Accounts/" + AccountId + "/Password/Retrieve", httpContent).Result;
string result = await message.Content.ReadAsStringAsync();
if (message.IsSuccessStatusCode)
{
return result;
}
else
{
throw new Exception("Failed to Get Secret " + result);
}
}
catch (Exception ex)
{
Console.Write("####### Error in method = " + ex.ToString());
throw new Exception("Failed to Get Secret " + ex.ToString());
}
}
// Custom Code - END

private readonly ExamplePluginConfig examplePluginConfig;
public ExamplePlugin(IOptions<ExamplePluginConfig> config)
{
// Possible tasks to handle when the service is instantiated:
// - validate configuration
// - initialize any sort of API client or other types that will be required for servicing requests
// - pre-load any information that may be required for servicing requests (files, API / product version info, etc.)
examplePluginConfig = config.Value;
}

public async Task<ActionResult<IList<CredentialSummary>>> FindCredentialsForSessionAsync(SRASession session)
{
// At this point the user has chosen a Jump Item in the console and attempted to initiate a session to the target system.
// The plugin should retrieve a list of credentials that are either queried or filtered based on the supplied
// information about the user and system to which the user is connecting.
// NOTE: While the operation is async, the SRA site will only wait for a certain period of time (20 seconds by default)
// for the list to be returned before it proceeds without presenting any creds for selection.
try
{
// GET Accounts List
string access_token = "";
string isCloud = examplePluginConfig.isCloud;
if (isCloud == "true")
{
// Authenticate - GET Bearer Token
var token = await GetAuthToken(examplePluginConfig.ApiBaseUrl, examplePluginConfig.OAuthClientId, examplePluginConfig.OAuthClientSecret);
dynamic jsonString_token = JsonConvert.DeserializeObject(token);
access_token = jsonString_token.access_token;
}
else if (isCloud == "false")
{
// Authenticate - GET Token
var token = await GetAuthTokenBasic(examplePluginConfig.ApiBaseUrl, examplePluginConfig.OAuthClientId, examplePluginConfig.OAuthClientSecret);
dynamic jsonString_token = JsonConvert.DeserializeObject(token);
access_token = jsonString_token.CyberArkLogonResult;
}
Console.Write("We got access token " + "\n");
// Get Accounts
var accounts = await GetAccounts(examplePluginConfig.ApiBaseUrl, access_token, examplePluginConfig.Safe, isCloud);
Console.Write("We got Accounts \n");
dynamic jsonString_accounts = JsonConvert.DeserializeObject(accounts);
List<CredentialSummary> credentials = new List<CredentialSummary>();
foreach (var i in jsonString_accounts)
{
Console.Write("####### Discovered Account = " + i.name + " id = " + i.id + " userName = " + i.userName + "\n");
CredentialSummary credential = new CredentialSummary { CredentialId = i.id, DisplayValue = "CyberArk : " + i.name };
credentials.Add(credential);
}
// Then put that all in an ActionResult object to be returned
return new ActionResult<IList<CredentialSummary>> { ResultValue = credentials, IsSuccess = true };
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to get list of Credentials");
return new ActionResult<IList<CredentialSummary>> { ResultValue = null, FailureReason = ex.Message, IsSuccess = false };
}
// COMMENTED - throw new NotImplementedException($"The {Name} definition must implement {nameof(FindCredentialsForSessionAsync)} as defined by {nameof(ICredentialActions)}");
}

public async Task<ActionResult<CredentialPackage>> GetCredentialForInjectionAsync(SRASession session, string credentialId)
{
// The user has been presented with a list of credentials (supplied by FindCredentialsForSessionAsync above) and has
// selected one from the list. The plugin should use the information supplied about the session as well as the ID of
// the selected credential to attempt to retrieve / check-out that credential and return it for injection into the session.
// NOTE: As above, it is important to note that while the operation is async, the same timeout applies.
try
{
string access_token = "";
string isCloud = examplePluginConfig.isCloud;
if (isCloud == "true")
{
// Authenticate - GET Bearer Token
var token = await GetAuthToken(examplePluginConfig.ApiBaseUrl, examplePluginConfig.OAuthClientId, examplePluginConfig.OAuthClientSecret);
dynamic jsonString_token = JsonConvert.DeserializeObject(token);
access_token = jsonString_token.access_token;
}
else if (isCloud == "false")
{
// Authenticate - GET Token
var token = await GetAuthTokenBasic(examplePluginConfig.ApiBaseUrl, examplePluginConfig.OAuthClientId, examplePluginConfig.OAuthClientSecret);
dynamic jsonString_token = JsonConvert.DeserializeObject(token);
access_token = jsonString_token.CyberArkLogonResult;
}
// GET userName from Account details
var account = await GetAccount(examplePluginConfig.ApiBaseUrl, access_token, credentialId, isCloud);
dynamic jsonString_account = JsonConvert.DeserializeObject(account);
string userName = jsonString_account.userName;
Console.Write("####### Retrieved userName = " + userName + "\n");
// Get Secret
Console.Write("####### Get secret id = " + credentialId + " username = " + userName + "\n");
var secret = await GetSecret(examplePluginConfig.ApiBaseUrl, access_token, credentialId, isCloud);
string secretValue = secret;
var result = CredentialPackage.BuildUsernamePasswordPackage(credentialId, userName, secretValue);
return new ActionResult<CredentialPackage> { ResultValue = result, IsSuccess = true };
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to inject Credentials");
return new ActionResult<CredentialPackage> { ResultValue = null, FailureReason = ex.Message, IsSuccess = false };
}
// COMMENTED - throw new NotImplementedException($"The {Name} definition must implement {nameof(GetCredentialForInjectionAsync)} as defined by {nameof(ICredentialActions)}");
}

return new ActionResult { IsSuccess = true };

Build and Debug


Next Steps
Once we can successfully Build and test the Plugin App via Debug in Visual Studio, the App and all its dependencies can be deployed. It is not recommended to use appsettings.json to store sensitive configuration information including credentials, so another config Source should be used. Several examples are available on the web, and covering them is out of scope for this guide. However, this guide does include an example using Environment Variables, which can make sense for when the Plugin App is containerized and a CI/CD solution like Jenkins is used to deploy the container to Docker or Kubernetes.