Skip to content

clerk/clerk-sdk-java

Repository files navigation

The most comprehensive User Management Platform



The Clerk Java library provides convenient access to the Clerk REST API from from a Java application. The library includes type definitions for all request params and response fields, and is powered by Apache Httpclient.

Summary

Clerk Backend API: The Clerk REST Backend API, meant to be accessed by backend servers.

Versions

When the API changes in a way that isn't compatible with older versions, a new version is released. Each version is identified by its release date, e.g. 2021-02-05. For more information, please see Clerk API Versions.

Please see https://clerk.com/docs for more information.

More information about the API can be found at https://clerk.com/docs

Table of Contents

SDK Installation

Getting started

JDK 11 or later is required.

The samples below show how a published SDK artifact is used:

Gradle:

implementation 'com.clerk:backend-api:1.5.0'

Maven:

<dependency>
    <groupId>com.clerk</groupId>
    <artifactId>backend-api</artifactId>
    <version>1.5.0</version>
</dependency>

How to build

After cloning the git repository to your file system you can build the SDK artifact from source to the build directory by running ./gradlew build on *nix systems or gradlew.bat on Windows systems.

If you wish to build from source and publish the SDK artifact to your local Maven repository (on your filesystem) then use the following command (after cloning the git repo locally):

On *nix:

./gradlew publishToMavenLocal -Pskip.signing

On Windows:

gradlew.bat publishToMavenLocal -Pskip.signing

SDK Example Usage

Example

package hello.world;

import com.clerk.backend_api.Clerk;
import com.clerk.backend_api.models.errors.ClerkErrors;
import com.clerk.backend_api.models.operations.GetEmailAddressResponse;
import java.lang.Exception;

public class Application {

    public static void main(String[] args) throws ClerkErrors, Exception {

        Clerk sdk = Clerk.builder()
                .bearerAuth("<YOUR_BEARER_TOKEN_HERE>")
            .build();

        GetEmailAddressResponse res = sdk.emailAddresses().get()
                .emailAddressId("<id>")
                .call();

        if (res.emailAddress().isPresent()) {
            // handle response
        }
    }
}

Authentication

Per-Client Security Schemes

This SDK supports the following security scheme globally:

Name Type Scheme
bearerAuth http HTTP Bearer

To authenticate with the API the bearerAuth parameter must be set when initializing the SDK client instance. For example:

package hello.world;

import com.clerk.backend_api.Clerk;
import com.clerk.backend_api.models.operations.GetPublicInterstitialResponse;
import java.lang.Exception;

public class Application {

    public static void main(String[] args) throws Exception {

        Clerk sdk = Clerk.builder()
                .bearerAuth("<YOUR_BEARER_TOKEN_HERE>")
            .build();

        GetPublicInterstitialResponse res = sdk.miscellaneous().getInterstitial()
                .frontendApi("<value>")
                .publishableKey("<value>")
                .call();

        // handle response
    }
}

Request Authentication

Use the authenticateRequest method to authenticate a request from your app's frontend (when using a Clerk frontend SDK) to Clerk's Backend API. For example the following utility function checks if the user is effectively signed in:

import java.net.http.HttpRequest;
import com.clerk.backend_api.helpers.jwks.AuthenticateRequest;
import com.clerk.backend_api.helpers.jwks.AuthenticateRequestOptions;
import com.clerk.backend_api.helpers.jwks.RequestState;

public class UserAuthentication {

