JWTs with SDKs

You can use the Descope management SDK for JWT operations like adding custom claims, generating session tokens for users, et cetera. The management SDK requires a management key, which can be generated here.

Install SDK

Terminal
npm i --save @descope/node-sdk
Terminal
pip3 install descope
Terminal
go get github.com/descope/go-sdk
// Include the following in your `pom.xml` (for 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>
Terminal
gem install descope
Terminal
composer require descope/descope-php
Terminal
dotnet add package descope

Import and Initialize Management SDK

import DescopeClient from '@descope/node-sdk';

const managementKey = "xxxx"

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__', managementKey: managementKey });
} 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
)

management_key = "xxxx"

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 a custom domain within your Descope project."
    descope_client = DescopeClient(project_id='__ProjectID__', management_key=management_key)
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"
import "fmt"

// 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"
)

managementKey = "xxxx"

// 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__", managementKey:managementKey})
if err != nil {
    // handle the error
    log.Println("failed to initialize: " + err.Error())
}
import com.descope.client;

// Initialized after setting the DESCOPE_PROJECT_ID env var (and optionally DESCOPE_MANAGEMENT_KEY)
var descopeClient = new DescopeClient();

// ** Or directly **
var descopeClient = new DescopeClient(Config.builder()
        .projectId("__ProjectID__")
        .managementKey("management-key")
        .build());
require 'descope'

descope_client = Descope::Client.new(
  {
    project_id: '__ProjectID__',
    management_key: 'management_key'
  }
)
require 'vendor/autoload.php';
use Descope\SDK\DescopeSDK;
 
$descopeSDK = new DescopeSDK([
    'projectId' => $_ENV['DESCOPE_PROJECT_ID'],
    'managementKey' => $_ENV['DESCOPE_MANAGEMENT_KEY']
]);
// appsettings.json

{
  "Descope": {
    "ProjectId": "your-project-id",
    "ManagementKey": "your-management-key"
  }
}

// Program.cs

using Descope;
using Microsoft.Extensions.Configuration;

// ... In your setup code
var config = new ConfigurationBuilder()
  .AddJsonFile("appsettings.json")
  .Build();

var descopeProjectId = config["Descope:ProjectId"];
var descopeManagementKey = config["Descope:ManagementKey"];

var descopeConfig = new DescopeConfig(projectId: descopeProjectId);
var descopeClient = new DescopeClient(descopeConfig)
{
    ManagementKey = descopeManagementKey,
};

Update JWT With Custom Claims

Note

Learn more about configuring custom token claims in our Token Claims Management docs.

This operation updates a valid JWT with the custom claims you provide. You can optionally set how long the updated JWT remains valid using refreshDuration (in seconds). The new JWT will be returned.

// Args:
//   jwt (string): The JWT to update (required).
//   customClaims (object): Optional, custom claims to add to the JWT
//   refreshDuration (number): Optional, duration in seconds for which the new JWT will be valid
const jwt = "original-jwt"
const customClaims = {
  "custom-key1": "custom-value1",
  "custom-key2": "custom-value2",
}
const refreshDuration = 3600

const resp = await descopeClient.management.jwt.update(jwt, customClaims, refreshDuration)
if (!resp.ok) {
  console.log("Failed to update JWT")
  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 JWT")
  console.log(resp.data.jwt)
}
# Args:
#   jwt (str): The JWT to update (required).
#   custom_claims (dict): Custom claims to add to the JWT
#   refresh_duration (int): Optional, duration in seconds for which the new JWT will be valid
jwt = "original-jwt"
custom_claims = {
    "custom-key1": "custom-value1",
    "custom-key2": "custom-value2",
}
refresh_duration = 3600

try:
  updated_jwt = descope_client.mgmt.jwt.update_jwt(
    jwt=jwt,
    custom_claims=custom_claims,
    refresh_duration=refresh_duration,
  )
  print("Successfully updated JWT.")
  print(updated_jwt)
except AuthException as error:
  print("Unable to update JWT.")
  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()
