Skip to content

Repository files navigation

CI

Descope SDK for Java

The Descope SDK for Java provides convenient access to the Descope user management and authentication API for a backend written in Java. You can read more on the Descope Website.

Requirements

The SDK supports Java version 8 and above.

Installing the SDK

Using maven add the following dependency to your pom.xml:

<dependencies>
    ...
    <dependency>
        <artifactId>java-sdk</artifactId>
        <groupId>com.descope</groupId>
        <version>[1.0.0,)</version>
    </dependency>
    ...
</dependencies>

Setup

A Descope Project ID is required to initialize the SDK. Find it on the project page in the Descope Console.

import com.descope.client;

// Initialized after setting the DESCOPE_PROJECT_ID env var (and optionally DESCOPE_MANAGEMENT_KEY)
// We can also take these variables from .env file in the running directory
var descopeClient = new DescopeClient();

// ** Or directly **
var descopeClient = new DescopeClient(Config.builder().projectId("Your-project").build());

Auth Management Key

Authentication methods whose public access has been disabled can still be used by providing an auth management key. When set, it is sent along with every authentication request.

Create one in the Descope Console with either the Authentication or Full Access scope on the project or company.

// Initialized after setting the DESCOPE_AUTH_MANAGEMENT_KEY env var
var descopeClient = new DescopeClient();

// ** Or directly **
var descopeClient = new DescopeClient(Config.builder()
        .projectId("Your-project")
        .authManagementKey("auth-management-key")
        .build());

Note: the auth management key can, and probably should, be a different management key than the one provided for management API usage. The auth management key is never sent on management requests, and the management key is never sent on authentication requests.

Authentication Functions

These sections show how to use the SDK to perform various authentication/authorization functions:

  1. OTP Authentication
  2. Magic Link
  3. Enchanted Link
  4. NOTP (WhatsApp)
  5. OAuth
  6. SSO/SAML
  7. TOTP Authentication
  8. Recovery Codes
  9. Passwords
  10. Email Verification
  11. Session Validation
  12. Roles & Permission Validation
  13. Logging Out

Management Functions

These sections show how to use the SDK to perform API management functions. Before using any of them, you will need to create a Management Key. The instructions for this can be found under Setup.

  1. Manage Tenants
  2. Manage Users
  3. Manage Access Keys
  4. Manage SSO Setting
  5. Manage Permissions
  6. Manage Roles
  7. Query SSO Groups
  8. Manage Flows
  9. Manage JWTs
  10. Audit
  11. FGA (Fine-Grained Authorization)
  12. Manage Outbound Applications
  13. Manage Inbound Applications
  14. Manage Engines
  15. Manage Project
  16. Manage Descopers
  17. Manage Auth Access Policy
  18. Manage Project Secrets
  19. Manage Families
  20. Analytics
  21. Manage Agentic Identities and Governance
  22. Manage Dynamic Registration Templates
  23. Manage SCIM Keys
  24. Manage Scope Claim Mapping
  25. Manage Session Classifications

If you wish to run any of our code samples and play with them, check out our Code Examples section.

If you're developing unit tests, see how you can use our mocks package underneath the Unit Testing and Data Mocks section.

If you're performing end-to-end testing, check out the Utils for your end to end (e2e) tests and integration tests section. You will need to use the descopeClient object created under Setup guide.

For rate limiting information, please confer to the API Rate Limits section.


OTP Authentication

Send a user a one-time password (OTP) using your preferred delivery method (email / SMS / Voice call / WhatsApp). An email address or phone number must be provided accordingly.

The user can either sign up, sign in or sign up or in

// Every user must have a loginID. All other user information is optional
String loginId = "desmond@descope.com"
User user = User.builder()
    .name("Desmond Copeland")
    .phone("212-555-1234")
    .email(loginId)
    .build();
OTPService otps = descopeClient.getAuthenticationServices().getOTPService();
try {
  String maskedAddress = otps.signUp(DeliveryMethod.EMAIL, loginId, user);
} catch (DescopeException de) {
  // Handle the error
}

The user will receive a code using the selected delivery method. Verify that code using:

// Will throw DescopeException if there is an error with update
try {
  AuthenticationInfo info = otps.verifyCode(DeliveryMethod.EMAIL, loginId, code);
} catch (DescopeException de) {
  // Handle the error
}

The session and refresh JWTs should be returned to the caller, and passed with every request in the session. Read more on session validation

Magic Link

Send a user a Magic Link using your preferred delivery method (email / SMS / WhatsApp). The Magic Link will redirect the user to page where the its token needs to be verified. This redirection can be configured in code, or globally in the Descope Console

The user can either sign up, sign in or sign up or in

// If configured globally, the redirect URI is optional. If provided however, it will be used
// instead of any global configuration

// Every user must have a loginID. All other user information is optional
String loginId = "desmond@descope.com"
User user = User.builder()
    .name("Desmond Copeland")
    .phone("212-555-1234")
    .email(loginId)
    .build();

MagicLinkService mls = descopeClient.getAuthenticationServices().getMagicLinkService();

try {
    String uri = "http://myapp.com/verify-magic-link";
    String maskedAddress = mls.signUp(DeliveryMethod.EMAIL, loginId, uri, user);
} catch (DescopeException de) {
    // Handle the error
}