    public static boolean isSignedIn(HttpRequest request) {
        RequestState requestState = AuthenticateRequest.authenticateRequest(request, AuthenticateRequestOptions
                .secretKey(System.getenv("CLERK_SECRET_KEY"))
                .authorizedParty("https://example.com")
                .build());
        return state.isSignedIn();
    }

If the request is correctly authenticated, the token's claims are made available in requestState.claims(). Otherwise the reason for the token verification failure is given by requestState.reason().

Available Resources and Operations

Available methods
  • delete - Delete identifier from allow-list
  • list - List all identifiers on the block-list
  • list - List all clients ⚠️ Deprecated
  • verify - Verify a client
  • get - Get a client
  • list - List all instance domains
  • add - Add a domain
  • delete - Delete a satellite domain
  • update - Update a domain
  • create - Create an email address
  • get - Retrieve an email address
  • delete - Delete an email address
  • update - Update an email address
  • upsert - Update a template for a given type and slug ⚠️ Deprecated
  • list - List all templates ⚠️ Deprecated
  • revert - Revert a template ⚠️ Deprecated
  • get - Retrieve a template ⚠️ Deprecated
  • toggleTemplateDelivery - Toggle the delivery by Clerk for a template of a given type and slug ⚠️ Deprecated
  • create - Create an invitation
  • list - List all invitations
  • revoke - Revokes an invitation
  • get - Retrieve the JSON Web Key Set of the instance
  • list - List all templates
  • create - Create a JWT template
  • get - Retrieve a template
  • update - Update a JWT template
  • delete - Delete a Template
  • list - Get a list of OAuth applications for an instance
  • create - Create an OAuth application
  • get - Retrieve an OAuth application by ID
  • update - Update an OAuth application
  • delete - Delete an OAuth application
  • rotateSecret - Rotate the client secret of the given OAuth application
  • update - Update an organization domain.
  • create - Create a new organization domain.
  • list - Get a list of all domains of an organization.
  • delete - Remove a domain from an organization.
  • getAll - Get a list of organization invitations for the current instance
  • create - Create and send an organization invitation
  • list - Get a list of organization invitations
  • bulkCreate - Bulk create and send organization invitations
  • listPending - Get a list of pending organization invitations ⚠️ Deprecated
  • get - Retrieve an organization invitation by ID
  • revoke - Revoke a pending organization invitation
  • create - Create a new organization membership
  • list - Get a list of all members of an organization
  • update - Update an organization membership
  • delete - Remove a member from an organization
  • updateMetadata - Merge and update organization membership metadata
  • getAll - Get a list of all organization memberships within an instance.
  • list - Get a list of organizations for an instance
  • create - Create an organization
  • get - Retrieve an organization by ID or slug
  • update - Update an organization
  • delete - Delete an organization
  • mergeMetadata - Merge and update metadata for an organization
  • uploadLogo - Upload a logo for the organization
  • deleteLogo - Delete the organization's logo.
  • create - Create a phone number
  • get - Retrieve a phone number
  • delete - Delete a phone number
  • update - Update a phone number
  • verify - Verify the proxy configuration for your domain
  • create - Create a redirect URL
  • get - Retrieve a redirect URL
  • delete - Delete a redirect URL
  • list - List all redirect URLs
  • list - Get a list of SAML Connections for an instance
  • create - Create a SAML Connection
  • get - Retrieve a SAML Connection by ID
  • update - Update a SAML Connection
  • delete - Delete a SAML Connection
  • create - Create sign-in token
  • revoke - Revoke the given sign-in token
  • preview - Preview changes to a template ⚠️ Deprecated
  • create - Retrieve a new testing token

Error Handling

Handling errors in this SDK should largely match your expectations. All operations return a response object or raise an exception.

By default, an API error will throw a models/errors/SDKError exception. When custom error responses are specified for an operation, the SDK may also throw their associated exception. You can refer to respective Errors tables in SDK docs for more details on possible exception types for each operation. For example, the verify method throws the following exceptions:

Error Type Status Code Content Type
models/errors/ClerkErrors 400, 401, 404 application/json
models/errors/SDKError 4XX, 5XX */*

Example

package hello.world;

import com.clerk.backend_api.Clerk;
import com.clerk.backend_api.models.errors.ClerkErrors;
import com.clerk.backend_api.models.operations.VerifyClientRequestBody;
import com.clerk.backend_api.models.operations.VerifyClientResponse;
import java.lang.Exception;

public class Application {

    public static void main(String[] args) throws ClerkErrors, Exception {

        Clerk sdk = Clerk.builder()
                .bearerAuth("<YOUR_BEARER_TOKEN_HERE>")
            .build();

        VerifyClientRequestBody req = VerifyClientRequestBody.builder()
                .build();

        VerifyClientResponse res = sdk.clients().verify()
                .request(req)
                .call();

        if (res.client().isPresent()) {
            // handle response
        }
    }
}

Server Selection

Override Server URL Per-Client

The default server can also be overridden globally using the .serverURL(String serverUrl) builder method when initializing the SDK client instance. For example:

package hello.world;

import com.clerk.backend_api.Clerk;
import com.clerk.backend_api.models.operations.GetPublicInterstitialResponse;
import java.lang.Exception;

public class Application {

    public static void main(String[] args) throws Exception {

        Clerk sdk = Clerk.builder()
                .serverURL("https://api.clerk.com/v1")
            .build();

        GetPublicInterstitialResponse res = sdk.miscellaneous().getInterstitial()
                .frontendApi("<value>")
                .publishableKey("<value>")
                .call();

        // handle response
    }
}

Development

Maturity

This SDK is in beta, and there may be breaking changes between versions without a major version update. Therefore, we recommend pinning usage to a specific package version. This way, you can install the same version each time without breaking changes unless you are intentionally looking for the latest version.

Contributions

While we value open-source contributions to this SDK, this library is generated programmatically. Feel free to open a PR or a Github issue as a proof of concept and we'll do our best to include it in a future release!

SDK Created by Speakeasy