//   jwt (string): The JWT to update (required).
jwt := "original-jwt"
//   customClaims (map[string]interface{}): Optional, custom claims to add to the JWT
customClaims := map[string]interface{}{
  "custom-key1": "custom-value1",
  "custom-key2": "custom-value2",
}
//   refreshDuration (int32): Optional, duration in seconds for which the new JWT will be valid
refreshDuration := int32(3600)

updatedJWT, err := descopeClient.Management.JWT().UpdateJWTWithCustomClaims(ctx, jwt, customClaims, refreshDuration)
if err != nil {
  fmt.Println("Unable to update JWT.", err)
} else {
  fmt.Println("Successfully updated JWT.")
  fmt.Println(updatedJWT)
}
// Args:
//   jwt (String): The JWT to update (required).
//   customClaims (Map<String, Object>): Custom claims to add to the JWT
JwtService jwts = descopeClient.getManagementServices().getJwtService();
try {
  String updatedJwt = jwts.updateJWTWithCustomClaims("original-jwt",
    new HashMap<String, Object>() {{
      put("custom-key1", "custom-value1");
      put("custom-key2", "custom-value2");
    }}).getJwt();
  System.out.println("Successfully updated JWT.");
  System.out.println(updatedJwt);
} catch (DescopeException de) {
  // Handle the error
}
# Args:
#   jwt (String): The JWT to update (required).
#   custom_claims (Hash): Custom claims to add to the JWT
updated_jwt = descope_client.update_jwt(
  jwt: 'original-jwt',
  custom_claims: {
    'custom-key1': 'custom-value1',
    'custom-key2': 'custom-value2',
  },
)
puts "Successfully updated JWT."
puts updated_jwt
// Args:
//   Jwt (string): The JWT to update (required).
//   CustomClaims (UpdateJWTRequest_customClaims): Custom claims to add to the JWT
//   RefreshDuration (int?): Optional, duration in seconds for which the new JWT will be valid
var customClaims = new UpdateJWTRequest_customClaims();
customClaims.AdditionalData["custom-key1"] = "custom-value1";
customClaims.AdditionalData["custom-key2"] = "custom-value2";

var updateJwtRequest = new UpdateJWTRequest
{
    Jwt = "original-jwt",
    CustomClaims = customClaims,
    RefreshDuration = 3600,
};

var updateJwtResponse = await descopeClient.Mgmt.V1.Jwt.Update.PostAsync(updateJwtRequest);
var updatedJwt = updateJwtResponse?.Jwt;
Console.WriteLine("Successfully updated JWT.");
Console.WriteLine(updatedJwt);

Generate JWT for Generic Auth Sign In

This operation is only for Sign-In, and if the login ID doesn't already exist it will return an error and ask you to sign up the user first.

This operation programmatically mints a Descope session (session and refresh JWTs) for an existing user (identified by loginID) independent of a specific auth method. The result is equivalent to that produced by a successful SignIn operation.

Use this if you verify identity elsewhere and want Descope tokens for an existing user, if you need backend-initiated sessions, or to generate valid tokens for automated testing. This requires a management key and must only be called from trusted server-side code.

Note

You can also perform this operation through the Generate JWT for Sign-In Management API.

// Args:
//   loginId (string): The login ID of the existing user to sign in (required).
//   loginOptions (object): Optional, options to customize the generated session (custom claims, refreshDuration, etc.)
const loginId = "user@example.com"
const loginOptions = {
  customClaims: {
    "custom-key1": "custom-value1",
  },
  refreshDuration: 3600, // Optional, duration in seconds for which the session will be valid
}

const resp = await descopeClient.management.jwt.signIn(loginId, loginOptions)
if (!resp.ok) {
  console.log("Failed to generate JWT for sign in")
  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 generated JWT for sign in")
  console.log(resp.data.sessionJwt)
  console.log(resp.data.refreshJwt)
}
from descope.management.common import MgmtLoginOptions

# Args:
#   login_id (str): The login ID of the existing user to sign in (required).
#   login_options (MgmtLoginOptions): Optional, options to customize the generated session
login_options = MgmtLoginOptions(
    custom_claims={"custom-key1": "custom-value1"},
    refresh_duration=3600,
)

