Management Keys with SDKs
You can use the Descope management SDK to create, update, delete, load, or search Management Keys. The management SDK requires a management key, which can be generated here.
If you wish to learn more about how Management Keys work, see Company Settings.
Management Keys using the management SDK
Backend SDK
Install SDK
npm i --save @descope/node-sdkpip3 install descopego get github.com/descope/go-sdk// Include the following in your `pom.xml` (Maven)
<dependency>
<artifactId>java-sdk</artifactId>
<groupId>com.descope</groupId>
<version>sdk-version</version> // Check https://github.com/descope/descope-java/releases for the latest versions
</dependency>gem install descopecomposer require descope/descope-phpdotnet add package DescopeImport and initialize SDK
import DescopeClient from '@descope/node-sdk';
try{
// baseUrl="<URL>" // When initializing the Descope client, you can also configure the baseUrl ex: https://auth.company.com - this is useful when you utilize a custom domain within your Descope project.
const descopeClient = DescopeClient({ projectId: '__ProjectID__' });
} catch (error) {
// handle the error
console.log("failed to initialize: " + error)
}
from descope import (
REFRESH_SESSION_TOKEN_NAME,
SESSION_TOKEN_NAME,
AuthException,
DeliveryMethod,
DescopeClient,
AssociatedTenant,
RoleMapping,
AttributeMapping,
LoginOptions
)
try:
# You can configure the baseURL by setting the env variable Ex: export DESCOPE_BASE_URI="https://auth.company.com - this is useful when you utilize custom domain within your Descope project."
descope_client = DescopeClient(project_id='__ProjectID__')
except Exception as error:
# handle the error
print ("failed to initialize. Error:")
print (error)import "github.com/descope/go-sdk/descope"
import "github.com/descope/go-sdk/descope/client"
// Utilizing the context package allows for the transmission of context capabilities like cancellation
// signals during the function call. In cases where context is absent, the context.Background()
// function serves as a viable alternative.
// Utilizing context within the Descope GO SDK is supported within versions 1.6.0 and higher.
import (
"context"
)
// DescopeBaseURL // within the client.Config, you can also configure the baseUrl ex: https://auth.company.com - this is useful when you utilize a custom domain within your Descope project.
descopeClient, err := client.NewWithConfig(&client.Config{ProjectID:"__ProjectID__"})
if err != nil {
// handle the error
log.Println("failed to initialize: " + err.Error())
}import com.descope.client.Config;
import com.descope.client.DescopeClient;
var descopeClient = new DescopeClient(Config.builder().projectId("__ProjectID__").build());require 'descope'
@project_id = ENV['__ProjectID__']
@client = Descope::Client.new({ project_id: @project_id})require 'vendor/autoload.php';
use Descope\SDK\DescopeSDK;
$descopeSDK = new DescopeSDK([
'projectId' => $_ENV['__ProjectID__'],
]);using Descope;
// Configure the Descope client
var options = new DescopeClientOptions
{
ProjectId = "__ProjectID__", // Required
ManagementKey = "DESCOPE_MANAGEMENT_KEY", // Optional, for management APIs
BaseUrl = "__BaseURL__", // Optional, auto-detected from project ID, only set to override
JwksCacheDuration = TimeSpan.FromMinutes(5) // Optional, how long public signing keys are cached (default: 5 minutes)
};
// Option 1: Dependency Injection - best for ASP.NET Core apps; registers IDescopeClient so it can be injected into your services
builder.Services.AddDescopeClient(options);
// Then inject IDescopeClient wherever you need it
public class MyService
{
private readonly IDescopeClient descopeClient;
public MyService(IDescopeClient client)
{
descopeClient = client;
}
}
// Option 2: Factory (Create once and reuse this instance) - best for console apps, background workers, or when you need to manually control the client's lifetime
var descopeClient = DescopeManagementClientFactory.Create(options);Search All Management Keys
Note
You can also use our Search Management Keys API to list all Management Keys.
This operation returns all Management Keys in your company.
const resp = await descopeClient.management.managementKey.search();
if (!resp.ok) {
console.log("Failed to search management keys.")
console.log("Status Code: " + resp.code)
console.log("Error Code: " + resp.error.errorCode)
console.log("Error Description: " + resp.error.errorDescription)
console.log("Error Message: " + resp.error.errorMessage)
}
else {
console.log("Successfully searched management keys.")
console.log(resp.data)
}try:
resp = descope_client.mgmt.management_key.search()
print ("Successfully searched management keys.")
print(json.dumps(resp, indent=2))
except AuthException as error:
print ("Unable to search management keys.")
print ("Status Code: " + str(error.status_code))
print ("Error: " + str(error.error_message))// Args:
// ctx: context.Context - Application context for the transmission of context capabilities like
// cancellation signals during the function call. In cases where context is absent, the context.Background()
// function serves as a viable alternative.
// Utilizing context within the Descope GO SDK is supported within versions 1.6.0 and higher.
ctx := context.Background()
// options (*descope.MgmtKeySearchOptions): Required search options. Currently unused; pass an empty struct (nil is not allowed).
options := &descope.MgmtKeySearchOptions{}
keys, err := descopeClient.Management.ManagementKey().Search(ctx, options)
if (err != nil){
fmt.Println("Unable to search management keys: ", err)
} else {
fmt.Println("Successfully searched management keys.")
fmt.Println(keys)
}try
{
var keyRes = await descopeClient.Mgmt.V1.Managementkey.Search.GetAsync();
}
catch (DescopeException ex)
{
// Handle the error
}Load Management Key by ID
Note
You can also use our Get Management Key API to load a specific Management Key.
This operation loads an existing Management Key by ID, including its name, description, status, expiration, permitted IPs, and role configuration. The key secret (cleartext) is not returned.
// Args:
// id (str): The Management Key ID.
const id = "key-id";
const resp = await descopeClient.management.managementKey.load(id);
if (!resp.ok) {
console.log("Failed to load management key.")
console.log("Status Code: " + resp.code)
console.log("Error Code: " + resp.error.errorCode)
console.log("Error Description: " + resp.error.errorDescription)
console.log("Error Message: " + resp.error.errorMessage)
}
else {
console.log("Successfully loaded management key.")
console.log(resp.data)
}# Args:
# id (str): The Management Key ID.
id = "key-id"
try:
resp = descope_client.mgmt.management_key.load(id)
print ("Successfully loaded management key.")
print(json.dumps(resp, indent=2))
except AuthException as error:
print ("Unable to load management key.")
print ("Status Code: " + str(error.status_code))
print ("Error: " + str(error.error_message))// Args:
// ctx: context.Context - Application context for the transmission of context capabilities like
// cancellation signals during the function call. In cases where context is absent, the context.Background()
// function serves as a viable alternative.
// Utilizing context within the Descope GO SDK is supported within versions 1.6.0 and higher.
ctx := context.Background()
// id (string): The Management Key ID.
id := "key-id"
key, err := descopeClient.Management.ManagementKey().Get(ctx, id)
if (err != nil){
fmt.Println("Unable to load management key: ", err)
} else {
fmt.Println("Successfully loaded management key.")
fmt.Println(key)
}// Args:
// id (string): The Management Key ID.
var id = "key-id";
try
{
var keyRes = await descopeClient.Mgmt.V1.Managementkey.GetAsync(config =>
{
config.QueryParameters.Id = id;
});
}
catch (DescopeException ex)
{
// Handle the error
}Create Management Key
Note
You can also use our Create Management Key API to create a Management Key.
This operation creates a new Management Key. A name and role configuration (reBac) are required; description, expiration (expiresIn in seconds; 0 for no expiration), and permitted IPs are optional. Roles can be set at the company, project, or tag level and cannot be changed after creation. The response includes the key details and the cleartext secret — store the secret securely, as it is only returned once.
// Args:
// name (str): Required name for the management key.
const name = "my-key-name";
// reBac (MgmtKeyReBac): Role-based access control configuration for the key.
const reBac = { companyRoles: ["company-fga-read-write"] };
// description (str): Optional description.
const description = "Optional description";
// expiresIn (number): Optional expiration time in seconds (0 for no expiration).
const expiresIn = 3600;
// permittedIps (List[str]): Optional list of IP addresses or CIDR ranges that are allowed to use this key.
const permittedIps = ["10.0.0.1/24"];
const resp = await descopeClient.management.managementKey.create(
name,
description,
expiresIn,
permittedIps,
reBac,
);
if (!resp.ok) {
console.log("Failed to create management key.")
console.log("Status Code: " + resp.code)
console.log("Error Code: " + resp.error.errorCode)
console.log("Error Description: " + resp.error.errorDescription)
console.log("Error Message: " + resp.error.errorMessage)
}
else {
console.log("Successfully created management key.")
console.log(resp.data.key)
console.log("Key secret (save this!): " + resp.data.cleartext)
}# Args:
# name (str): Required name for the management key.
name = "my-key-name"
# rebac (MgmtKeyReBac): Role-based access control configuration for the key.
rebac = MgmtKeyReBac(company_roles=["company-fga-read-write"])
# description (str): Optional description.
description = "Optional description"
# expires_in (int): Optional expiration time in seconds (0 for no expiration).
expires_in = 3600
# permitted_ips (List[str]): Optional list of IP addresses or CIDR ranges that are allowed to use this key.
permitted_ips = ["10.0.0.1/24"]
try:
resp = descope_client.mgmt.management_key.create(
name=name,
rebac=rebac,
description=description,
expires_in=expires_in,
permitted_ips=permitted_ips,
)
print ("Successfully created management key.")
print(json.dumps(resp["key"], indent=2))
print ("Key secret (save this!): " + resp["cleartext"])
except AuthException as error:
print ("Unable to create management key.")
print ("Status Code: " + str(error.status_code))
print ("Error: " + str(error.error_message))// Args:
// ctx: context.Context - Application context for the transmission of context capabilities like
// cancellation signals during the function call. In cases where context is absent, the context.Background()
// function serves as a viable alternative.
// Utilizing context within the Descope GO SDK is supported within versions 1.6.0 and higher.
ctx := context.Background()
// name (string): Required name for the management key.
name := "my-key-name"
// description (string): Optional description.
description := "Optional description"
// expiresIn (uint64): Optional expiration time in seconds (0 for no expiration).
expiresIn := uint64(3600)
// permittedIPs ([]string): Optional list of IP addresses or CIDR ranges that are allowed to use this key.
permittedIPs := []string{"10.0.0.1/24"}
// reBac (*descope.MgmtKeyReBac): Role-based access control configuration for the key.
reBac := &descope.MgmtKeyReBac{CompanyRoles: []string{"company-fga-read-write"}}
key, cleartext, err := descopeClient.Management.ManagementKey().Create(
ctx,
name,
description,
expiresIn,
permittedIPs,
reBac,
)
if (err != nil){
fmt.Println("Unable to create management key: ", err)
} else {
fmt.Println("Successfully created management key.")
fmt.Println(key)
fmt.Println("Key secret (save this!): ", cleartext)
}// Args:
// name (string): Required name for the management key.
var name = "my-key-name";
// reBac (ManagementKeyReBac): Role-based access control configuration for the key.
var reBac = new ManagementKeyReBac
{
CompanyRoles = new List<string> { "company-fga-read-write" },
};
// description (string): Optional description.
var description = "Optional description";
// expiresIn (string?): Optional expiration time in seconds ("0" for no expiration).
var expiresIn = "3600";
// permittedIps (List<string>?): Optional list of IP addresses or CIDR ranges that are allowed to use this key.
var permittedIps = new List<string> { "10.0.0.1/24" };
var createRequest = new CreateManagementKeyRequest
{
Name = name,
ReBac = reBac,
Description = description,
ExpiresIn = expiresIn,
PermittedIps = permittedIps,
};
try
{
var keyRes = await descopeClient.Mgmt.V1.Managementkey.PutAsync(createRequest);
}
catch (DescopeException ex)
{
// Handle the error
}Update Management Key
Note
You can also use our Update Management Key API to update a Management Key.
This operation updates an existing Management Key's name, description, status (active or inactive), and permitted IPs. All provided fields override the current values, and fields will be reset if not provided.
Role and project associations cannot be changed after creation — deactivate or delete the key and create a new one if those need to change.
// Args:
// id (str): The Management Key ID.
const id = "key-id";
// name (str): The updated name for the management key.
const name = "updated-key-name";
// description (str): The updated description for the management key.
const description = "Updated description";
// status (MgmtKeyStatus): The status of the management key ('active' or 'inactive').
const status = "active";
// permittedIps (List[str]): Optional list of IP addresses or CIDR ranges that are allowed to use this key.
const permittedIps = ["1.2.3.4"];
const resp = await descopeClient.management.managementKey.update(
id,
name,
description,
status,
permittedIps,
);
if (!resp.ok) {
console.log("Failed to update management key.")
console.log("Status Code: " + resp.code)
console.log("Error Code: " + resp.error.errorCode)
console.log("Error Description: " + resp.error.errorDescription)
console.log("Error Message: " + resp.error.errorMessage)
}
else {
console.log("Successfully updated management key.")
console.log(resp.data)
}# Args:
# id (str): The Management Key ID.
id = "key-id"
# name (str): The updated name for the management key.
name = "updated-key-name"
# description (str): The updated description for the management key.
description = "Updated description"
# permitted_ips (List[str]): List of IP addresses or CIDR ranges that are allowed to use this key.
permitted_ips = ["1.2.3.4"]
# status (MgmtKeyStatus): The status of the management key (MgmtKeyStatus.ACTIVE or MgmtKeyStatus.INACTIVE).
status = MgmtKeyStatus.ACTIVE
try:
resp = descope_client.mgmt.management_key.update(
id=id,
name=name,
description=description,
permitted_ips=permitted_ips,
status=status,
)
print ("Successfully updated management key.")
print(json.dumps(resp, indent=2))
except AuthException as error:
print ("Unable to update management key.")
print ("Status Code: " + str(error.status_code))
print ("Error: " + str(error.error_message))// Args:
// ctx: context.Context - Application context for the transmission of context capabilities like
// cancellation signals during the function call. In cases where context is absent, the context.Background()
// function serves as a viable alternative.
// Utilizing context within the Descope GO SDK is supported within versions 1.6.0 and higher.
ctx := context.Background()
// id (string): The Management Key ID.
id := "key-id"
// name (string): The updated name for the management key.
name := "updated-key-name"
// description (string): The updated description for the management key.
description := "Updated description"
// permittedIPs ([]string): Optional list of IP addresses or CIDR ranges that are allowed to use this key.
permittedIPs := []string{"1.2.3.4"}
// status (descope.MgmtKeyStatus): The status of the management key (descope.MgmtKeyActive or descope.MgmtKeyInactive).
status := descope.MgmtKeyActive
key, err := descopeClient.Management.ManagementKey().Update(
ctx,
id,
name,
description,
permittedIPs,
status,
)
if (err != nil){
fmt.Println("Unable to update management key: ", err)
} else {
fmt.Println("Successfully updated management key.")
fmt.Println(key)
}// Args:
// id (string): The Management Key ID.
var id = "key-id";
// name (string): The updated name for the management key.
var name = "updated-key-name";
// description (string): The updated description for the management key.
var description = "Updated description";
// status (string): The status of the management key ("active" or "inactive").
var status = "active";
// permittedIps (List<string>?): Optional list of IP addresses or CIDR ranges that are allowed to use this key.
var permittedIps = new List<string> { "1.2.3.4" };
var updateRequest = new UpdateManagementKeyRequest
{
Id = id,
Name = name,
Description = description,
Status = status,
PermittedIps = permittedIps,
};
try
{
var keyRes = await descopeClient.Mgmt.V1.Managementkey.PatchAsync(updateRequest);
}
catch (DescopeException ex)
{
// Handle the error
}Delete Management Key(s)
Note
You can also use our Delete Management Keys API to delete a Management Key.
This operation deletes one or more existing Management Keys by ID. This action is irreversible — deleted keys are removed and can no longer be used or reactivated.
// Args:
// ids (List[str]): The IDs of the Management Keys to delete.
const ids = ["key-id-1", "key-id-2"];
const resp = await descopeClient.management.managementKey.delete(ids);
if (!resp.ok) {
console.log("Failed to delete management keys.")
console.log("Status Code: " + resp.code)
console.log("Error Code: " + resp.error.errorCode)
console.log("Error Description: " + resp.error.errorDescription)
console.log("Error Message: " + resp.error.errorMessage)
}
else {
console.log("Successfully deleted management keys.")
}# Args:
# ids (List[str]): The IDs of the Management Keys to delete.
ids = ["key-id-1", "key-id-2"]
try:
resp = descope_client.mgmt.management_key.delete(ids)
print ("Successfully deleted management keys.")
print ("Total deleted: " + str(resp["total"]))
except AuthException as error:
print ("Unable to delete management keys.")
print ("Status Code: " + str(error.status_code))
print ("Error: " + str(error.error_message))// Args:
// ctx: context.Context - Application context for the transmission of context capabilities like
// cancellation signals during the function call. In cases where context is absent, the context.Background()
// function serves as a viable alternative.
// Utilizing context within the Descope GO SDK is supported within versions 1.6.0 and higher.
ctx := context.Background()
// ids ([]string): The IDs of the Management Keys to delete.
ids := []string{"key-id-1", "key-id-2"}
total, err := descopeClient.Management.ManagementKey().Delete(ctx, ids)
if (err != nil){
fmt.Println("Unable to delete management keys: ", err)
} else {
fmt.Println("Successfully deleted management keys.")
fmt.Println("Total deleted: ", total)
}// Args:
// ids (List<string>): The IDs of the Management Keys to delete.
var ids = new List<string> { "key-id-1", "key-id-2" };
try
{
var keyRes = await descopeClient.Mgmt.V1.Managementkey.DeletePath.PostAsync(
new DeleteManagementKeysRequest { Ids = ids }
);
}
catch (DescopeException ex)
{
// Handle the error
}