To verify a magic link, your redirect page must call the validation function on the token (t) parameter (https://your-redirect-address.com/verify?t=<token>):

try {
    AuthenticationInfo info = mls.verify(token);
} catch (DescopeException de) {
    // Handle the error
}

The session and refresh JWTs should be returned to the caller, and passed with every request in the session. Read more on session validation

Enchanted Link

Using the Enchanted Link APIs enables users to sign in by clicking a link delivered to their email address. The email will include 3 different links, and the user will have to click the right one, based on the 2-digit number that is displayed when initiating the authentication process.

This method is similar to Magic Link but differs in two major ways:

  • The user must choose the correct link out of the three, instead of having just one single link.
  • This supports cross-device clicking, meaning the user can try to log in on one device, like a computer, while clicking the link on another device, for instance a mobile phone.

The Enchanted Link will redirect the user to page where the its token needs to be verified. This redirection can be configured in code per request, or set globally in the Descope Console.

The user can either sign up, sign in or sign up or in

// If configured globally, the redirect URI is optional. If provided however, it will be used
// instead of any global configuration.

EnchantedLinkService els = descopeClient.getAuthenticationServices().getEnchantedLinkService();
EnchantedLinkResponse res = null;
try {
    String uri = "http://myapp.com/verify-enchanted-link";
    res = els.signUp(loginId, uri, user);
} catch (DescopeException de) {
    // Handle the error
}

To deliver the enchanted link by SMS, use the WithPhone variants, which take a phone number as the login ID and return a PhoneEnchantedLinkResponse carrying maskedPhone. The SMS carries only the correct link, so there is nothing for the user to choose.

PhoneEnchantedLinkResponse res = null;
try {
    String uri = "http://myapp.com/verify-enchanted-link";
    res = els.signUpOrInWithPhone(phoneNumber, uri);
} catch (DescopeException de) {
    // Handle the error
}

After sending the link, you must poll to receive a valid session using the PendingRef from the previous step. A valid session will be returned only after the user clicks the right link.

// Poll for a certain number of tries / time frame
for (int i = retriesCount; i > 0; i--) {
    try {
        AuthenticationInfo info = els.getSession(res.getPendingRef());
    } catch (DescopeException de) {
        if (i > 1) {
            // Poll again after X seconds
            TimeUnit.SECONDS.sleep(retryInterval);
            continue;
        }
        else {
            // Handle the error
            break;
        }
    }
}

To verify an enchanted link, your redirect page must call the validation function on the token (t) parameter (https://your-redirect-address.com/verify?t=<token>). Once the token is verified, the session polling will receive a valid response.

try {
    els.verify(token);
} catch (DescopeException de) {
    // Token is invalid, handle the error
}

The session and refresh JWTs should be returned to the caller, and passed with every request in the session. Read more on session validation

NOTP (WhatsApp)

Using NOTP, users authenticate by sending a message from their own phone through a messaging provider (currently WhatsApp) instead of receiving a code. Start the process with sign up, sign in or sign up or in, then show the user the returned redirectUrl (a link to the provider app) or the QR code image. The login ID is optional for sign in and sign up or in, since it can be taken from the message.

NOTPService ns = descopeClient.getAuthenticationServices().getNotpService();
NOTPResponse res = null;
try {
    res = ns.signUpOrIn(NOTPProvider.WHATSAPP, "+12025550123");
    // Or: ns.signUp(NOTPProvider.WHATSAPP, "+12025550123", user)
    // Or: ns.signIn(NOTPProvider.WHATSAPP, "+12025550123", loginOptions)
    String redirectUrl = res.getRedirectUrl();
    String qrCodeImage = res.getImage();
} catch (DescopeException de) {
    // Handle the error
}

Then poll for a valid session using the pendingRef. A session is returned only after the user sent the message.

// Poll for a certain number of tries / time frame
for (int i = retriesCount; i > 0; i--) {
    try {
        AuthenticationInfo info = ns.getSession(res.getPendingRef());
        break;
    } catch (DescopeException de) {
        if (i > 1) {
            // Poll again after X seconds
            TimeUnit.SECONDS.sleep(retryInterval);
            continue;
        }
        else {
            // Handle the error
            break;
        }
    }
}

A signed-in user can update their phone the same way, using their refresh token.

try {
    UpdateOptions updateOptions = new UpdateOptions(true, false); // add to login IDs, don't merge
    NOTPResponse res = ns.updateUserPhone(NOTPProvider.WHATSAPP, loginId, "+12025550123", refreshToken,
        updateOptions);
    // Show res.getRedirectUrl() or res.getImage(), then poll ns.getSession(res.getPendingRef())
} catch (DescopeException de) {
    // Handle the error
}

OAuth

Users can authenticate using their social logins, using the OAuth protocol. Configure your OAuth settings on the Descope console. To start a flow call:

// Choose an oauth provider out of the supported providers
// If configured globally, the return URL is optional. If provided however, it will be used
// instead of any global configuration.
// Redirect the user to the returned URL to start the OAuth redirect chain
OAuthService oas = descopeClient.getAuthenticationServices().getOAuthService();

try {
    String returnUrl = "https://my-app.com/handle-oauth";
    oas.start("google", returnUrl, loginOptions);
} catch (DescopeException de) {
    // Handle the error
}

// For step-up or MFA, pass the user's current refresh JWT in the login options
try {
    String returnUrl = "https://my-app.com/handle-oauth";
    String refreshToken = "user-refresh-jwt"; // the user's current refresh JWT
    LoginOptions stepUpOptions = LoginOptions.builder().stepup(true).jwt(refreshToken).build();
    oas.start("google", returnUrl, stepUpOptions);
} catch (DescopeException de) {
    // Handle the error
}

The user will authenticate with the authentication provider, and will be redirected back to the redirect URL, with an appended code HTTP URL parameter. Exchange it to validate the user:

try {
    AuthenticationInfo info = oas.exchangeToken(code);
} catch (DescopeException de) {
    // Handle the error
}

The session and refresh JWTs should be returned to the caller, and passed with every request in the session. Read more on session validation

When info.getSsoAuthenticationOnly() is true (OAuth, SAML or SSO login through an authentication-only configuration), no session was issued and info.getToken() is null: do not treat the result as a login.

SSO/SAML

Users can authenticate to a specific tenant using SAML or Single Sign On. Configure your SSO/SAML settings on the Descope console. To start a flow call:

// Choose which tenant to log into
// Redirect the user to the returned URL to start the SSO/SAML redirect chain
SAMLService ss = descopeClient.getAuthenticationServices().getSAMLService();

try {
    String returnURL = "https://my-app.com/handle-saml";
    String url = ss.start("my-tenant-ID", returnURL, loginOptions);
} catch (DescopeException de) {
    // Handle the error
}

The user will authenticate with the authentication provider configured for that tenant, and will be redirected back to the redirect URL, with an appended code HTTP URL parameter. Exchange it to validate the user:

// The optional `w http.ResponseWriter` adds the session and refresh cookies to the response automatically.
// Otherwise they're available via authInfo
try {
    String url = ss.exchangeToken(code);
} catch (DescopeException de) {
    // Handle the error
}

The session and refresh JWTs should be returned to the caller, and passed with every request in the session. Read more on session validation

When info.getSsoAuthenticationOnly() is true (login through an authentication-only SSO configuration), no session was issued and info.getToken() is null: do not treat the result as a login.

TOTP Authentication

The user can authenticate using an authenticator app, such as Google Authenticator. Sign up like you would using any other authentication method. The sign up response will then contain a QR code Image that can be displayed to the user to scan using their mobile device camera app, or the user can enter the Key manually or click on the link provided by the ProvisioningURL.

Existing users can add TOTP using the update function.

// Every user must have a loginID. All other user information is optional
String loginId = "desmond@descope.com"
User user = User.builder()
    .name("Desmond Copeland")
    .phone("212-555-1234")
    .email(loginId)
    .build();

TOTPService ts = descopeClient.getAuthenticationServices().getTOTPService();

try {
    TOTPResponse resp = ts.signUp(loginId, user);
} catch (DescopeException de) {
    // Handle the error
}

// Use one of the provided options to have the user add their credentials to the authenticator
// resp.getProvisioningURL()
// resp.getImage()
// resp.getKey()

There are 3 different ways to allow the user to save their credentials in their authenticator app - either by clicking the provisioning URL, scanning the QR image or inserting the key manually. After that, signing in is done using the code the app produces.

// The optional `w http.ResponseWriter` adds the session and refresh cookies to the response automatically.
// Otherwise they're available via authInfo
try {
    AuthenticationInfo info = ts.signInCode(loginId, code, loginOptions);
} catch (DescopeException de) {
    // Handle the error
}

The session and refresh JWTs should be returned to the caller, and passed with every request in the session. Read more on session validation

Recovery Codes

A signed-in user can generate a new set of recovery codes, to be shown to them once and kept somewhere safe.

RecoveryCodesService rcs = descopeClient.getAuthenticationServices().getRecoveryCodesService();

try {
    // The refresh token of the signed-in user is required
    RecoveryCodesResponse resp = rcs.generate("desmond@descope.com", refreshToken);
    for (RecoveryCode code : resp.getCodes()) {
        // code.getCode()
    }
} catch (DescopeException de) {
    // Handle the error
}

Passwords

The user can also authenticate with a password, though it's recommended to prefer passwordless authentication methods if possible. Sign up requires the caller to provide a valid password that meets all the requirements configured for the password authentication method in the Descope console.

// Every user must have a loginID. All other user information is optional
String loginId = "desmond@descope.com";
User user = User.builder()
    .name("Desmond Copeland")
    .phone("212-555-1234")
    .email(loginId)
    .build();
String password = "qYlvi65KaX";

PasswordService ps = descopeClient.getAuthenticationServices().getPasswordService();

try {
    AuthenticationInfo info = ps.signUp(loginId, user, password);
} catch (DescopeException de) {
    // Handle the error
}

The user can later sign in using the same loginID and password.

try {
    AuthenticationInfo info = ps.signIn(loginId, password);
} catch (DescopeException de) {
    // Handle the error
}

The session and refresh JWTs should be returned to the caller, and passed with every request in the session. Read more on session validation

In case the user needs to update their password, one of two methods are available: Resetting their password or replacing their password

Changing Passwords

NOTE: SendPasswordReset will only work if the user has a validated email address. Otherwise password reset prompts cannot be sent.

In the password authentication method in the Descope console, it is possible to define which alternative authentication method can be used in order to authenticate the user, in order to reset and update their password.

// Start the reset process by sending a password reset prompt. In this example we'll assume
// that magic link is configured as the reset method. The optional redirect URL is used in the
// same way as in regular magic link authentication.
PasswordService ps = descopeClient.getAuthenticationServices().getPasswordService();
String loginId = "desmond@descope.com";
String redirectUrl = "https://myapp.com/password-reset";
try {
    ps.sendPasswordReset(loginId, redirectUrl);
} catch (DescopeException de) {
    // Handle the error
}

The magic link, in this case, must then be verified like any other magic link (see the magic link section for more details). However, after verifying the user, it is expected to allow them to provide a new password instead of the old one. Since the user is now authenticated, this is possible with the refresh token received from the verify:

try {
    ps.updateUserPassword(loginId, newPassword, refreshToken);
} catch (DescopeException de) {
    // Handle the error
}

UpdateUserPassword can always be called when the user is authenticated and has a valid session.

Alternatively, it is also possible to replace an existing active password with a new one.

// Replaces the user's current password with a new one
try {
    AuthenticationInfo info = ps.replaceUserPassword(loginId, oldPassword, newPassword);
} catch (DescopeException de) {
    // Handle the error
}

Email Verification

Get a single-use nonce for the hidden email-verification-token input of a sign-in page. The browser binds it into the email verification token it issues, so the token can only be redeemed once and only for this project. This is in beta, and available when the project enabled Email Verification.

EmailVerificationService evs = descopeClient.getAuthenticationServices().getEmailVerificationService();

try {
    EmailVerificationStartResponse resp = evs.start();
    // Use resp.getNonce() for the sign-in page's hidden email-verification-token input
} catch (DescopeException de) {
    // Handle the error
}

Session Validation

Every secure request performed between your client and server needs to be validated.

Tokens can be validated directly:

// Validate the session. Will return an error if expired
AuthenticationService as = descopeClient.getAuthenticationServices().getAuthenticationService();
try {
    Token t = as.validateSessionWithToken(sessionToken);
} catch (DescopeException de) {
    // Handle the unauthorized error
}

// If ValidateSessionWithRequest raises an exception, you will need to refresh the session using
try {
    Token t = as.refreshSessionWithToken(refreshToken);
} catch (DescopeException de) {
    // Handle the unauthorized error
}

// Alternatively, you could combine the two and
// have the session validated and automatically refreshed when expired
try {
    Token t = as.validateAndRefreshSessionWithTokens(sessionToken, refreshToken);
} catch (DescopeException de) {
    // unauthorized error
}

// Exchange an access key for a session token. Use exchangeAccessKeyWithResponse
// to also get the ID of the access key
try {
    ExchangeAccessKeyResponse resp = as.exchangeAccessKeyWithResponse(accessKey,
            new AccessKeyLoginOptions(mapOf("k", "v")));
    Token t = resp.getToken();
    String keyId = resp.getKeyId();
} catch (DescopeException de) {
    // unauthorized error
}

Choose the right session validation and refresh combination that suits your needs.

Refreshed sessions return the same response as is returned when users first sign up / log in, Make sure to return the session token from the response to the client if tokens are validated directly.

Usually, the tokens can be passed in and out via HTTP headers or via a cookie. The implementation can defer according to your implementation. See our examples for a few examples.

If Roles & Permissions are used, validate them immediately after validating the session. See the next section for more information.

Session Validation Using Middleware

Alternatively, you can validate the session using Spring Framework middleware. See example using java-spring.

Tenant selection

For a user that has permissions to multiple tenants, you can set a specific tenant as the current selected one This will add an extra attribute to the refresh JWT and the session JWT with the selected tenant ID

AuthenticationService as = descopeClient.getAuthenticationServices().getAuthService();
try {
    String tenantId = "t1";
    AuthenticationInfo jwtResponse = as.selectTenant(tenantId, refreshToken);
    // Use jwtResponse.getToken().getJwt() and jwtResponse.getRefreshToken().getJwt()
} catch (DescopeException de) {
    // Handle the error
}

Roles & Permission Validation

When using Roles & Permission, it's important to validate the user has the required authorization immediately after making sure the session is valid. Taking the sessionToken received by the session validation, call the following functions:

For multi-tenant uses:

// You can validate specific permissions
AuthenticationService as = descopeClient.getAuthenticationServices().getAuthenticationService();
try {
    if (!as.validatePermissions(sessionToken, "my-tenant-ID", Arrays.asList("Permission to validate"))) {
        // Deny access
    }
} catch (DescopeException de) {
    // Handle the error
}

// Or validate roles directly
try {
    if (!as.validateRoles(sessionToken, "my-tenant-ID", Arrays.asList("Role to validate"))) {
        // Deny access
    }
} catch (DescopeException de) {
    // Handle the error
}

// Or get the matched roles/permissions
List<String> matchedPermissions = as.getMatchedPermissions(sessionToken, "my-tenant-ID", Arrays.asList("Permission1", "Permission2"));

List<String> matchedRoles = as.getMatchedRoles(sessionToken, "my-tenant-ID", Arrays.asList("Role1", "Role2"));

When not using tenants use:

// You can validate specific permissions
AuthenticationService as = descopeClient.getAuthenticationServices().getAuthenticationService();
try {
    if (!as.validatePermissions(sessionToken, Arrays.asList("Permission to validate"))) {
        // Deny access
    }
} catch (DescopeException de) {
    // Handle the error
}

// Or validate roles directly
try {
    if (!as.validateRoles(sessionToken, Arrays.asList("Role to validate"))) {
        // Deny access
    }
} catch (DescopeException de) {
    // Handle the error
}

// Or get the matched roles/permissions
List<String> matchedPermissions = as.getMatchedPermissions(sessionToken, Arrays.asList("Permission1", "Permission2"));

List<String> matchedRoles = as.getMatchedRoles(sessionToken, Arrays.asList("Role1", "Role2"));

Logging Out

You can log out a user from an active session by providing their refreshToken for that session. After calling this function, you must invalidate or remove any cookies you have created.

AuthenticationService as = descopeClient.getAuthenticationServices().getAuthenticationService();
try {
    as.logout(refreshToken);
} catch (DescopeException de) {
    // Handle the error
}

To also log the user out of their SSO identity provider, pass LogoutOptions with ssoLogout. When the session signed in through a SAML SSO configuration with single logout on, the response's ssoLogoutUrl is set, and you must send the browser there. The optional redirectUrl is where the browser lands afterwards; it must be in the project's approved domains, and when empty the SSO configuration's redirect URL is used. The Descope session ends either way.

try {
    LogoutResponse res = as.logout(refreshToken,
        LogoutOptions.builder().ssoLogout(true).redirectUrl("https://app.example.com/signed-out").build());
    if (StringUtils.isNotBlank(res.getSsoLogoutUrl())) {
        // Redirect the browser to res.getSsoLogoutUrl()
    }
} catch (DescopeException de) {
    // Handle the error
}

It is also possible to sign the user out of all the devices they are currently signed-in with. Calling logoutAll will invalidate all user's refresh tokens. After calling this function, you must invalidate or remove any cookies you have created.

try {
    as.logoutAll(refreshToken);
} catch (DescopeException de) {
    // Handle the error
}

To also log the user out of their SSO identity provider, pass LogoutOptions with ssoLogout. When the session signed in through a SAML SSO configuration with single logout on, send the browser to the returned ssoLogoutUrl.

try {
    LogoutResponse res = as.logoutAll(refreshToken, LogoutOptions.builder()
        .ssoLogout(true)
        .redirectUrl("https://app.example.com/signed-out") // must be in the project's approved domains
        .build());
    if (StringUtils.isNotBlank(res.getSsoLogoutUrl())) {
        // Redirect the browser to res.getSsoLogoutUrl()
    }
} catch (DescopeException de) {
    // Handle the error
}

Management Functions

It is very common for some form of management or automation to be required. These can be performed using the management functions. Please note that these actions are more sensitive as they are administrative in nature. Please use responsibly.

Setup

To use the management API you'll need a Management Key along with your Project ID. Create one in the Descope Console. This key is used only for management functions - to reach authentication methods whose public access has been disabled, use the Auth Management Key instead.

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("Your-project")
        .managementKey("management-key")
        .build());

Manage Tenants

You can create, update, delete or load tenants:

TenantService ts = descopeClient.getManagementServices().getTenantService();
// The self provisioning domains or optional. If given they'll be used to associate
// Users logging in to this tenant
try {
    ts.create("My Tenant", Arrays.asList("domain.com"), new HashMap<String, Object>() {{
                put("custom-attribute-1", "custom-value1");
                put("custom-attribute-2", "custom-value2");
            }});
} catch (DescopeException de) {
    // Handle the error
}

// You can optionally set your own ID when creating a tenant
try {
    ts.createWithId("my-custom-id", "My Tenant", Arrays.asList("domain.com"), new HashMap<String, Object>() {{
                put("custom-attribute-1", "custom-value1");
                put("custom-attribute-2", "custom-value2");
            }});
} catch (DescopeException de) {
    // Handle the error
}

// Update will override all fields as is. Use carefully.
try {
    ts.update("my-custom-id", "My Tenant", Arrays.asList("domain.com", "another-domain.com"), new HashMap<String, Object>() {{
                put("custom-attribute-1", "custom-value1");
                put("custom-attribute-2", "custom-value2");
            }});
} catch (DescopeException de) {
    // Handle the error
}

// Create a tenant with all its settings, as a sub-tenant of "parent-tenant-id"
try {
    String tenantId = ts.create(CreateTenantRequest.builder()
            .name("My Tenant")
            .parent("parent-tenant-id")
            .selfProvisioningDomains(Arrays.asList("domain.com"))
            .approvedDomains(Arrays.asList("vanity.example.com"))
            .enforceSSOExclusionPermissions(Arrays.asList("SSO Exempt"))
            .permittedIps(Arrays.asList("10.0.0.0/8"))
            .roleInheritance(TenantRoleInheritance.USER_ONLY.getValue())
            .strict(true) // fail on custom attributes the project does not declare
            .build());
} catch (DescopeException de) {
    // Handle the error
}

// Create up to 100 tenants in one call; failed tenants are returned without failing the others
try {
    CreateTenantsBatchResponse res = ts.createBatch(Arrays.asList(
            CreateTenantRequest.builder().name("Tenant A").build(),
            CreateTenantRequest.builder().name("Tenant B").build()), null);
    for (CreateTenantBatchFailureResponse failed : res.getFailedTenants()) {
        // failed.getFailure(), failed.getTenant()
    }
} catch (DescopeException de) {
    // Handle the error
}

// Update replaces the tenant's settings: unset fields are cleared, except approvedDomains
try {
    ts.update(UpdateTenantRequest.builder()
            .id("my-custom-id")
            .name("My Tenant")
            .approvedDomains(Arrays.asList("vanity.example.com"))
            .enforceSSOExclusionPermissions(Arrays.asList("SSO Exempt"))
            .permittedIps(Arrays.asList("10.0.0.0/8"))
            .build());
} catch (DescopeException de) {
    // Handle the error
}

// Update up to 100 tenants in one call
try {
    UpdateTenantsBatchResponse res = ts.updateBatch(Arrays.asList(
            UpdateTenantRequest.builder().id("tenant-a").name("Tenant A").build(),
            UpdateTenantRequest.builder().id("tenant-b").name("Tenant B").build()), null);
} catch (DescopeException de) {
    // Handle the error
}

// Patch changes only the fields that are set
try {
    ts.patch("my-custom-id", PatchTenantRequest.builder()
            .disabled(true)
            .permittedIps(Arrays.asList("10.0.0.1"))
            .build());
} catch (DescopeException de) {
    // Handle the error
}

// Tenant deletion cannot be undone. Use carefully.
try {
    ts.delete("my-custom-id");
    // Or cascade the deletion
    ts.delete("my-custom-id", true);
} catch (DescopeException de) {
    // Handle the error
}

// Delete up to 100 tenants in one call
try {
    DeleteTenantsBatchResponse res = ts.deleteBatch(Arrays.asList("tenant-a", "tenant-b"), false);
} catch (DescopeException de) {
    // Handle the error
}

// Load a tenant
try {
    Tenant tenant = ts.load("my-custom-id");
    // tenant.getParent(), tenant.getSuccessors(), tenant.getApprovedDomains(), tenant.getPermittedIps()...
} catch (DescopeException de) {
    // Handle the error
}

// Load all tenants
try {
    List<Tenant> tenants = ts.loadAll();
    for (Tenant t : tenants) {
        // Do something
    }
} catch (DescopeException de) {
    // Handle the error
}

// Search tenants
try {
    List<Tenant> tenants = ts.searchAll(TenantSearchRequest.builder()
            .ids(Arrays.asList("my-custom-id"))
            .names(Arrays.asList("My Tenant"))
            .customAttributes(Map.of("custom-attribute-1", "custom-value1"))
            .selfProvisioningDomains(Arrays.asList("domain.com", "another-domain.com")).build());
    for (Tenant t : tenants) {
        // Do something
    }
} catch (DescopeException de) {
    // Handle the error
}

// Search the top level tenants, the sub-tenants of a parent, or by SSO domains
try {
    List<Tenant> tenants = ts.searchAll(TenantSearchRequest.builder()
            .ssoDomains(Arrays.asList("sso.domain.com"))
            .parentTenantId("parent-tenant-id")
            .topLevelOnly(false)
            .build());
} catch (DescopeException de) {
    // Handle the error
}

// Load and configure the tenant settings, including step-up token expiration and the SSO Setup Suite
try {
    TenantSettings current = ts.getSettings("my-custom-id");
    // Only the settings that are set are sent
    ts.configureSettings("my-custom-id", TenantSettings.builder()
            .stepupTokenExpiration(10)
            .stepupTokenExpirationUnit("minutes")
            .ssoSetupSuiteSettings(SSOSetupSuiteSettings.builder()
                    .enabled(true)
                    .disabledFeatures(SSOSetupSuiteSettingsDisabledFeatures.builder().scim(true).build())
                    .build())
            .build());
} catch (DescopeException de) {
    // Handle the error
}

// Update the default roles applied to users of the tenant
try {
    ts.updateDefaultRoles("my-custom-id", Arrays.asList("Tenant Admin"));
} catch (DescopeException de) {
    // Handle the error
}

Manage Users

You can create, update, delete or load users, as well as search according to filters:

// A user must have a loginID, other fields are optional.
// Roles should be set directly if no tenants exist, otherwise set on a per-tenant basis.
UserService us = descopeClient.getManagementServices().getUserService();
try {
    us.create("desmond@descope.com", UserRequest.builder()
            .email("desmond@descope.com")
            .displayName("Desmond Copeland")
            .userTenants(Arrays.asList(
                AssociatedTenant.builder()
                    .tenantId("tenant-ID1")
                    .roleNames(Arrays.asList("role-name1")).build(),
                AssociatedTenant.builder()
                    .tenantId("tenant-ID2").build()))
            .build());
} catch (DescopeException de) {
    // Handle the error
}

// Alternatively, a user can be created and invited via an email message.
// You can configure the invite URL in the Descope console prior to using this function, or pass inviteUrl in the options parameter.
// and that an email address is provided in the information.
try {
    us.invite("desmond@descope.com",
						UserRequest.builder()
            .email("desmond@descope.com")
            .displayName("Desmond Copeland")
            .userTenants(Arrays.asList(
                AssociatedTenant.builder()
                    .tenantId("tenant-ID1")
                    .roleNames(Arrays.asList("role-name1")).build(),
                AssociatedTenant.builder()
                    .tenantId("tenant-ID2").build()))
            .build(),
			InviteOptions.builder()
				.inviteUrl("https://my-app.com/invite")
                .build());
} catch (DescopeException de) {
    // Handle the error
}

// Update will override all fields as is. Use carefully. Use patch instead if providing select fields.
try {
    us.update("desmond@descope.com", UserRequest.builder()
            .email("desmond@descope.com")
            .displayName("Desmond Copeland")
            .userTenants(Arrays.asList(
                AssociatedTenant.builder()
                    .tenantId("tenant-ID1")
                    .roleNames(Arrays.asList("role-name1")).build(),
                AssociatedTenant.builder()
                    .tenantId("tenant-ID2").build()))
            .build());
} catch (DescopeException de) {
    // Handle the error
}

// Patch will override provided fields but will leave other fields untouched.
try {
    us.patch("desmond@descope.com", PatchUserRequest.builder()
            .name("Desmond Copeland")
            .build());
} catch (DescopeException de) {
    // Handle the error
}

// User deletion cannot be undone. Use carefully.
try {
    us.delete("desmond@descope.com");
} catch (DescopeException de) {
    // Handle the error
}

// Load specific user
try {
    us.load("desmond@descope.com");
} catch (DescopeException de) {
    // Handle the error
}

// If needed, users can be loaded using their ID as well
try {
    us.loadByUserId("<user-id>");
} catch (DescopeException de) {
    // Handle the error
}

// Load multiple users by their IDs, optionally including invalid (e.g. expired or disabled) users
try {
    AllUsersResponseDetails res = us.loadUsers(Arrays.asList("<user-id-1>", "<user-id-2>"), false);
    for (UserResponse u : res.getUsers()) {
        // Do something
    }
} catch (DescopeException de) {
    // Handle the error
}

// Search all users, optionally according to tenant and/or role filter
// Results can be paginated using the limit and page parameters
try {
    List<AllUsersResponsibleDetails> users = us.searchAll(UserRequest.builder()
            .userTenants(Arrays.asList(
                AssociatedTenant.builder()
                    .tenantId("tenant-ID1").build(),
                AssociatedTenant.builder()
                    .tenantId("tenant-ID2").build())).build());
    for (AllUsersResponsibleDetails u : users) {
        // Do something
    }
}

// Delete multiple users at once by their user IDs
try {
    us.deleteBatch(Arrays.asList("<user-id-1>", "<user-id-2>"));
} catch (DescopeException de) {
    // Handle the error
}

// Update a user's recovery email / phone
try {
    us.updateRecoveryEmail("desmond@descope.com", "recovery@descope.com", true);
    us.updateRecoveryPhone("desmond@descope.com", "+1234567890", true);
} catch (DescopeException de) {
    // Handle the error
}

// Manage a user's passkeys (WebAuthn credentials)
try {
    List<UserPasskey> passkeys = us.listPasskeys("desmond@descope.com");
    us.removePasskey("desmond@descope.com", "<credential-id>");
    us.removeAllPasskeys("desmond@descope.com");
} catch (DescopeException de) {
    // Handle the error
}

// Remove a user's TOTP seed (forces re-enrollment)
try {
    us.removeTOTPSeed("desmond@descope.com");
} catch (DescopeException de) {
    // Handle the error
}

// Log out all sessions created in a time range. before and after are optional (at least one is required).
// A null before means the server's current time; prefer it over Instant.now(), since a before in the
// future is rejected. A null after means open-ended. The returned range is what the server stored, which
// may have a later after than requested. Each session is logged out on its next refresh or validation.
// The range stays active for a year.
try {
    LogoutSessionRange range =
        us.logoutSessionsCreatedBetween(null, Instant.now().minus(1, ChronoUnit.HOURS), null);
    List<LogoutSessionRange> ranges = us.listLogoutSessionRanges();
    // Stops logging out matching sessions not logged out yet, sessions already logged out stay logged out
    us.deleteLogoutSessionRange(range.getId());
} catch (DescopeException de) {
    // Handle the error
}

Set or Expire User Password

You can set a new active password for a user, which they can then use to sign in. You can also set a temporary password that the user will be forced to change on the next login.

UserService us = descopeClient.getManagementServices().getUserService();

// Set a temporary user's password
try {
    us.setTemporaryPassword("my-custom-id", "some-password");
} catch (DescopeException de) {
    // Handle the error
}

// Set a user's password
try {
    us.setActivePassword("my-custom-id", "some-password");
} catch (DescopeException de) {
    // Handle the error
}

// Or alternatively, expire a user password
try {
    us.expirePassword("my-custom-id");
} catch (DescopeException de) {
    // Handle the error
}

// Later, if the user is signing in with an expired password, the returned error will be ErrPasswordExpired
PasswordService ps = descopeClient.getAuthenticationServices().getPasswordService();
try {
    AuthenticationInfo info = ps.signIn("my-custom-id", "some-password");
} catch (DescopeException de) {
    // Handle the error
    // Handle a case when the error is expired, the user should replace/reset the password
}

Manage Access Keys

You can create, update, delete or load access keys, as well as search according to filters:

// Roles should be set directly if no tenants exist, otherwise set
// on a per-tenant basis.
AccessKeyService aks = descopeClient.getManagementServices().getAccessKeyService();
try {
    // Create a new access key with a name, delay time, and tenant
    AccessKeyResponse resp = aks.create("access-key-1", 0,
            Arrays.asList("Role names"),
            Arrays.asList(
                new Tenant("tenant-ID1",
                    "Key Tenant",
                    Arrays.asList(new AssociatedTenant("tenant-ID2", Arrays.asList("Role names"))))));
} catch (DescopeException de) {
    // Handle the error
}

// Load specific user
try {
    AccessKeyResponse resp = aks.load("access-key-1");
} catch (DescopeException de) {
    // Handle the error
}

// Search all users, optionally according to tenant and/or role filter
try {
    AccessKeyResponseList resp = aks.searchAll(Arrays.asList("Tenant IDs"));
    for (AccessKeyResponse r : aks.getKeys()) {
        // Do something
    }
} catch (DescopeException de) {
    // Handle the error
}

// Search access keys with more filters and a sort order
try {
    AccessKeyResponseList resp = aks.search(AccessKeySearchRequest.builder()
            .tenantIds(Arrays.asList("tenant-ID1"))
            .text("access-key")
            .boundUserId("bound-user-id")
            .creatingUser("creating-user-id")
            .customAttributes(mapOf("attr1", "value1"))
            .sort(Arrays.asList(SortField.builder().field("createdTime").desc(true).build()))
            .build());
    for (AccessKeyResponseDetails key : resp.getKeys()) {
        // Each key also carries getBoundUserId(), getCustomClaims() and getCustomAttributes()
    }
} catch (DescopeException de) {
    // Handle the error
}

// Create an access key with custom attributes
try {
    AccessKeyResponse resp = aks.create(AccessKeyRequest.builder()
            .name("access-key-1")
            .customAttributes(mapOf("attr1", "value1"))
            .build());
} catch (DescopeException de) {
    // Handle the error
}

// Update will override all fields as is. Use carefully.
try {
    AccessKeyResponse resp = aks.update("access-key-1", "updated-name");
} catch (DescopeException de) {
    // Handle the error
}

// Replace the key's tenants and custom attributes. An empty tenant list clears the tenants;
// keyTenants can't be combined with non-empty roleNames.
try {
    AccessKeyResponse resp = aks.update(AccessKeyUpdateRequest.builder()
            .id("access-key-1")
            .name("updated-name")
            .customAttributes(mapOf("attr1", "value1"))
            .keyTenants(MgmtUtils.createAssociatedTenantList(Arrays.asList(
                AssociatedTenant.builder().tenantId("tenant-ID1").roleNames(Arrays.asList("Role names")).build())))
            .build());
} catch (DescopeException de) {
    // Handle the error
}

// Access keys can be deactivated to prevent usage. This can be undone using "activate".
try {
    AccessKeyResponse resp = aks.deactivate("access-key-1");
} catch (DescopeException de) {
    // Handle the error
}

// Disabled access keys can be activated once again.
try {
    AccessKeyResponse resp = aks.activate("access-key-1");
} catch (DescopeException de) {
    // Handle the error
}

// Access key deletion cannot be undone. Use carefully.
try {
    aks.delete("access-key-1");
} catch (DescopeException de) {
    // Handle the error
}

// Rotate an access key - the previous cleartext becomes invalid and a new one is returned.
try {
    AccessKeyResponse resp = aks.rotate("access-key-1");
} catch (DescopeException de) {
    // Handle the error
}

// Batch operations on multiple access keys at once.
try {
    aks.activateBatch(Arrays.asList("access-key-1", "access-key-2"));
    aks.deactivateBatch(Arrays.asList("access-key-1", "access-key-2"));
    aks.deleteBatch(Arrays.asList("access-key-1", "access-key-2"));
} catch (DescopeException de) {
    // Handle the error
}

Manage SSO Setting

You can manage SSO settings and map SSO group roles and user attributes.

SsoService ss = descopeClient.getManagementServices().getSsoService();
// Load the default SSO settings for a tenant
try {
    SSOTenantSettingsResponse resp = ss.loadSettings("tenant-id");
} catch (DescopeException de) {
    // Handle the error
}

// Load a specific SSO configuration by ssoId (multi-SSO tenants)
try {
    SSOTenantSettingsResponse resp = ss.loadSettings("tenant-id", "sso-config-id");
} catch (DescopeException de) {
    // Handle the error
}

// Load all SSO configurations for a tenant
try {
    SSOAllSettingsResponse resp = ss.loadAllSettings("tenant-id");
    List<SSOTenantSettingsResponse> allConfigs = resp.getSsoSettings();
} catch (DescopeException de) {
    // Handle the error
}

// Configure SSO - SAML
String tenantId = "tenant-id"; // Which tenant this configuration is for
String idpUrl = "https://idp.com";
String entityId = "my-idp-entity-id";
String idpCert = "<your-cert-here>";
String idpMetadataUrl = "https://idp.com/metadata";
String redirectUrl = "https://my-app.com/handle-saml"; // Global redirect URL for SSO/SAML
List<String> domains = Arrays.asList("domain.com"); // Users logging in from this domain will be logged in to this tenant

// Map IDP groups to Descope roles, or map user attributes.
// This function overrides any previous mapping (even when empty). Use carefully.
List<RoleMapping> rm = Arrays.asList(new RoleMapping(Arrays.asList("Groups"), "Tenant Role"));
AttributeMapping am = new AttributeMapping("Tenant Name", "Tenant Email", "Tenant Phone Num", "Tenant Group");


// Using Manual Configuration
SSOSAMLSettings manualSettings = SSOSAMLSettings.builder()
    .idpUrl(idpUrl)
    .entityId(entityId)
    .idpCert(idpCert)
    .attributeMapping(am)
    .roleMappings(rm)
    // Optional - audience values the IdP's SAML assertions may carry in place of the tenant's SP entity ID,
    // for an IdP that sends a different audience and can't be changed. Leave it unset (null) to keep the
    // stored values. Any list replaces them, and an empty list clears them.
    .acceptedAudiences(Arrays.asList("urn:idp:audience"))
    .build();

try {
    ss.configureSAMLSettings(tenantId, manualSettings, redirectUrl, domains);
} catch (DescopeException de) {
    // Handle the error
}

// Using metadata URL
SSOSAMLSettingsByMetadata metadataSettings = SSOSAMLSettingsByMetadata.builder()
    .idpMetadataUrl(idpMetadataUrl)
    .attributeMapping(am)
    .roleMappings(rm)
    .acceptedAudiences(Arrays.asList("urn:idp:audience")) // Optional - same as in the manual configuration
    .build();

try {
    ss.configureSAMLSettingsByMetadata(tenantId, metadataSettings, redirectUrl, domains);
} catch (DescopeException de) {
    // Handle the error
}

// Configure SSO - OIDC
String name = "Provider"; // Name of the provider
String clientId = "<oidc-client-id>"; // The client id set on the IdP
String clientSecret = "<oidc-client-secret>"; // The client secret on the IdP
String redirectUrl = "https://my-app.com/redirect"; // Optional - a custom redirect url
String authUrl = "https://idp.com/auth"; // The IdP's authentication endpoint
String tokenUrl = "https://idp.com/token"; // The IdP's token endpoint
String userDataUrl = "https://idp.com/user"; // The IdP's user endpoint
List<String> scope = Arrays.asList("openid", "profile"); // The scopes
String grantType = "implicit"; // The grant type
List<String> domains = Arrays.asList("domain.com"); // Users logging in from this domain will be logged in to this tenant


SSOOIDCSettings oidcSettings = new SSOOIDCSettings(name, clientId, clientSecret, redirectUrl, authUrl, tokenUrl, userDataUrl, scope, grantType);

try {
    ss.configureOIDCSettings(tenantId, oidcSettings, domains);
} catch (DescopeException de) {
    // Handle the error
}

Note: Certificates should have a similar structure to:

-----BEGIN CERTIFICATE-----
Certifcate contents
-----END CERTIFICATE-----
// To delete SSO settings, call the following method
try {
    ss.deleteSettings(tenantId);
} catch (DescopeException de) {
    // Handle the error
}

// Configure the SAML/OAuth redirect URLs used after SSO authentication
try {
    ss.configureSSORedirectURL(tenantId, "https://my-app.com/handle-saml", "https://my-app.com/handle-oauth", "sso-config-id");
} catch (DescopeException de) {
    // Handle the error
}

// Recalculate the role/attribute mappings for a tenant's SSO configuration
try {
    ss.recalculateSSOMappings(tenantId, "sso-config-id");
} catch (DescopeException de) {
    // Handle the error
}

Manage Permissions

You can create, update, delete or load permissions:

// You can optionally set a description for a permission.
PermissionService ps = descopeClient.getManagementServices().getPermissionService();

String name = "My Permission";
String description = "Optional description to briefly explain what this permission allows.";

try {
    ps.create(name, description);
} catch (DescopeException de) {
    // Handle the error
}

// Update will override all fields as is. Use carefully.
String newName = "My Updated Permission";
description = "A revised description";

try {
    ps.update(name, newName, description);
} catch (DescopeException de) {
    // Handle the error
}

// Permission deletion cannot be undone. Use carefully.
try {
    ps.delete(newName);
} catch (DescopeException de) {
    // Handle the error
}

// Load all permissions
try {
    PermissionResponse resp = ps.loadAll();
    for (Permission p : resp.getPermissions()) {
        String id = p.getId();
        // Do something
    }
} catch (DescopeException de) {
    // Handle the error
}

// Create several permissions in a single request
try {
    ps.createBatch(Arrays.asList(
        Permission.builder().name("Permission A").description("desc A").build(),
        Permission.builder().name("Permission B").build()));
} catch (DescopeException de) {
    // Handle the error
}

// Update or delete a permission by its ID (useful when renaming)
try {
    ps.updateWithId("<permission-id>", "My Updated Permission", "A revised description");
    ps.deleteWithId("<permission-id>");
} catch (DescopeException de) {
    // Handle the error
}

// Update several permissions in a single request
try {
    ps.updateBatch(Arrays.asList(
        PermissionUpdateRequest.builder().id("<permission-id>").newName("Renamed").description("desc").build()));
} catch (DescopeException de) {
    // Handle the error
}

// Delete multiple permissions at once, by name and/or by ID
try {
    ps.deleteBatch(Arrays.asList("Permission A"), Arrays.asList("<permission-id>"));
} catch (DescopeException de) {
    // Handle the error
}

Manage Roles

You can create, update, delete or load roles:

// You can optionally set a description and associated permission for a roles.
RolesService rs = descopeClient.getManagementServices().getRolesService();

String name = "My Role";
String description = "Optional description to briefly explain what this role allows.";
List<String> permissionNames = Arrays.asList("My Updated Permission");

// In case roles are on tenant scope, use the overloaded functions that has the tenantId parameter

try {
    rs.create(name, description, permissionNames);
} catch (DescopeException de) {
    // Handle the error
}

// Update will override all fields as is. Use carefully.
String newName = "My Updated Role";
description = "A revised description";
permissionNames.add("Another Permission");

try {
    rs.update(name, newName, description, permissionNames);
} catch (DescopeException de) {
    // Handle the error
}

// Create or update a role with its default and private flags, and get the role back
try {
    Role created = rs.create("Default Role", "", description, permissionNames, true, false);
    Role updated = rs.update("Default Role", "", "Default Role", description, permissionNames, true, true);
    // Or identify the role to update by its ID
    updated = rs.updateWithId(created.getId(), "", "Default Role", description, permissionNames, true, true);
} catch (DescopeException de) {
    // Handle the error
}

// Role deletion cannot be undone. Use carefully.
try {
    rs.delete(newName);
} catch (DescopeException de) {
    // Handle the error
}

// Load all roles
try {
    RoleResponse resp = rs.loadAll();
    for (Role r : resp.getRoles()) {
        // Do something
    }
} catch (DescopeException de) {
    // Handle the error
}

// Search roles
try {
    RoleResponse resp = rs.search(RoleSearchOptions.builder().tenantIds(Arrays.asList(tid)).build());
    for (Role r : resp.getRoles()) {
        // Do something
    }
} catch (DescopeException de) {
    // Handle the error
}

// Search roles by free text or IDs, sorted, including project roles alongside the tenant's roles
try {
    RoleResponse resp = rs.search(RoleSearchOptions.builder()
        .tenantIds(Arrays.asList(tid))
        .includeProjectRoles(true)
        .text("admin")
        .roleIds(Arrays.asList("<role-id>"))
        .sort(Arrays.asList(SortField.builder().field("createdTime").desc(true).build()))
        .build());
} catch (DescopeException de) {
    // Handle the error
}

// Delete a role by its ID (pass the tenant ID for tenant-scoped roles, or "" for project roles)
try {
    rs.deleteWithId("<role-id>", "tenant-id");
} catch (DescopeException de) {
    // Handle the error
}

// Create, update or delete several roles in a single request
try {
    RoleResponse created = rs.createBatch(Arrays.asList(
        Role.builder().name("Role A").description("desc A").build()));
    RoleResponse updated = rs.updateBatch(Arrays.asList(
        RoleUpdateRequest.builder().name("Role A").newName("Role A Renamed").build()));
    rs.deleteBatch(Arrays.asList("Role A Renamed"), "", null);
} catch (DescopeException de) {
    // Handle the error
}

Query SSO Groups

You can query SSO groups:

// Load all groups for a given tenant id
GroupService gs = descopeClient.getManagementServices().getGroupService();
try {
    List<Group> groups = gs.loadAllGroups("tenant-id");
    for (Group g : groups) {
        // Do something
    }
} catch (DescopeException de) {
    // Handle the error
}

// Load all groups for the given user/login IDs (can be found in the user's JWT, used for sign-in)
try {
    List<Group> groups = gs.loadAllGroupsForMembers("tenant-id",
            Arrays.asList("user-id-1", "user-id-2"),
            Arrays.asList("login-id-1", "login-id-2"));
    for (Group g : groups) {
        // Do something
    }
} catch (DescopeException de) {
    // Handle the error
}

// Load all group's members by the given group id
try {
    List<Group> groups = gs.loadAllGroupMembers("tenant-id", "group-id");
    for (Group g : groups) {
        // Do something
    }
} catch (DescopeException de) {
    // Handle the error
}

// Each of the above also accepts an SSO configuration ID (ssoId) as a last argument, to only
// return groups from that SSO configuration. Use "default_ssoid" for the tenant's default one.
try {
    List<Group> groups = gs.loadAllGroups("tenant-id", "sso-id");
    groups = gs.loadAllGroupsForMembers("tenant-id",
            Arrays.asList("user-id-1", "user-id-2"),
            Arrays.asList("login-id-1", "login-id-2"),
            "sso-id");
    groups = gs.loadAllGroupMembers("tenant-id", "group-id", "sso-id");
    for (Group g : groups) {
        String ssoId = g.getSsoId(); // The SSO configuration the group came from
    }
} catch (DescopeException de) {
    // Handle the error
}

Manage Flows

You can list, import and export flows and screens, or the project theme, run management flows, and manage a tenant's own theme:

FlowService fs = descopeClient.getManagementServices().getFlowService();

// List all your flows
try {
    List<Flow> flows = fs.listFlows();
    for (Flow f : flows) {
        // Do something
    }
} catch (DescopeException de) {
    // Handle the error
}

// Export the flow and it's matching screens based on the given id
try {
    FlowResponse resp = fs.exportFlow("sign-up");
    Flow flow = resp.getFlow();
    List<Screen> screens = resp.getScreens();
    for (Screen s : screens) {
        // Do something
    }
} catch (DescopeException de) {
    // Handle the error
}

// Import the given flow and screens as the given id
try {
    FlowResponse resp = fs.importFlow("sign-up", flow, screens);
    Flow flow = resp.getFlow();
    List<Screen> screens = resp.getScreens();
    for (Screen s : screens) {
        // Do something
    }
} catch (DescopeException de) {
    // Handle the error
}

// Export the flow and its screens based on the given id, as raw JSON data
try {
    Map<String, Object> exported = fs.exportFlowV2("sign-up");
    Object metadata = exported.get("metadata");
} catch (DescopeException de) {
    // Handle the error
}

// Import exported flow data as the given id, overriding the existing flow (irreversible).
// The given id overrides any flowId in the flow data. changelog is optional.
try {
    fs.importFlowV2("sign-up", exported);
    fs.importFlowV2("sign-up", exported, "Updated the sign-up screen");
} catch (DescopeException de) {
    // Handle the error
}

// Export the current theme of the project
try {
    Theme t = fs.exportTheme();
    System.out.println(t.getId());
} catch (DescopeException de) {
    // Handle the error
}

// Import the given theme to the project
try {
    Theme theme = fs.importTheme(t);
    System.out.println(theme.getId());
} catch (DescopeException de) {
    // Handle the error
}

// Export the project theme, with its styles and the project entities they reference
try {
    ExportedTheme exported = fs.exportProjectTheme();
    Map<String, Object> styles = exported.getStyles();
} catch (DescopeException de) {
    // Handle the error
}

// Import a theme to the project. Its styles are created or overwritten,
// other styles in the project are left as they are
try {
    fs.importProjectTheme(exported);
} catch (DescopeException de) {
    // Handle the error
}

// Get the styles a tenant overrides the project theme with (not found when the tenant has none)
try {
    TenantTheme tt = fs.getTenantTheme("my-tenant-id");
    Map<String, Map<String, Object>> styles = tt.getStyles();
} catch (DescopeException de) {
    // Handle the error
}

// Create or replace a tenant's styles, keyed by flavor ("light", "dark", "<styleId>-light", ...).
// A logo must be given as a base64 data URI.
try {
    Map<String, Map<String, Object>> styles = new HashMap<>();
    styles.put("light", lightStyle);
    styles.put("dark", darkStyle);
    TenantTheme stored = fs.setTenantTheme("my-tenant-id", TenantTheme.builder().styles(styles).build());
} catch (DescopeException de) {
    // Handle the error
}

// Delete a tenant's theme, so its flows use the project theme again
try {
    fs.deleteTenantTheme("my-tenant-id");
} catch (DescopeException de) {
    // Handle the error
}

// Delete flows by their IDs
try {
    fs.deleteFlows(Arrays.asList("sign-up", "sign-in"));
} catch (DescopeException de) {
    // Handle the error
}

// List only the flows with the given IDs, with their total count
try {
    FlowsResponse resp = fs.listFlows(Arrays.asList("sign-up", "sign-in"));
    int total = resp.getTotal();
    for (FlowMetadata f : resp.getFlows()) {
        // Do something
    }
} catch (DescopeException de) {
    // Handle the error
}

// Run a management flow and get its output
ManagementFlowOptions options = ManagementFlowOptions.builder()
    .input(Collections.singletonMap("email", "test@example.com"))
    .preview(true)
    .tenant("t1")
    .build();
try {
    ManagementFlowResponse resp = fs.runManagementFlow("management-flow", options);
    Map<String, Object> output = resp.getOutput();
} catch (DescopeException de) {
    // Handle the error
}

// Start a management flow without waiting, and fetch its output later
try {
    String executionId = fs.runManagementFlowAsync("management-flow", options);
    ManagementFlowResponse resp = fs.getManagementFlowAsyncResult(executionId);
    Map<String, Object> output = resp.getOutput();
} catch (DescopeException de) {
    // Handle the error
}

Manage JWTs

You can add custom claims to a valid JWT.

JwtService jwts = descopeClient.getManagementServices().getJwtService();
try {
    String res = jwts.updateJWTWithCustomClaims("original-jwt",
            new HashMap<String, Object>() {{
                put("custom-key1", "custom-value1");
                put("custom-key2", "custom-value2");
            }}).getJwt();
} catch (DescopeException de) {
    // Handle the error
}

Generate a JWT for a user, simulating a signin request.

JwtService jwtService = descopeClient.getManagementServices().getJwtService();
LoginOptions loginOptions = new LoginOptions();
loginOptions.setCustomClaims(new HashMap<String, Object>() {{
	put("custom-key1", "custom-value1");
	put("custom-key2", "custom-value2");
}});
AuthenticationInfo res = jwtService.signIn("dummy", loginOptions);

Generate a JWT for a user, simulating a signup request.

JwtService jwtService = descopeClient.getManagementServices().getJwtService();
MgmtSignUpUser mgmtSignUpUser = new MgmtSignUpUser();
mgmtSignUpUser.setCustomClaims(new HashMap<String, Object>() {{
	put("custom-key1", "custom-value1");
	put("custom-key2", "custom-value2");
		}});
AuthenticationInfo res = jwtService.signUp("Dummy", mgmtSignUpUser);

Generate a JWT for a user, simulates a signup or in request.

JwtService jwtService = descopeClient.getManagementServices().getJwtService();
MgmtSignUpUser mgmtSignUpUser = new MgmtSignUpUser();
mgmtSignUpUser.setCustomClaims(new HashMap<String, Object>() {{
	put("custom-key1", "custom-value1");
	put("custom-key2", "custom-value2");
		}});
AuthenticationInfo res = jwtService.signUpOrIn("Dummy", mgmtSignUpUser);

Generate a client assertion JWT for OAuth 2.0 client credentials flow.

JwtService jwtService = descopeClient.getManagementServices().getJwtService();
try {
    ClientAssertionResponse response = jwtService.generateClientAssertionJwt(
        "client-id",
        "client-id",
        Arrays.asList("https://auth.example.com/token"),
        3600,
        false,
        "RS256"
    );
    String jwt = response.getJwt();
} catch (DescopeException de) {
    // Handle the error
}

Impersonate another user (the impersonator must have permission to do so). stopImpersonation returns a regular JWT for the original impersonator.

JwtService jwtService = descopeClient.getManagementServices().getJwtService();
try {
    String jwt = jwtService.impersonate("impersonator-id", "target-login-id", true,
            new HashMap<String, Object>() {{ put("custom-key1", "custom-value1"); }}, "tenant-id");
    // Step-up impersonation (requires an existing session)
    String stepupJwt = jwtService.impersonateStepup("impersonator-id", "target-login-id", true, null, "tenant-id");
    // Optionally set the refresh token duration (seconds) and the session cookie name
    String customJwt = jwtService.impersonate("impersonator-id", "target-login-id", true, null, "tenant-id",
            3600, "my-session-cookie");
    String customStepupJwt = jwtService.impersonateStepup("impersonator-id", "target-login-id", true, null,
            "tenant-id", 3600, "my-session-cookie");
    // Return to the original user
    String originalJwt = jwtService.stopImpersonation(jwt, null, "tenant-id");
    // Optionally set the refresh duration of the returned JWT
    String originalJwtWithRefresh = jwtService.stopImpersonation(jwt, null, "tenant-id", 3600);
} catch (DescopeException de) {
    // Handle the error
}

Audit

You can perform an audit search for either specific values or full-text across the fields. Audit search is limited to the last 30 days.

AuditService as = descopeClient.getManagementServices().getAuditService();
// Full text search on the last 10 days
try {
    AuditSearchResponse resp = as.search(AuditSearchRequest.builder()
            .from(Instant.now().minus(Duration.ofDays(10))));
} catch (DescopeException de) {
    // Handle the error
}

// Search successful logins in the last 30 days
try {
    AuditSearchResponse resp = as.search(AuditSearchRequest.builder()
            .from(Instant.now().minus(Duration.ofDays(30)))
            .actions(Arrays.asList("LoginSucceed"))
            .build());
} catch (DescopeException de) {
    // Handle the error
}

You can also create audit event with data

```java
try {
    as.createEvent(AuditCreateRequest.builder()
            .userId("some-id")
            .actorId("some-actor-id")
            .type(AuditType.INFO)
            .action("some-action-name")
            .build());
} catch (DescopeException de) {
    // Handle the error
}

You can also configure an audit webhook connector that streams audit events to an external endpoint:

try {
    as.createAuditWebhook(AuditWebhook.builder()
            .name("My Audit Webhook")
            .url("https://my-app.com/audit-hook")
            .build());
} catch (DescopeException de) {
    // Handle the error
}

// Create or update an audit webhook connector by name
try {
    as.setAuditWebhook(AuditWebhook.builder()
            .name("My Audit Webhook")
            .url("https://my-app.com/audit-hook")
            .authentication(AuditWebhookAuthentication.builder().bearerToken("my-token").build())
            .filters(Arrays.asList(AuditWebhookFilter.builder()
                    .filterType("actions")
                    .operator("includes")
                    .values(Arrays.asList("LoginSucceed"))
                    .build()))
            .build());
} catch (DescopeException de) {
    // Handle the error
}

Analytics

You can search analytics, the summarized audit data, grouped by time period and by the fields you choose. Analytics search is limited to the last 12 months.

AnalyticsService ans = descopeClient.getManagementServices().getAnalyticsService();
// Count successful logins per day and method in the last 30 days
try {
    AnalyticsSearchResponse resp = ans.search(AnalyticsSearchRequest.builder()
            .from(Instant.now().minus(Duration.ofDays(30)))
            .to(Instant.now())
            .actions(Arrays.asList("LoginSucceed"))
            .groupByMethod(true)
            .groupByCreated(AnalyticsGroupByCreated.DAY)
            .build());
    for (AnalyticRecord r : resp.getAnalytics()) {
        // r.getCreated(), r.getMethod(), r.getCnt()
    }
} catch (DescopeException de) {
    // Handle the error
}

FGA (Fine-Grained Authorization)

You can manage fine-grained authorization schemas, relations, and resource metadata:

// Create and manage authorization schemas
FGAService fs = descopeClient.getManagementServices().getFgaService();

String dsl = "model AuthZ 1.0\n" +
             "type user\n" +
             "type document\n" +
             "  relation owner: user\n" +
             "  relation editor: user\n" +
             "  relation viewer: user";

try {
    FGASchema schema = new FGASchema(dsl);
    fs.saveSchema(schema);
} catch (DescopeException de) {
    // Handle the error
}

// Preview what saving a schema would delete, without saving it
try {
    FGASchemaDryRunResponse dryRun = fs.dryRunSchema(new FGASchema(dsl));
    FGASchemaDryDeletes deletes = dryRun.getDeletesPreview();
    if (deletes != null && deletes.isHasDeletes()) {
        System.out.println("Would delete relations: " + deletes.getRelations());
        System.out.println("Would delete types: " + deletes.getTypes());
    }
} catch (DescopeException de) {
    // Handle the error
}

// Load the current authorization schema
try {
    FGASchema schema = fs.loadSchema();
    // Do something with schema.getDsl(), schema.getVersion() and schema.getConditions()
} catch (DescopeException de) {
    // Handle the error
}

// Create relations between resources and users
List<FGARelation> relations = Arrays.asList(
    new FGARelation("doc1", "document", "owner", "user123", "user"),
    new FGARelation("doc1", "document", "viewer", "user456", "user")
);

try {
    fs.createRelations(relations);
} catch (DescopeException de) {
    // Handle the error
}

// Check if relations are allowed
try {
    List<FGACheckResult> results = fs.check(relations);
    for (FGACheckResult result : results) {
        // Do something with result.isAllowed(), result.getRelation() and result.getInfo()
    }
} catch (DescopeException de) {
    // Handle the error
}

// Check relations against a schema that uses conditions (ABAC), passing the values
// the conditions are evaluated with
Map<String, Object> context = new HashMap<>();
context.put("role", "admin");

try {
    List<FGACheckResult> results = fs.check(relations, context);
    for (FGACheckResult result : results) {
        FGACheckInfo info = result.getInfo();
        // info.isConditional() - the result was decided by a condition
        // info.getMissingContext() - context variables the conditions needed but did not get
        // info.getConditionalErr() - the condition could not be evaluated
    }
} catch (DescopeException de) {
    // Handle the error
}

// The same context can be passed to the authz queries that evaluate conditions
AuthzService authz = descopeClient.getManagementServices().getAuthzService();
List<String> targets = authz.whoCanAccess("doc1", "viewer", "document", context);
List<Relation> relationsForTarget = authz.whatCanTargetAccess("user123", context);
// relation.getTargetNamespace() is the namespace (type) of each returned relation's target
// Only return targets of the given type (namespace); null returns all targets
List<String> userTargets = authz.whoCanAccess("doc1", "viewer", "document", "user", context);
List<Relation> viewableDocs = authz.whatCanTargetAccessWithRelation("user123", "viewer", "document", context);

// Delete all relations in which the given resources are the resource
try {
    authz.deleteResourceRelationsForResources(Arrays.asList("doc1", "doc2"));
} catch (DescopeException de) {
    // Handle the error
}

// Delete relations
try {
    fs.deleteRelations(relations);
} catch (DescopeException de) {
    // Handle the error
}

// Save resource metadata
List<FGAResourceDetails> resourceDetails = Arrays.asList(
    new FGAResourceDetails("doc1", "document", "Important Document"),
    new FGAResourceDetails("doc2", "document", "Public Document")
);

try {
    fs.saveResourcesDetails(resourceDetails);
} catch (DescopeException de) {
    // Handle the error
}

// Load resource metadata
List<FGAResourceIdentifier> identifiers = Arrays.asList(
    new FGAResourceIdentifier("doc1", "document")
);

try {
    List<FGAResourceDetails> details = fs.loadResourcesDetails(identifiers);
    for (FGAResourceDetails detail : details) {
        // Do something with detail.getDisplayName()
    }
} catch (DescopeException de) {
    // Handle the error
}

Routing FGA calls to an FGA cache

If you run an FGA cache (authzcache) instance, set fgaCacheUrl on the config, or the DESCOPE_FGA_CACHE_URL env var, and the calls it serves are sent there instead of the Descope base URL: saveSchema, createRelations, deleteRelations and check on the FGA service, plus whoCanAccess and whatCanTargetAccess on the authz service. Every other call, including loadSchema, dryRunSchema and the resource details calls, stays on the base URL. Leave it unset to send everything to the base URL.

var descopeClient = new DescopeClient(Config.builder()
        .projectId("Your-project")
        .managementKey("management-key")
        .fgaCacheUrl("https://your-authzcache-host")
        .build());

Manage Outbound Applications

You can create outbound applications, fetch, upload and delete their tokens, and manage their SCIM configuration:

// Set up the outbound apps service
OutboundAppsService outboundAppsService = descopeClient.getManagementServices().getOutboundAppsService();

// Fetch a user token for an outbound app
try {
    FetchOutboundAppUserTokenResponse res = outboundAppsService.fetchOutboundAppUserToken(
        FetchOutboundAppUserTokenRequest.builder()
            .appId("app-id") // required
            .userId("user-id") // required
            .scopes(Arrays.asList("read", "write")) // required, at least one scope
            // .tenantId("tenant-id") // optional
            // .externalIdentifier("key-1") // optional
            // .options(
            //     FetchOutboundAppTokenOptions.builder() // optional
            //         .withRefreshToken(false)
            //         .forceRefresh(false)
            //         .build()
            // )
            .build()
    );
    OutboundAppToken token = res.getToken();
} catch (DescopeException de) {
    // Handle the error
}

// Delete a user token by token ID
try {
    outboundAppsService.deleteOutboundAppTokenById("token-id");
} catch (DescopeException de) {
    // Handle the error
}

// Delete all outbound app tokens for a user
try {
    outboundAppsService.deleteOutboundAppUserTokens(
        DeleteOutboundAppUserTokensRequest.builder()
            .appId("app-id") // required
            .userId("user-id") // required
            .build()
    );
} catch (DescopeException de) {
    // Handle the error
}

// Delete all of a user's tokens for an outbound app
try {
    outboundAppsService.deleteOutboundAppUserTokens("app-id", "user-id"); // both required
} catch (DescopeException de) {
    // Handle the error
}

// Create an outbound application
try {
    OutboundAppCreateResponse res = outboundAppsService.createApplication(
        OutboundAppRequest.builder()
            .name("My Outbound App") // required
            // .id("optional-custom-id")
            // .description("optional-description")
            // .clientId("client-id")
            // .clientSecret("client-secret")
            // .discoveryUrl("https://provider.com/.well-known/openid-configuration")
            // .authorizationUrl("https://provider.com/authorize")
            // .authorizationUrlParams(Arrays.asList(OutboundAppURLParam.builder().key("k").value("v").build()))
            // .tokenUrl("https://provider.com/token")
            // .defaultScopes(Arrays.asList("read"))
            // .pkce(true)
            // .accessType(OutboundAppAccessType.OFFLINE)
            // .prompt(Arrays.asList(OutboundAppPrompt.CONSENT))
            // .appType(OutboundAppType.OAUTH)
            // .tokenEndpointAuthMethod(OutboundAppTokenEndpointAuthMethod.PRIVATE_KEY_JWT)
            // .tokenEndpointAuthSigningAlg(OutboundAppTokenEndpointAuthSigningAlg.RS256)
            // .useNonce(true)
            .build()
    );
    OutboundApp app = res.getApp();
} catch (DescopeException de) {
    // Handle the error
}

// Update an outbound application. Unset tokenEndpointAuthMethod, tokenEndpointAuthSigningAlg and useNonce keep
// their stored value
try {
    OutboundApp app = outboundAppsService.updateOutboundApp(
        OutboundApp.builder()
            .id("app-id") // required
            .name("My Outbound App") // required
            // .description("optional-description")
            // .clientSecret("client-secret")
            // .tokenUrl("https://provider.com/token")
            // .defaultScopes(Arrays.asList("read"))
            .build()
    );
} catch (DescopeException de) {
    // Handle the error
}

// Load an outbound application by ID
try {
    OutboundApp app = outboundAppsService.loadOutboundApp("app-id");
} catch (DescopeException de) {
    // Handle the error
}

// Create an outbound application from a template
try {
    OutboundApp app = outboundAppsService.createApplicationByTemplate(
        CreateOutboundAppByTemplateRequest.builder()
            .templateId("template-id") // required
            // .clientId("client-id")
            // .clientSecret("client-secret")
            // .overrides(OutboundAppTemplateOverrides.builder().name("My App").build())
            .build()
    );
} catch (DescopeException de) {
    // Handle the error
}

// List the IDs of the apps for which a user has a valid token (tenant ID is optional)
try {
    List<String> appIds = outboundAppsService.listAppsWithUserToken("user-id", null);
} catch (DescopeException de) {
    // Handle the error
}

// Upload a static API key for a user or a tenant on an apikey-type app
try {
    outboundAppsService.uploadUserAPIKey(
        UploadOutboundAppUserAPIKeyRequest.builder()
            .appId("app-id") // required
            .userId("user-id") // required
            .apiKey("api-key") // required
            // .tenantId("tenant-id")
            // .externalIdentifier("key-1") // store several keys per user
            .build()
    );
    outboundAppsService.uploadTenantAPIKey(
        UploadOutboundAppTenantAPIKeyRequest.builder()
            .appId("app-id") // required
            .tenantId("tenant-id") // required
            .apiKey("api-key") // required
            .build()
    );
} catch (DescopeException de) {
    // Handle the error
}

// Upload (migrate) an existing OAuth token for a user or a tenant
try {
    outboundAppsService.uploadUserToken(
        UploadOutboundAppUserTokenRequest.builder()
            .appId("app-id") // required
            .userId("user-id") // required
            .refreshToken("refresh-token")
            .accessToken("access-token")
            .accessTokenExpiry(1767225600) // epoch seconds
            .scopes(Arrays.asList("read"))
            // .verifyRefresh(true) // verify the refresh token with the provider before saving
            .build()
    );
    outboundAppsService.uploadTenantToken(
        UploadOutboundAppTenantTokenRequest.builder()
            .appId("app-id") // required
            .tenantId("tenant-id") // required
            .refreshToken("refresh-token")
            .build()
    );
} catch (DescopeException de) {
    // Handle the error
}

// Batch upload OAuth tokens (up to 500). All-or-nothing: if failures are returned, nothing was saved
try {
    List<OutboundAppTokenUploadFailure> failures = outboundAppsService.batchUploadUserTokens(Arrays.asList(
        OutboundAppUserTokenUploadItem.builder().appId("app-id").userId("user-id").refreshToken("rt").build()));
    failures = outboundAppsService.batchUploadTenantTokens(Arrays.asList(
        OutboundAppTenantTokenUploadItem.builder().appId("app-id").tenantId("tenant-id").refreshToken("rt").build()));
} catch (DescopeException de) {
    // Handle the error
}

// Manage the outbound SCIM configuration of an app
try {
    Map<String, Object> configuration = new HashMap<>();
    configuration.put("baseUrl", "https://provider.com/scim/v2");
    OutboundSCIMConfiguration scim = outboundAppsService.createSCIMConfiguration(
        CreateOutboundSCIMConfigurationRequest.builder()
            .appId("app-id") // required
            .configuration(configuration) // required
            .build()
    );
    scim = outboundAppsService.updateSCIMConfiguration(
        UpdateOutboundSCIMConfigurationRequest.builder()
            .appId("app-id") // required
            .configuration(configuration)
            .version(scim.getVersion()) // optional
            .build()
    );
    scim = outboundAppsService.setSCIMEnabled("app-id", true);
    scim = outboundAppsService.loadSCIMConfiguration("app-id");
    outboundAppsService.deleteSCIMConfiguration("app-id");
} catch (DescopeException de) {
    // Handle the error
}

Manage Inbound Applications

You can create, update, patch, delete, and load inbound applications, as well as manage secrets and consents:

// Set up the inbound apps service
InboundAppsService inboundAppsService = descopeClient.getManagementServices().getInboundAppsService();

// Create a new inbound application
try {
    InboundAppCreateResponse response = inboundAppsService.createApplication(
        InboundAppRequest.builder()
            .name("My Inbound App") // required
            // .id("optional-custom-id")
            // .description("optional-description")
            // .logo("optional-logo")
            // .loginPageUrl("optional-loginPageUrl")
            // .approvedCallbackUrls(new String[] { "https://example.com/callback1", "https://example.com/callback2" })
            // .permissionsScopes(new InboundAppScope[] {
            //     InboundAppScope.builder()
            //         .name("scope-name") // required for each scope
            //         .description("optional description")
            //         // .values(new String[] { "value1", "value2" }) // if supported
            //         .build()
            // })
            // .attributesScopes(new InboundAppScope[] {
            //     InboundAppScope.builder()
            //         .name("attribute-scope-name") // required for each attribute scope
            //         .description("optional description")
            //         // .values(new String[] { "value1", "value2" }) // if supported
            //         .build()
            // })
            .build()
    );
    String appId = response.getId();
    String secret = response.getSecret();
} catch (DescopeException de) {
    // Handle the error
}

// Update an existing inbound application (overwrites all fields)
try {
    inboundAppsService.updateApplication(
        InboundAppRequest.builder()
            .id("app-id") // required
            .name("Updated Name") // required
            // .description("optional-description")
            // .logo("optional-logo")
            // .loginPageUrl("optional-loginPageUrl")
            // .approvedCallbackUrls(new String[] { "https://example.com/callback1" })
            // .permissionsScopes(new InboundAppScope[] {
            //     InboundAppScope.builder().name("scope-name").build()
            // })
            // .attributesScopes(new InboundAppScope[] {
            //     InboundAppScope.builder().name("attribute-scope-name").build()
            // })
            .build()
    );
} catch (DescopeException de) {
    // Handle the error
}

// Patch an inbound application (updates only provided fields)
try {
    inboundAppsService.patchApplication(
        InboundAppRequest.builder()
            .id("app-id") // required
            // .name("Patched Name")
            // .description("optional-description")
            // .logo("optional-logo")
            // .loginPageUrl("optional-loginPageUrl")
            // .approvedCallbackUrls(new String[] { "https://example.com/callback1" })
            // .permissionsScopes(new InboundAppScope[] {
            //     InboundAppScope.builder().name("scope-name").build()
            // })
            // .attributesScopes(new InboundAppScope[] {
            //     InboundAppScope.builder().name("attribute-scope-name").build()
            // })
            .build()
    );
} catch (DescopeException de) {
    // Handle the error
}

// Delete an inbound application by ID
try {
    inboundAppsService.deleteApplication("app-id");
} catch (DescopeException de) {
    // Handle the error
}

// Load a specific inbound application by ID
try {
    InboundApp app = inboundAppsService.loadApplication("app-id"); 
} catch (DescopeException de) {
    // Handle the error
}

// Load a specific inbound application by client ID
try {
    InboundApp app = inboundAppsService.loadApplicationByClientId("client-id"); 
} catch (DescopeException de) {
    // Handle the error
}

// Get the application's secret
try {
    String secret = inboundAppsService.getApplicationSecret("app-id"); 
} catch (DescopeException de) {
    // Handle the error
}

// Rotate the application's secret (returns new secret)
try {
    String newSecret = inboundAppsService.rotateApplicationSecret("app-id"); 
} catch (DescopeException de) {
    // Handle the error
}

// Load all inbound applications
try {
    InboundApp[] apps = inboundAppsService.loadAllApplications();
    for (InboundApp app : apps) {
        // Do something
    }
} catch (DescopeException de) {
    // Handle the error
}

// Delete user consents for an inbound app
// At least one identifying field must be set: consentIds, appId, userIds, or tenantId
try {
    inboundAppsService.deleteConsents(
        InboundAppConsentDeleteOptions.builder()
            // .consentIds(new String[] { "consent-id-1", "consent-id-2" }) 
            // .appId("app-id") 
            // .userIds(new String[] { "user-id-1", "user-id-2" }) 
            // .tenantId("tenant-id") 
            .build()
    );
} catch (DescopeException de) {
    // Handle the error
}

// Delete tenant consents for an inbound app
// At least one identifying field must be set: consentIds, appId, or tenantId
try {
    inboundAppsService.deleteTenantConsents(
        InboundAppTenantConsentDeleteOptions.builder()
            // .consentIds(new String[] { "consent-id-1", "consent-id-2" }) 
            // .appId("app-id") 
            // .tenantId("tenant-id") 
            .build()
    );
} catch (DescopeException de) {
    // Handle the error
}

// Search consents for inbound apps
// All fields are optional, use to filter results
try {
    InboundAppConsentSearchResponse res = inboundAppsService.searchConsents(
        InboundAppConsentSearchOptions.builder()
            // .appId("app-id") 
            // .userId("user-id") 
            // .consentId("consent-id") 
            // .tenantId("tenant-id") 
            // .page("page-token") 
            .build()
    );
    // res.getConsents(), res.getTotal()
} catch (DescopeException de) {
    // Handle the error
}

Manage Engines

You can create, update, delete, load and list engines, as well as rotate their secrets:

// Set up the engine service
EngineService engineService = descopeClient.getManagementServices().getEngineService();

// Create a new engine. The returned secret cannot be retrieved again.
try {
    Engine engine = engineService.createEngine("my-engine");
    String engineId = engine.getId();
    String secret = engine.getSecret();
} catch (DescopeException de) {
    // Handle the error
}

// Update an engine's name
try {
    Engine engine = engineService.updateEngine("engine-id", "my-engine");
} catch (DescopeException de) {
    // Handle the error
}

// Load an engine by ID. The secret is never returned here.
try {
    Engine engine = engineService.loadEngine("engine-id");
} catch (DescopeException de) {
    // Handle the error
}

// Rotate an engine's secret. The previous secret is immediately invalidated.
try {
    String newSecret = engineService.rotateEngineSecret("engine-id");
} catch (DescopeException de) {
    // Handle the error
}

// Delete an engine
try {
    engineService.deleteEngine("engine-id");
} catch (DescopeException de) {
    // Handle the error
}

// Load all engines. Their secrets are never returned here.
try {
    List<Engine> engines = engineService.loadAllEngines();
    for (Engine engine : engines) {
        String engineId = engine.getId();
        String name = engine.getName();
    }
} catch (DescopeException de) {
    // Handle the error
}

Manage Project

You can change the project name, as well as to clone the current project to a new one.

ProjectService ps = descopeClient.getManagementServices().getProjectService();
// Change the project name
try {
    ps.updateName("New Project Name");
} catch (DescopeException de) {
    // Handle the error
}

// Clone the current project to a new one
// Note that this action is supported only with a pro license or above.
try {
    NewProjectResponse resp = ps.cloneProject("New Project Name", ProjectTag.None);
} catch (DescopeException de) {
    // Handle the error
}

// Update the project's tags
try {
    ps.updateTags(Arrays.asList("production", "eu"));
} catch (DescopeException de) {
    // Handle the error
}

// List all projects in the current company
try {
    List<Project> projects = ps.listProjects();
} catch (DescopeException de) {
    // Handle the error
}

// Delete the current project. This action is irreversible - use carefully.
try {
    ps.deleteProject();
} catch (DescopeException de) {
    // Handle the error
}

You can manage your project's settings and configurations by exporting your project's environment.

// Exports the current state of the project
try {
    ExportProjectResponse resp = ps.exportProject();
} catch (DescopeException de) {
    // Handle the error
}

You can also import previously exported data into the same project or a different one.

try {
    // Load data from a previous export of this project or some other one
    Map<String, Object> files = ...

    // Update the current project's settings to mirror those in the exported data
    ps.importProject(files);
} catch (DescopeException de) {
    // Handle the error
}

Manage Descopers

You can create, load, update, delete and list descopers, the console users of your company:

DescoperService ds = descopeClient.getManagementServices().getDescoperService();

// Create descopers. Each needs a loginId (an email for now) and rbac.
// Tags are referred to by name, without the company ID prefix.
try {
    DescopersResponse res = ds.createDescopers(Arrays.asList(
        DescoperCreate.builder()
            .loginId("someone@example.com")
            .attributes(DescoperAttributes.builder()
                .displayName("Someone")
                .email("someone@example.com")
                .phone("+15555555555")
                .build())
            .sendInvite(true)
            .rbac(DescoperRBAC.builder()
                .isCompanyAdmin(false)
                .tags(Arrays.asList(DescoperTagRole.builder()
                    .tags(Arrays.asList("my-tag"))
                    .role(DescoperRole.DEVELOPER) // required
                    .build()))
                .projects(Arrays.asList(DescoperProjectRole.builder()
                    .projectIds(Arrays.asList("project-id"))
                    .role(DescoperRole.ADMIN) // required
                    .build()))
                .build())
            .build()));
    // res.getDescopers(), res.getTotal()
} catch (DescopeException de) {
    // Handle the error
}

// Load a descoper by ID
try {
    Descoper d = ds.loadDescoper("descoper-id");
    // d.getAttributes(), d.getRbac(), d.getStatus(), d.getLoginIds()
} catch (DescopeException de) {
    // Handle the error
}

// Update a descoper. Every field that is set overrides the current value; pass null to leave attributes or rbac as is.
try {
    Descoper d = ds.updateDescoper("descoper-id",
        DescoperAttributes.builder().displayName("New Name").build(),
        DescoperRBAC.builder().isCompanyAdmin(true).build());
} catch (DescopeException de) {
    // Handle the error
}

// Delete a descoper. This action is irreversible.
try {
    ds.deleteDescoper("descoper-id");
} catch (DescopeException de) {
    // Handle the error
}

// List all descopers
try {
    DescopersResponse res = ds.listDescopers();
    // res.getDescopers(), res.getTotal()
} catch (DescopeException de) {
    // Handle the error
}

Manage Auth Access Policy

You can manage the rules that allow or block authentication, for the project and for each tenant. Rules are evaluated in order and the first matching rule decides; when none matches, the settings' default action decides. Every project method has a tenant variant that takes the tenant ID first.

AuthAccessService aas = descopeClient.getManagementServices().getAuthAccessService();

// Create a rule. The effect is required; the rule is appended at the end of the evaluation order.
// All conditions must match. Values are in canonical form, e.g. uppercase countries and lowercase emails.
try {
    AuthAccessRule rule = aas.createRule(AuthAccessRule.builder()
        .name("Block some countries")
        .description("Block sign-ins from these countries")
        .enabled(true)
        .effect(AuthAccessRuleEffect.BLOCK)
        .expireTime(0L) // epoch seconds, 0 means never
        .conditionsList(AuthAccessConditionList.builder()
            .items(Arrays.asList(AuthAccessCondition.builder()
                .key("request.country")
                .operator("in")
                .values(Arrays.asList("XX", "YY"))
                .build()))
            .build())
        .build());
    // For a tenant: aas.createTenantRule("tenant-id", rule)
} catch (DescopeException de) {
    // Handle the error
}

// Load a rule, or all rules in evaluation order
try {
    AuthAccessRule rule = aas.loadRule("rule-id");
    List<AuthAccessRule> rules = aas.loadAllRules();
    // For a tenant: aas.loadTenantRule("tenant-id", "rule-id"), aas.loadAllTenantRules("tenant-id")
} catch (DescopeException de) {
    // Handle the error
}

// Update a rule. The ID is required; fields that are not set keep their stored values.
// A null conditionsList keeps the conditions, an empty one clears them.
try {
    AuthAccessRule rule = aas.updateRule(AuthAccessRule.builder().id("rule-id").enabled(false).build());
    // For a tenant: aas.updateTenantRule("tenant-id", rule)
} catch (DescopeException de) {
    // Handle the error
}

// Move a rule to a 1-based position in the evaluation order. Returns all rules in their new order.
try {
    List<AuthAccessRule> rules = aas.reorderRule("rule-id", 1);
    // For a tenant: aas.reorderTenantRule("tenant-id", "rule-id", 1)
} catch (DescopeException de) {
    // Handle the error
}

// Delete a rule
try {
    aas.deleteRule("rule-id");
    // For a tenant: aas.deleteTenantRule("tenant-id", "rule-id")
} catch (DescopeException de) {
    // Handle the error
}

// Load and update the settings: the default action and the full evaluation order.
// ruleIds, when set, must list every rule exactly once. Fields that are not set keep their stored values.
try {
    AuthAccessSettings settings = aas.loadSettings();
    settings = aas.configureSettings(AuthAccessSettings.builder()
        .defaultAction(AuthAccessDefaultAction.ALLOW)
        .ruleIds(Arrays.asList("rule-id-1", "rule-id-2"))
        .build());
    // For a tenant: aas.loadTenantSettings("tenant-id"), aas.configureTenantSettings("tenant-id", settings)
} catch (DescopeException de) {
    // Handle the error
}

Manage Project Secrets

You can create, update, delete or load project secrets. A secret value is encrypted at rest and can be referenced from connectors and scripts, but is never returned by any API.

// Set up the project secret service
ProjectSecretService projectSecretService = descopeClient.getManagementServices().getProjectSecretService();

// Create a secret. The name cannot be changed later, and the description is optional.
try {
    ProjectSecret secret = projectSecretService.createSecret("MySecret", "secret-value", "My secret description");
} catch (DescopeException de) {
    // Handle the error
}

// Update a secret's description, and optionally rotate its value (pass null to keep the stored value).
// The ID is the lowercased secret name.
try {
    ProjectSecret secret = projectSecretService.updateSecret("mysecret", "Updated description", "new-secret-value");
} catch (DescopeException de) {
    // Handle the error
}

// Load a secret by ID. Secret values are never returned.
try {
    ProjectSecret secret = projectSecretService.loadSecret("mysecret");
} catch (DescopeException de) {
    // Handle the error
}

// Load all secrets
try {
    List<ProjectSecret> secrets = projectSecretService.loadAllSecrets();
} catch (DescopeException de) {
    // Handle the error
}

// Delete a secret. Fails while a connector still references it.
try {
    projectSecretService.deleteSecret("mysecret");
} catch (DescopeException de) {
    // Handle the error
}

Manage Families

You can create, update, delete or search families, manage their dependents and the project's family settings:

FamilyService fs = descopeClient.getManagementServices().getFamilyService();

// Create a family. Custom attributes, photo and disabled are optional
try {
    Family family = fs.create("My Family", new HashMap<String, Object>() {{
                put("custom-attribute-1", "custom-value1");
            }}, "https://example.com/photo.png", false);
} catch (DescopeException de) {
    // Handle the error
}

// You can optionally set your own ID when creating a family
try {
    Family family = fs.createWithId("my-family-id", "My Family", null, null, null);
} catch (DescopeException de) {
    // Handle the error
}

// Update only changes the fields that are not null.
// Custom attributes, when given, replace all of the family's custom attributes.
try {
    Family family = fs.update("my-family-id", "New Name", null, null, true);
} catch (DescopeException de) {
    // Handle the error
}

// Family deletion cannot be undone. Use carefully.
try {
    fs.delete("my-family-id");
} catch (DescopeException de) {
    // Handle the error
}

// Search families. Empty options return all families
try {
    List<Family> families = fs.searchAll(FamilySearchRequest.builder()
        .ids(Arrays.asList("my-family-id"))
        .names(Arrays.asList("My Family"))
        .text("Fam")
        .page(0)
        .size(100)
        .build());
} catch (DescopeException de) {
    // Handle the error
}

// Create a dependent in a family. When the login ID is empty it is derived from the name
try {
    FamilyDependent dependent = fs.createDependent("my-family-id", FamilyDependentRequest.builder()
        .loginId("kid@example.com")
        .name("Kid")
        .familyScopedAttributes(new HashMap<String, Object>() {{
                put("family-attribute", "value");
            }})
        .build());
} catch (DescopeException de) {
    // Handle the error
}

// Delete a dependent. The family is inferred from the dependent
try {
    fs.deleteDependent("dependent-user-id");
} catch (DescopeException de) {
    // Handle the error
}

// Impersonate a dependent: the impersonator must be a member of the dependent's family
// and have the permission to impersonate dependents. The selected family is optional
try {
    String jwt = fs.impersonateDependent("parent@example.com", "kid@example.com", "my-family-id");
    // Stop the impersonation and get a new JWT for the impersonator.
    // Custom claims and refresh duration are optional
    String impersonatorJwt = fs.stopImpersonation(jwt, null, null);
} catch (DescopeException de) {
    // Handle the error
}

// Load and configure the project's family settings. Settings left null keep their current value
try {
    FamilySettings settings = fs.getSettings();
    settings = fs.configureSettings(FamilySettings.builder()
        .enabled(true)
        .maxFamilyMembers(6)
        .allowMultipleFamiliesUsers(false)
        .build());
} catch (DescopeException de) {
    // Handle the error
}

Manage Agentic Identities and Governance

You can search, revoke, block and unblock agentic identities, and manage Agentic Governance Suite access requests and settings:

AgenticService as = descopeClient.getManagementServices().getAgenticService();

// Search agentic identities (consents granted to agentic apps). All criteria are optional.
try {
    SearchAgenticIdentitiesResponse res = as.searchAgenticIdentities(SearchAgenticIdentitiesRequest.builder()
        .userId("user-id")
        .clientId("client-id")
        .resourceId("resource-id")
        .page(0)
        .limit(10)
        .build());
    // res.getIdentities(), res.getTotal(); each identity's getConsent().getId() is its consent ID
} catch (DescopeException de) {
    // Handle the error
}

// Revoke agentic identities and their consents. At least one of userId, clientId, resourceId or consentId is required.
// Only a user ID revokes all of the user's agentic identities across MCP servers.
try {
    RevokeAgenticIdentitiesResponse res = as.revokeAgenticIdentities(RevokeAgenticIdentitiesRequest.builder()
        .userId("user-id")
        .build());
    // res.getRevoked()
} catch (DescopeException de) {
    // Handle the error
}

// Block or unblock XAA (ID-JAG) agentic identities by consent ID (up to 100). A change can take up to 5 minutes to apply.
try {
    XaaAgenticIdentitiesResponse res = as.blockXaaAgenticIdentities(Arrays.asList("consent-id"));
    // res.getIdentities() are the updated identities, res.getSkippedConsentIds() the ones not updated
    as.unblockXaaAgenticIdentities(Arrays.asList("consent-id"));
} catch (DescopeException de) {
    // Handle the error
}

// Load and update the Agentic Governance Suite settings. Only the fields that are set are changed.
try {
    AgenticGovernanceSettings settings = as.loadGovernanceSettings();
    settings = as.updateGovernanceSettings(AgenticGovernanceSettings.builder().autoApproval(true).build());
} catch (DescopeException de) {
    // Handle the error
}

// Create an access request on behalf of a console user in your company
try {
    GovernanceAccessRequest req = as.createGovernanceAccessRequest(CreateGovernanceAccessRequestRequest.builder()
        .requestorUserId("console-user-id") // required
        .clientName("My Agent")
        .clientType("agent")
        .grantTypes(Arrays.asList(GovernanceGrantType.CLIENT_CREDENTIALS))
        .targets(Arrays.asList(GovernanceAccessRequestTarget.builder()
            .name("My API")
            .kind("resource")
            .scopes(Arrays.asList("read"))
            .build()))
        .justification("Nightly reports")
        .build());
    // req.getId(), req.getStatus()
} catch (DescopeException de) {
    // Handle the error
}

// Load, search and resolve access requests
try {
    GovernanceAccessRequest req = as.getGovernanceAccessRequest("request-id");
    SearchGovernanceAccessRequestsResponse res = as.searchGovernanceAccessRequests(
        SearchGovernanceAccessRequestsRequest.builder()
            .text("My Agent")
            .sort(Arrays.asList(GovernanceSortField.builder().field("createdTime").desc(true).build()))
            .limit(10)
            .build());
    // res.getRequests(), res.getTotal()
    // Approve or deny a pending request, with an optional note
    req = as.resolveGovernanceAccessRequest("request-id", "approve", "Approved for the reports team");
} catch (DescopeException de) {
    // Handle the error
}

Manage Dynamic Registration Templates

You can create, update, load and delete dynamic registration templates, which hold the client defaults that MCP resources can use for dynamic client registration:

ResourceService rs = descopeClient.getManagementServices().getResourceService();

// Create a template. The name is required.
try {
    DynamicRegistrationTemplate t = rs.createDynamicRegistrationTemplate(DynamicRegistrationTemplateCreate.builder()
        .name("My Template")
        .description("Defaults for MCP clients")
        .loginPageURL("https://example.com/login")
        .sessionSettings(ThirdPartyApplicationSessionSettings.builder()
            .enabled(true)
            .refreshTokenExpiration(30)
            .refreshTokenExpirationUnit(SessionTimeUnit.DAYS)
            .sessionTokenExpiration(10)
            .sessionTokenExpirationUnit(SessionTimeUnit.MINUTES)
            .build())
        .skipConsentScreen(false)
        .forceAddAllAuthorizationInfo(false)
        .tags(Arrays.asList("tag1"))
        .fallbackClientLogo("https://example.com/logo.png")
        .build());
    // t.getId(), t.getVersion(), t.getCreatedTime()
} catch (DescopeException de) {
    // Handle the error
}

// Update a template. The id and name are required.
// To change only some fields, load the template, change them and pass it back.
try {
    DynamicRegistrationTemplate existing = rs.loadDynamicRegistrationTemplate("template-id");
    existing.setLoginPageURL("https://example.com/new-login");
    DynamicRegistrationTemplate t = rs.updateDynamicRegistrationTemplate(existing);
} catch (DescopeException de) {
    // Handle the error
}

// Load a template by ID
try {
    DynamicRegistrationTemplate t = rs.loadDynamicRegistrationTemplate("template-id");
} catch (DescopeException de) {
    // Handle the error
}

// Load all templates
try {
    DynamicRegistrationTemplatesResponse res = rs.loadAllDynamicRegistrationTemplates();
    // res.getTemplates(), res.getTotal()
} catch (DescopeException de) {
    // Handle the error
}

// Delete a template, or several. This action is irreversible.
try {
    rs.deleteDynamicRegistrationTemplate("template-id");
    rs.deleteDynamicRegistrationTemplates(Arrays.asList("template-id-1", "template-id-2"));
} catch (DescopeException de) {
    // Handle the error
}

Manage SCIM Keys

You can create, rotate, load, revoke and activate the SCIM access keys of a tenant. Omitting the ssoId targets the tenant's default SSO configuration, not every configuration (except when loading keys).

ScimService ss = descopeClient.getManagementServices().getScimService();

// Create a SCIM access key. Existing SCIM keys for the same SSO configuration stay valid.
try {
    SCIMAccessKeyResponse res = ss.createKey(SCIMAccessKeyCreateRequest.builder()
        .tenantId("tenant-id") // required
        .ssoId("sso-id")
        .name("My SCIM key")
        .description("Provisioning from my identity provider")
        .expireTime(0L) // epoch seconds; 0 or null means the key never expires
        .build());
    // Configure res.getCleartext() (returned only once) and res.getScimUrl() in the identity provider
} catch (DescopeException de) {
    // Handle the error
}

// Rotate: create a new key and revoke the existing SCIM keys for the same SSO configuration
try {
    SCIMAccessKeyResponse res = ss.rotateKey(SCIMAccessKeyRotateRequest.builder()
        .tenantId("tenant-id") // required
        .ssoId("sso-id")
        .revokeMode(ScimKeyRevokeMode.DEACTIVATE) // DELETE (the default) or DEACTIVATE
        .build());
    // res.getCleartext(), res.getScimUrl(), res.getRevokedKeyIds()
} catch (DescopeException de) {
    // Handle the error
}

// Load the SCIM keys of a tenant; pass null as the ssoId to load them across every SSO configuration
try {
    List<SCIMAccessKey> keys = ss.loadKeys("tenant-id", "sso-id");
    // keys.get(0).getKey(), keys.get(0).getSsoId()
} catch (DescopeException de) {
    // Handle the error
}

// Revoke every SCIM key of a tenant's SSO configuration. DEACTIVATE keeps them so they can be activated later.
try {
    List<String> revokedKeyIds = ss.revokeKeys("tenant-id", "sso-id", ScimKeyRevokeMode.DEACTIVATE);
} catch (DescopeException de) {
    // Handle the error
}

// Activate specific deactivated SCIM keys (up to 100)
try {
    List<String> activatedKeyIds = ss.activateKeys("tenant-id", "sso-id", Arrays.asList("key-id"));
} catch (DescopeException de) {
    // Handle the error
}

Manage Scope Claim Mapping

You can get, set and delete the project-wide mapping of OIDC scopes to JWT claims:

ScopeClaimMappingService scms = descopeClient.getManagementServices().getScopeClaimMappingService();

// Replace the whole mapping. Each claim value may be a static string or a {{...}} template.
// When two entries set the same claim name, the later entry wins.
try {
    scms.setScopeClaimMapping(Arrays.asList(
        ScopeClaimMappingEntry.builder()
            .scope("email")
            .claims(mapOf("email", "{{user.email}}"))
            .description("Adds the user's email")
            // Optional: limit a claim to some tokens; a claim without targets goes to every token
            .claimTargets(mapOf("email", ClaimTokenTargets.builder()
                .tokens(Arrays.asList(ClaimTokenTarget.ID_TOKEN, ClaimTokenTarget.USER_INFO))
                .build()))
            // Optional: add this scope to applications created from now on
            .addToNewApplications(true)
            .build()));
} catch (DescopeException de) {
    // Handle the error
}

// Get the mapping (an empty list when none is configured)
try {
    List<ScopeClaimMappingEntry> mappings = scms.getScopeClaimMapping();
} catch (DescopeException de) {
    // Handle the error
}

// Delete the mapping. This action is irreversible.
try {
    scms.deleteScopeClaimMapping();
} catch (DescopeException de) {
    // Handle the error
}

Manage Session Classifications

You can get, set, delete and load all session classifications, named sets of session rules applied to the users assigned to them. The name is the ID: unique per project and immutable.

SessionClassificationService scs = descopeClient.getManagementServices().getSessionClassificationService();

// Create or update a session classification by name. On a new name the defaults are applied;
// on an existing one, fields left unset keep their stored value.
try {
    SessionClassification c = scs.setSessionClassification(SessionClassification.builder()
        .name("contractors") // required
        .description("External contractors")
        .sessionTimeLimitRule(SessionTimeLimitRule.MIN_OF_TENANTS)
        .accessAllTenants(false)
        .maxConcurrentSessions(3) // 0 means unlimited
        .version(4) // optional: the version it was read at, to reject conflicting updates
        .build());
} catch (DescopeException de) {
    // Handle the error
}

// Get a session classification by name
try {
    SessionClassification c = scs.getSessionClassification("contractors");
    // c.getSessionTimeLimitRule(), c.getMaxConcurrentSessions(), c.getVersion()
} catch (DescopeException de) {
    // Handle the error
}

// Delete a session classification. Users assigned to it are left without one.
try {
    scs.deleteSessionClassification("contractors");
} catch (DescopeException de) {
    // Handle the error
}

// Load all session classifications
try {
    List<SessionClassification> all = scs.loadAllSessionClassifications();
} catch (DescopeException de) {
    // Handle the error
}

Code Examples

You can find various usage examples in the examples folder.

Setup

To run the examples, set your Project ID and Management Key by setting the DESCOPE_PROJECT_ID and DESCOPE_MANAGEMENT_KEY env vars or directly in the sample code. Find your Project ID in the Descope console. Find your management key in the Descope console.

export DESCOPE_PROJECT_ID=<ProjectID>
export DESCOPE_MANAGEMENT_KEY=<ManagementKey>
# Optional, only needed for authentication methods with disabled public access
export DESCOPE_AUTH_MANAGEMENT_KEY=<AuthManagementKey>

Alternatively, you can create a .env file in the working folder with your project ID and management key.

DESCOPE_PROJECT_ID=<ProjectID>
DESCOPE_MANAGEMENT_KEY=<ManagementKey>
DESCOPE_AUTH_MANAGEMENT_KEY=<AuthManagementKey>

Run an example

  1. Make sure that the main Descope java-sdk is installed in the local Maven. Run this in the main folder.

    mvn install
  2. Run this command in your project to build the example in the examples/management-cli folder.

    mvn package
  3. Run a specific example

    # CLI example
    java -jar target/management-cli-1.0.jar command-name -option1 -option2
    # For example to display 10 users:
    java -jar target/management-cli-1.0.jar user-search-all -l 10
    # Help is available on all commands and within the command itself:
    java -jar target/management-cli-1.0.jar -h
    java -jar target/management-cli-1.0.jar user-search-all -h

Using Visual Studio Code

To run Run and Debug using Visual Studio Code open the examples folder and run the ManagementCLI class

Unit Testing and Data Mocks

Java provides a very simple way to mock services and objects using the Mockito package. Here is a simple example of how you can mock a magic link verify response.

User user = new User("someUserName", MOCK_EMAIL, "+1-555-555-5555");
ApiProxy apiProxy = mock(ApiProxy.class); // Mock the proxy that actually sends the HTTP requests
var maskedEmailRes = new MaskedEmailRes(MOCK_MASKED_EMAIL); // Define expected response
doReturn(maskedEmailRes).when(apiProxy).post(any(), any(), any()); // When post is called, return mock response
try (MockedStatic<ApiProxyBuilder> mockedApiProxyBuilder = mockStatic(ApiProxyBuilder.class)) { // Mock proxy builder
    mockedApiProxyBuilder.when(() -> ApiProxyBuilder.buildProxy(any(), any())).thenReturn(apiProxy); // to return our mock proxy
    String signUp = magicLinkService.signUp(DeliveryMethod.EMAIL, MOCK_EMAIL, MOCK_DOMAIN, user); // call the service as you usually would
}

// Now mock the verify
ApiProxy apiProxy = mock(ApiProxy.class);
doReturn(MOCK_JWT_RESPONSE).when(apiProxy).post(any(), any(), any()); // Return the mock JWT response
doReturn(new SigningKeysResponse(Arrays.asList(MOCK_SIGNING_KEY))).when(apiProxy).get(any(), eq(SigningKeysResponse.class)); // Return mock key
var provider = mock(Provider.class);
when(provider.getProvidedKey()).thenReturn(mock(Key.class));

AuthenticationInfo authenticationInfo;
try (MockedStatic<ApiProxyBuilder> mockedApiProxyBuilder = mockStatic(ApiProxyBuilder.class)) {
    mockedApiProxyBuilder.when(() -> ApiProxyBuilder.buildProxy(any(), any())).thenReturn(apiProxy); // Return proxy when building
    try (MockedStatic<JwtUtils> mockedJwtUtils = mockStatic(JwtUtils.class)) {
        mockedJwtUtils.when(() -> JwtUtils.getToken(anyString(), any())).thenReturn(MOCK_TOKEN); // Return mock token instead of parsing
        authenticationInfo = magicLinkService.verify("SomeToken");
    }
}

Utils for your end to end (e2e) tests and integration tests

To ease your e2e tests, we exposed dedicated management methods. That way, you don't need to use 3rd party messaging services in order to receive sign-in/up Email, SMS, Voice call or WhatsApp, and avoid the need of parsing the code and token from them.

// User for test can be created, this user will be able to generate code/link without
// the need of 3rd party messaging services.
// Test user must have a loginID, other fields are optional.
// Roles should be set directly if no tenants exist, otherwise set
// on a per-tenant basis.
UserService us = descopeClient.getManagementServices().getUserService();
try {
    UserResponseDetails resp = us.createTestUser("desmond@descope.com", UserRequest.builder()
            .email("desmond@descope.com")
            .displayName("Desmond Copeland")
            .userTenants(Arrays.asList(
                AssociatedTenant.builder()
                    .tenantId("tenant-ID1")
                    .roleNames(Arrays.asList("role-name1")).build(),
                AssociatedTenant.builder()
                    .tenantId("tenant-ID2").build())).build());
} catch (DescopeException de) {
    // Handle the error
}

// Now test user got created, and this user will be available until you delete it,
// you can use any management operation for test user CRUD.
// You can also delete all test users.
try {
    us.deleteAllTestUsers();
} catch (DescopeException de) {
    // Handle the error
}

// OTP code can be generated for test user, for example:
try {
    OTPTestUserResponse res = us.generateOtpForTestUser("desmond@descope.com", DeliveryMethod.EMAIL);
    // Use res.getCode() for verify and establishing a session
} catch (DescopeException de) {
    // Handle the error
}

// Same as OTP, magic link can be generated for test user, for example:
try {
    MagicLinkTestUserResponse res = us.generateMagicLinkForTestUser("desmond@descope.com", "", DeliveryMethod.EMAIL);
    // Use res.getLink() to get the generated link. To get the actual token, use:
    // var params = UriUtils.splitQuery("https://example.com" + res.getLink());
    // var authInfo = magicLinkService.verify(params.get("t").get(0));

} catch (DescopeException de) {
    // Handle the error
}

// Enchanted link can be generated for test user, for example:
try {
    EnchantedLinkTestUserResponse res = us.generateEnchantedLinkForTestUser("desmond@descope.com", "");
    // Use res.getLink() to get the generated link. To get the actual token, use:
    // var params = UriUtils.splitQuery("https://example.com" + res.getLink());
    // enchantedLinkService.verify(params.get("t").get(0));
    // var authInfo = enchantedLinkService.getSession(res.getPendingRef());
} catch (DescopeException de) {
    // Handle the error
}

// Note 1: The generate code/link methods, work only for test users, will not work for regular users.
// Note 2: In case of testing sign-in / sign-up methods with test users, need to make sure to generate the code prior calling the sign-in / sign-up methods

// Embedded links can be created to directly receive a verifiable token without sending it.
// This token can then be verified using the magic link 'verify' function, either directly or through a flow.
UserService us = descopeClient.getManagementServices().getUserService();
MagicLinkService mls = descopeClient.getAuthenticationServices().getMagicLinkService();
try {
    String token - us.generateEmbeddedLink("desmond@descope.com", null /*custom claims if any */);
    var authInfo = mls.verify(token);
} catch (DescopeException de) {
    // Handle the error
}
token, err := descopeClient.Management.User().GenerateEmbeddedLink("desmond@descope.com", map[string]any{"key1":"value1"})

API Rate Limits

Handle API rate limits by catching the RateLimitExceededException. The exception includes the number of seconds until the next valid API call can take place.

MagicLinkService mls = descopeClient.getAuthenticationServices().getMagicLinkService();
try {
    mls.signUpOrIn(DeliveryMethod.EMAIL, "desmond@descope.com", "http://myapp.com/verify-magic-link");
} catch (RateLimitExceededException re) {
    // Use re.getRetryAfterSeconds() to determine time until retry
} catch (DescopeException de) {
    // Handle the error
}

Learn More

To learn more please see the Descope Documentation and API reference page.

Contact Us

If you need help you can email Descope Support

License

The Descope SDK for Java is licensed for use under the terms and conditions of the MIT license Agreement.

Releases

Used by

Contributors

Languages