try:
  jwt_response = descope_client.mgmt.jwt.sign_in(
    login_id="user@example.com",
    login_options=login_options,
  )
  print("Successfully generated JWT for sign in.")
  print(jwt_response)
except AuthException as error:
  print("Unable to generate JWT for sign in.")
  print("Status Code: " + str(error.status_code))
  print("Error: " + str(error.error_message))
// Args:
//   ctx: context.Context - Application context.
ctx := context.Background()
//   loginID (string): The login ID of the existing user to sign in (required).
loginID := "user@example.com"
//   loginOptions (*descope.MgmLoginOptions): Optional, options to customize the generated session
loginOptions := &descope.MgmLoginOptions{
  CustomClaims: map[string]any{
    "custom-key1": "custom-value1",
  },
  RefreshDuration: int32(3600),
}

authInfo, err := descopeClient.Management.JWT().SignIn(ctx, loginID, loginOptions)
if err != nil {
  fmt.Println("Unable to generate JWT for sign in.", err)
} else {
  fmt.Println("Successfully generated JWT for sign in.")
  fmt.Println(authInfo.SessionToken.JWT)
  fmt.Println(authInfo.RefreshToken.JWT)
}
// Args:
//   loginId (String): The login ID of the existing user to sign in (required).
//   loginOptions (LoginOptions): Optional, options to customize the generated session
JwtService jwts = descopeClient.getManagementServices().getJwtService();
try {
  LoginOptions loginOptions = LoginOptions.builder()
      .customClaims(new HashMap<String, Object>() {{
        put("custom-key1", "custom-value1");
      }})
      .build();
  AuthenticationInfo authInfo = jwts.signIn("user@example.com", loginOptions);
  System.out.println("Successfully generated JWT for sign in.");
  System.out.println(authInfo.getToken().getJwt());
  System.out.println(authInfo.getRefreshToken().getJwt());
} catch (DescopeException de) {
  // Handle the error
}
// Args:
//   LoginId (string): The login ID of the existing user to sign in (required).
//   CustomClaims (GenerateJWTSignInRequest_customClaims): Optional, custom claims to add to the session JWT
//   RefreshDuration (int?): Optional, duration in seconds for which the session will be valid
var customClaims = new GenerateJWTSignInRequest_customClaims();
customClaims.AdditionalData["custom-key1"] = "custom-value1";

var signInRequest = new GenerateJWTSignInRequest
{
    LoginId = "user@example.com",
    CustomClaims = customClaims,
    RefreshDuration = 3600,
};

var signInResponse = await descopeClient.Mgmt.V1.Auth.Signin.PostAsync(signInRequest);
Console.WriteLine("Successfully generated JWT for sign in.");
Console.WriteLine(signInResponse?.SessionJwt);
Console.WriteLine(signInResponse?.RefreshJwt);

Generate JWT for Generic Auth Sign Up

This operation is only for Sign-Up, and if the login ID already exists it will return an error and ask you to sign in the user.

This operation programmatically mints a Descope session (session and refresh JWTs) for a new user independent of a specific auth method. The result is equivalent to that produced by a successful SignUp operation.

This operation is especially useful for backend-driven user migrations, where you have already collected user details from another system and want to seamlessly onboard users into Descope. It allows you to validate the user’s session and issue a Descope token in a single step. This requires a management key and must only be called from trusted server-side code.

Note

You can also perform this operation through the Generate JWT for Sign-Up Management API.

// Args:
//   loginId (string): The login ID of the user to create (required).
//   user (object): Optional, user details such as email, phone, and name.
//   signUpOptions (object): Optional, options to customize the generated session (custom claims, refreshDuration, etc.)
const loginId = "user@example.com"
const user = {
  email: "user@example.com",
  phone: "+15551234567",
  name: "Jane Doe",
}
const signUpOptions = {
  customClaims: {
    "custom-key1": "custom-value1",
  },
  refreshDuration: 3600, // Optional, duration in seconds for which the session will be valid
}

