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.
Clerk Backend API: The Clerk REST Backend API, meant to be accessed by backend servers.
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. 2024-10-01
. 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
- SDK Installation
- SDK Example Usage
- Authentication
- Request Authentication
- Available Resources and Operations
- Retries
- Error Handling
- Server Selection
- Development
JDK 11 or later is required.
The samples below show how a published SDK artifact is used:
Gradle:
implementation 'com.clerk:backend-api:2.0.0'
Maven:
<dependency>
<groupId>com.clerk</groupId>
<artifactId>backend-api</artifactId>
<version>2.0.0</version>
</dependency>
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
package hello.world;
import com.clerk.backend_api.Clerk;
import com.clerk.backend_api.models.operations.GetPublicInterstitialRequest;
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()
.build();
GetPublicInterstitialRequest req = GetPublicInterstitialRequest.builder()
.build();
GetPublicInterstitialResponse res = sdk.miscellaneous().getPublicInterstitial()
.request(req)
.call();
// handle response
}
}
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.GetPublicInterstitialRequest;
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();
GetPublicInterstitialRequest req = GetPublicInterstitialRequest.builder()
.build();
GetPublicInterstitialResponse res = sdk.miscellaneous().getPublicInterstitial()
.request(req)
.call();
// handle response
}
}
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 requestState.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 methods
- list - List all identifiers on the allow-list
- create - Add identifier to the allow-list
- delete - Delete identifier from allow-list
- updateInstanceSettings - Update instance settings
updateProductionInstanceDomain- Update production instance domain⚠️ Deprecated
- list - List all identifiers on the block-list
- create - Add identifier to the block-list
- delete - Delete identifier from block-list
- 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⚠️ Deprecatedget- Retrieve a template⚠️ Deprecatedrevert- Revert a template⚠️ DeprecatedtoggleTemplateDelivery- Toggle the delivery by Clerk for a template of a given type and slug⚠️ Deprecated
- get - Fetch the current instance
- update - Update instance settings
- updateRestrictions - Update instance restrictions
- changeDomain - Update production instance domain
- updateOrganizationSettings - Update instance organization settings
- create - Create an invitation
- list - List all invitations
- bulkCreate - Create multiple invitations
- revoke - Revokes an invitation
- getJWKS - 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
- getPublicInterstitial - Returns the markup for the interstitial page
- 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
- create - Create a new organization domain.
- list - Get a list of all domains of an organization.
- update - Update an organization domain.
- 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
- 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
- list - List all redirect URLs
- create - Create a redirect URL
- get - Retrieve a redirect URL
- delete - Delete a redirect URL
- 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
- list - List all sessions
- create - Create a new active session
- get - Retrieve a session
- revoke - Revoke a session
verify- Verify a session⚠️ Deprecated- createToken - Create a session token
- createTokenFromTemplate - Create a session token from a jwt template
preview- Preview changes to a template⚠️ Deprecated
- create - Retrieve a new testing token
- list - List all users
- create - Create a new user
- count - Count users
- get - Retrieve a user
- update - Update a user
- delete - Delete a user
- ban - Ban a user
- unban - Unban a user
- lock - Lock a user
- unlock - Unlock a user
- setProfileImage - Set user profile image
- deleteProfileImage - Delete user profile image
- updateMetadata - Merge and update a user's metadata
- getOAuthAccessToken - Retrieve the OAuth access token of a user
- getOrganizationMemberships - Retrieve all memberships for a user
- getOrganizationInvitations - Retrieve all invitations for a user
- verifyPassword - Verify the password of a user
- verifyTotp - Verify a TOTP or backup code for a user
- disableMfa - Disable a user's MFA methods
- deleteBackupCodes - Disable all user's Backup codes
- deletePasskey - Delete a user passkey
- deleteWeb3Wallet - Delete a user web3 wallet
- deleteTOTP - Delete all the user's TOTPs
- deleteExternalAccount - Delete External Account
- getInstanceOrganizationMemberships - Get a list of all organization memberships within an instance.
- createSvixApp - Create a Svix app
- deleteSvixApp - Delete a Svix app
- generateSvixAuthURL - Create a Svix Dashboard URL
Some of the endpoints in this SDK support retries. If you use the SDK without any configuration, it will fall back to the default retry strategy provided by the API. However, the default retry strategy can be overridden on a per-operation basis, or across the entire SDK.
To change the default retry strategy for a single API call, you can provide a RetryConfig
object through the retryConfig
builder method:
package hello.world;
import com.clerk.backend_api.Clerk;
import com.clerk.backend_api.models.operations.GetPublicInterstitialRequest;
import com.clerk.backend_api.models.operations.GetPublicInterstitialResponse;
import com.clerk.backend_api.utils.BackoffStrategy;
import com.clerk.backend_api.utils.RetryConfig;
import java.lang.Exception;
import java.util.concurrent.TimeUnit;
public class Application {
public static void main(String[] args) throws Exception {
Clerk sdk = Clerk.builder()
.build();
GetPublicInterstitialRequest req = GetPublicInterstitialRequest.builder()
.build();
GetPublicInterstitialResponse res = sdk.miscellaneous().getPublicInterstitial()
.request(req)
.retryConfig(RetryConfig.builder()
.backoff(BackoffStrategy.builder()
.initialInterval(1L, TimeUnit.MILLISECONDS)
.maxInterval(50L, TimeUnit.MILLISECONDS)
.maxElapsedTime(1000L, TimeUnit.MILLISECONDS)
.baseFactor(1.1)
.jitterFactor(0.15)
.retryConnectError(false)
.build())
.build())
.call();
// handle response
}
}
If you'd like to override the default retry strategy for all operations that support retries, you can provide a configuration at SDK initialization:
package hello.world;
import com.clerk.backend_api.Clerk;
import com.clerk.backend_api.models.operations.GetPublicInterstitialRequest;
import com.clerk.backend_api.models.operations.GetPublicInterstitialResponse;
import com.clerk.backend_api.utils.BackoffStrategy;
import com.clerk.backend_api.utils.RetryConfig;
import java.lang.Exception;
import java.util.concurrent.TimeUnit;
public class Application {
public static void main(String[] args) throws Exception {
Clerk sdk = Clerk.builder()
.retryConfig(RetryConfig.builder()
.backoff(BackoffStrategy.builder()
.initialInterval(1L, TimeUnit.MILLISECONDS)
.maxInterval(50L, TimeUnit.MILLISECONDS)
.maxElapsedTime(1000L, TimeUnit.MILLISECONDS)
.baseFactor(1.1)
.jitterFactor(0.15)
.retryConnectError(false)
.build())
.build())
.build();
GetPublicInterstitialRequest req = GetPublicInterstitialRequest.builder()
.build();
GetPublicInterstitialResponse res = sdk.miscellaneous().getPublicInterstitial()
.request(req)
.call();
// handle response
}
}
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 | */* |
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()
.token("<value>")
.build();
VerifyClientResponse res = sdk.clients().verify()
.request(req)
.call();
if (res.client().isPresent()) {
// handle response
}
}
}
The default server can 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.GetPublicInterstitialRequest;
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();
GetPublicInterstitialRequest req = GetPublicInterstitialRequest.builder()
.build();
GetPublicInterstitialResponse res = sdk.miscellaneous().getPublicInterstitial()
.request(req)
.call();
// handle response
}
}
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.
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!