const resp = await descopeClient.management.jwt.signUp(loginId, user, signUpOptions)
if (!resp.ok) {
  console.log("Failed to generate JWT for sign up")
  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 generated JWT for sign up")
  console.log(resp.data.sessionJwt)
  console.log(resp.data.refreshJwt)
}
from descope.management.common import MgmtUserRequest, MgmtSignUpOptions

# Args:
#   login_id (str): The login ID of the user to create (required).
#   user (MgmtUserRequest): Optional, user details such as email, phone, and name.
#   signup_options (MgmtSignUpOptions): Optional, options to customize the generated session
user = MgmtUserRequest(
    name="Jane Doe",
    email="user@example.com",
    phone="+15551234567",
)
signup_options = MgmtSignUpOptions(
    custom_claims={"custom-key1": "custom-value1"},
    refresh_duration=3600,
)

try:
  jwt_response = descope_client.mgmt.jwt.sign_up(
    login_id="user@example.com",
    user=user,
    signup_options=signup_options,
  )
  print("Successfully generated JWT for sign up.")
  print(jwt_response)
except AuthException as error:
  print("Unable to generate JWT for sign up.")
  print("Status Code: " + str(error.status_code))
  print("Error: " + str(error.error_message))
// Args:
//   ctx: context.Context - Application context.
ctx := context.Background()
//   loginID (string): The login ID of the user to create (required).
loginID := "user@example.com"
//   user (*descope.MgmtUserRequest): Optional, user details such as email, phone, and name.
user := &descope.MgmtUserRequest{
  User: descope.User{
    Name:  "Jane Doe",
    Email: "user@example.com",
    Phone: "+15551234567",
  },
}
//   signUpOptions (*descope.MgmSignUpOptions): Optional, options to customize the generated session
signUpOptions := &descope.MgmSignUpOptions{
  CustomClaims: map[string]any{
    "custom-key1": "custom-value1",
  },
  RefreshDuration: int32(3600),
}

authInfo, err := descopeClient.Management.JWT().SignUp(ctx, loginID, user, signUpOptions)
if err != nil {
  fmt.Println("Unable to generate JWT for sign up.", err)
} else {
  fmt.Println("Successfully generated JWT for sign up.")
  fmt.Println(authInfo.SessionToken.JWT)
  fmt.Println(authInfo.RefreshToken.JWT)
}
// Args:
//   loginId (String): The login ID of the user to create (required).
//   signUpUserDetails (MgmtSignUpUser): Optional, user details and session options.
JwtService jwts = descopeClient.getManagementServices().getJwtService();
try {
  MgmtSignUpUser signUpUser = MgmtSignUpUser.builder()
      .user(User.builder()
          .name("Jane Doe")
          .email("user@example.com")
          .phone("+15551234567")
          .build())
      .customClaims(new HashMap<String, Object>() {{
        put("custom-key1", "custom-value1");
      }})
      .build();
  AuthenticationInfo authInfo = jwts.signUp("user@example.com", signUpUser);
  System.out.println("Successfully generated JWT for sign up.");
  System.out.println(authInfo.getToken().getJwt());
  System.out.println(authInfo.getRefreshToken().getJwt());
} catch (DescopeException de) {
  // Handle the error
}
// Args:
//   LoginId (string): The login ID of the user to create (required).
//   User (SignUpUser): Optional, user details such as email, phone, and name.
//   CustomClaims (GenerateJWTSignUpRequest_customClaims): Optional, custom claims to add to the session JWT
//   RefreshDuration (int?): Optional, duration in seconds for which the session will be valid
var customClaims = new GenerateJWTSignUpRequest_customClaims();
customClaims.AdditionalData["custom-key1"] = "custom-value1";

var signUpRequest = new GenerateJWTSignUpRequest
{
    LoginId = "user@example.com",
    User = new SignUpUser
    {
        Email = "user@example.com",
        Phone = "+15551234567",
        Name = "Jane Doe",
    },
    CustomClaims = customClaims,
    RefreshDuration = 3600,
};

var signUpResponse = await descopeClient.Mgmt.V1.Auth.Signup.PostAsync(signUpRequest);
Console.WriteLine("Successfully generated JWT for sign up.");
Console.WriteLine(signUpResponse?.SessionJwt);
Console.WriteLine(signUpResponse?.RefreshJwt);

Generate JWT for Generic Auth Sign Up or In

This operation programmatically mints a Descope session (session and refresh JWTs) for a user identified by loginID, creating the user if they do not exist or signing in an existing user if they do, independent of a specific auth method. The result is equivalent to that produced by a successful SignUpOrIn operation.

Use this when you want a single backend code path that works for both first-time and returning users. This requires a management key and must only be called from trusted server-side code.

Note

You can also perform this operation through the Generate JWT for Sign-Up or Sign-In Management API.

// Args:
//   loginId (string): The login ID of the user to sign up or in (required).
//   user (object): Optional, user details such as email, phone, and name (used only if the user is created).
//   signUpOptions (object): Optional, options to customize the generated session (custom claims, refreshDuration, etc.)
const loginId = "user@example.com"
const user = {
  email: "user@example.com",
  phone: "+15551234567",
  name: "Jane Doe",
}
const signUpOptions = {
  customClaims: {
    "custom-key1": "custom-value1",
  },
  refreshDuration: 3600, // Optional, duration in seconds for which the session will be valid
}

const resp = await descopeClient.management.jwt.signUpOrIn(loginId, user, signUpOptions)
if (!resp.ok) {
  console.log("Failed to generate JWT for sign up or in")
  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 generated JWT for sign up or in")
  console.log(resp.data.sessionJwt)
  console.log(resp.data.refreshJwt)
}
from descope.management.common import MgmtUserRequest, MgmtSignUpOptions

# Args:
#   login_id (str): The login ID of the user to sign up or in (required).
#   user (MgmtUserRequest): Optional, user details (used only if the user is created).
#   signup_options (MgmtSignUpOptions): Optional, options to customize the generated session
user = MgmtUserRequest(
    name="Jane Doe",
    email="user@example.com",
    phone="+15551234567",
)
signup_options = MgmtSignUpOptions(
    custom_claims={"custom-key1": "custom-value1"},
    refresh_duration=3600,
)

try:
  jwt_response = descope_client.mgmt.jwt.sign_up_or_in(
    login_id="user@example.com",
    user=user,
    signup_options=signup_options,
  )
  print("Successfully generated JWT for sign up or in.")
  print(jwt_response)
except AuthException as error:
  print("Unable to generate JWT for sign up or in.")
  print("Status Code: " + str(error.status_code))
  print("Error: " + str(error.error_message))
// Args:
//   ctx: context.Context - Application context.
ctx := context.Background()
//   loginID (string): The login ID of the user to sign up or in (required).
loginID := "user@example.com"
//   user (*descope.MgmtUserRequest): Optional, user details (used only if the user is created).
user := &descope.MgmtUserRequest{
  User: descope.User{
    Name:  "Jane Doe",
    Email: "user@example.com",
    Phone: "+15551234567",
  },
}
//   signUpOptions (*descope.MgmSignUpOptions): Optional, options to customize the generated session
signUpOptions := &descope.MgmSignUpOptions{
  CustomClaims: map[string]any{
    "custom-key1": "custom-value1",
  },
  RefreshDuration: int32(3600),
}

authInfo, err := descopeClient.Management.JWT().SignUpOrIn(ctx, loginID, user, signUpOptions)
if err != nil {
  fmt.Println("Unable to generate JWT for sign up or in.", err)
} else {
  fmt.Println("Successfully generated JWT for sign up or in.")
  fmt.Println(authInfo.SessionToken.JWT)
  fmt.Println(authInfo.RefreshToken.JWT)
}
// Args:
//   loginId (String): The login ID of the user to sign up or in (required).
//   signUpUserDetails (MgmtSignUpUser): Optional, user details and session options.
JwtService jwts = descopeClient.getManagementServices().getJwtService();
try {
  MgmtSignUpUser signUpUser = MgmtSignUpUser.builder()
      .user(User.builder()
          .name("Jane Doe")
          .email("user@example.com")
          .phone("+15551234567")
          .build())
      .customClaims(new HashMap<String, Object>() {{
        put("custom-key1", "custom-value1");
      }})
      .build();
  AuthenticationInfo authInfo = jwts.signUpOrIn("user@example.com", signUpUser);
  System.out.println("Successfully generated JWT for sign up or in.");
  System.out.println(authInfo.getToken().getJwt());
  System.out.println(authInfo.getRefreshToken().getJwt());
} catch (DescopeException de) {
  // Handle the error
}
// Args:
//   LoginId (string): The login ID of the user to sign up or in (required).
//   User (SignUpUser): Optional, user details (used only if the user is created).
//   CustomClaims (GenerateJWTSignUpRequest_customClaims): Optional, custom claims to add to the session JWT
//   RefreshDuration (int?): Optional, duration in seconds for which the session will be valid
var customClaims = new GenerateJWTSignUpRequest_customClaims();
customClaims.AdditionalData["custom-key1"] = "custom-value1";

var signUpOrInRequest = new GenerateJWTSignUpRequest
{
    LoginId = "user@example.com",
    User = new SignUpUser
    {
        Email = "user@example.com",
        Phone = "+15551234567",
        Name = "Jane Doe",
    },
    CustomClaims = customClaims,
    RefreshDuration = 3600,
};

var signUpOrInResponse = await descopeClient.Mgmt.V1.Auth.SignupIn.PostAsync(signUpOrInRequest);
Console.WriteLine("Successfully generated JWT for sign up or in.");
Console.WriteLine(signUpOrInResponse?.SessionJwt);
Console.WriteLine(signUpOrInResponse?.RefreshJwt);

Generate Client Assertion JWT for OAuth

Note

You can learn more about Private Key JWT authentication here.

This operation mints a short-lived, signed client assertion JWT that your application can use to authenticate itself to an OAuth 2.0 authorization server (for example, in the private_key_jwt client authentication method or the client credentials flow). Instead of sending a static client secret, your backend presents this signed JWT as proof of the client's identity. This requires a management key and must only be called from trusted server-side code.

// Args:
//   issuer (string): The issuer of the JWT, typically the client ID (required).
//   subject (string): The subject of the JWT, typically the client ID (required).
//   audience (string[]): The intended audience, typically the authorization server token endpoint (required).
//   expiresIn (number): Number of seconds the token will be valid for (required).
//   flattenAudience (boolean): Optional, set the audience claim as a single string instead of an array (when only one value is provided).
//   algorithm (string): Optional, signing algorithm - one of 'RS256', 'RS384', 'ES384' (default is 'RS256').
const issuer = "https://example.com/issuer"
const subject = "client-id-123"
const audience = ["https://example.com/token"]
const expiresIn = 300
const flattenAudience = false
const algorithm = "RS256"

const resp = await descopeClient.management.jwt.generateClientAssertionJwt(
  issuer,
  subject,
  audience,
  expiresIn,
  flattenAudience,
  algorithm,
)
if (!resp.ok) {
  console.log("Failed to generate client assertion JWT")
  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 generated client assertion JWT")
  console.log(resp.data.jwt)
}
// Args:
//   issuer (String): The issuer of the JWT, typically the client ID (required).
//   subject (String): The subject of the JWT, typically the client ID (required).
//   audience (List<String>): The intended audience, typically the authorization server (required).
//   expiresIn (Integer): Expiration time in seconds (required).
//   flattenAudience (Boolean): Optional, flatten the audience array to a single string.
//   algorithm (String): Optional, signing algorithm - one of RS256, RS384, or ES384.
JwtService jwts = descopeClient.getManagementServices().getJwtService();
try {
  ClientAssertionResponse response = jwts.generateClientAssertionJwt(
      "client-id",
      "client-id",
      Arrays.asList("https://auth.example.com/token"),
      3600,
      false,
      "RS256");
  System.out.println("Successfully generated client assertion JWT.");
  System.out.println(response.getJwt());
} catch (DescopeException de) {
  // Handle the error
}
Was this helpful?

On this page