Auth0 Java SDK

repository·master·Indexed 43 days ago

https://github.com/auth0/auth0-java

A Java client library for interacting with Auth0's Authentication and Management APIs, designed for server-side JVM applications. Version 5.3.0 provides the AuthAPI and ManagementApi clients for tenant management, user and role CRUD operations, and ID token verification for RS256 and HS256 signatures.

Tokens
81.8K
Snippets
301
Records
343
Agent score
55%

What's inside Auth0 Java

  1. Understand the scope of .fernignore

    master

    The .fernignore file does not protect the entire Management API. It only protects explicitly listed files and directories. Specifically, it protects:

    • The Authentication API
    • net/
    • exception/
    • utils/
    • json/auth/
    • Custom builders/token providers
    • Specific tests

    Everything else within the generated mgmt tree is subject to regeneration and will overwrite any manual changes.

  2. Construct clients using the Builder pattern

    master

    Public clients in this SDK are constructed using builder patterns rather than raw constructors. This ensures proper configuration of credentials and domains.

    • For the Authentication API, use AuthAPI.newBuilder(domain, clientId, clientSecret).build().
    • For the Management API, use ManagementApi.builder() and provide credentials via .token(token) or .clientCredentials(clientId, clientSecret).
    // Authentication API
    AuthAPI authApi = AuthAPI.newBuilder("your-domain.auth0.com", "CLIENT_ID", "CLIENT_SECRET").build();
    
    // Management API
    ManagementApi managementApi = ManagementApi.builder()
        .domain("your-domain.auth0.com")
        .clientCredentials("CLIENT_ID", "CLIENT_SECRET")
        .build();
  3. Understand Management API resource clients and patterns

    master

    The Management API follows specific architectural patterns for resource access:

    • Lazy Resource Clients: Resource clients (e.g., usersClient, rolesClient) are exposed as Supplier<XxxClient> types. They are constructed lazily from ClientOptions when accessed.
    • Sync/Async/Raw Variants: Most resource clients provide three variants to suit different needs:
      1. A standard synchronous client.
      2. An AsyncXxxClient for asynchronous operations.
      3. A RawXxxClient which returns the raw HTTP response.
    • Typed Responses: API calls return specific, typed response objects (e.g., GetUserResponseContent) instead of generic maps.
    • HTTP Layer: All network communication is abstracted through the com.auth0.net layer. Do not instantiate OkHttp clients directly in your feature code.
  4. How to write and maintain tests

    master

    When adding or modifying tests, distinguish between generated and hand-maintained code:

    Generated Tests

    Most Management API tests are Fern-generated and reside under the mgmt tree. Do not hand-edit these files; any changes to their behavior must be made in the specification/generator.

    Hand-maintained Tests

    Hand-maintained tests (which are listed in .fernignore to prevent clobbering) include:

    • Files in src/test/java/com/auth0/client/auth/ (Authentication API)
    • Specific management files like ManagementApiBuilderTest.java, DynamicTokenManagementTest.java, OAuthTokenSupplierTest.java, CustomDomainInterceptorTest.java, and CustomDomainHeaderIntegrationTest.java.

    Shared Infrastructure

    Reuse existing shared test infrastructure instead of creating new HTTP-assertion helpers. Key utilities are located under com/auth0/client/:

    • MockServer
    • RecordedRequestMatcher
    • UrlMatcher
    • AssertsUtil
  5. Manage Auth0 Actions

    master

    Auth0 Actions allow you to extend flows by running custom code. You can create, list, retrieve, update, deploy, test, and delete actions using the client.actions() API.

    Lifecycle Note: Once an action is created, it must be deployed to create an immutable version, and then bound to a trigger before it will execute in a flow. Updating an action that is currently bound to a trigger will not affect user flows until the action is deployed again.

  6. Use OptionalNullable<T> for nullable response fields

    master

    In v5, response fields that are nullable in the Auth0 API use OptionalNullable<T>. This type provides a way to distinguish between a field being absent and a field being explicitly null.

    Available Methods

    • isPresent(): Returns true if a value is present.
    • isAbsent(): Returns true if the field was omitted.
    • isNull(): Returns true if the API explicitly returned null.
    • wasSpecified(): Returns true if the field was present in the response (either as a value or as null).
    • get(): Returns the value. Throws IllegalStateException if the field is absent or null.
    • getValueOrNull(): Returns the value or null.
    • orElse(fallback): Returns fallback if the field was absent, but returns null if the field was explicitly null.
    • map(function): Maps the value if present.
    • toOptional(): Converts the OptionalNullable to a standard java.util.Optional. This treats both 'absent' and 'explicit-null' states as an empty Optional.

    Affected Getters

    • Session/UpdateSession/GetSessionResponseContent: getCreatedAt(), getUpdatedAt(), getAuthenticatedAt(), getIdleExpiresAt(), getExpiresAt(), getLastInteractedAt()
    • Refresh Token (Get/Update/ResponseContent): getCreatedAt(), getIdleExpiresAt(), getExpiresAt(), getLastExchangedAt()
    • SessionAuthenticationSignal: getTimestamp()
    • FlowActionFlowMapValueParams: getFallback()
    // v4 approach (will fail in v5)
    Optional<SessionDate> created = session.getCreatedAt();
    session.getCreatedAt().ifPresent(this::audit);
    
    // v5 approach: simplest migration using .toOptional()
    Optional<SessionDate> created = session.getCreatedAt().toOptional();
    session.getCreatedAt().toOptional().ifPresent(this::audit);
    
    // v5 approach: distinguishing between absent and explicit null
    OptionalNullable<SessionDate> expires = session.getExpiresAt();
    if (expires.isPresent()) {
        handle(expires.get());
    } else if (expires.isNull()) {
        // the API explicitly returned null for this field
    } else {
        // the API omitted the field
    }
  7. Java version compatibility requirements

    master

    The library is strictly compatible with Java 8 (sourceCompatibility = 1.8). When contributing or writing code for this project, do not use syntax introduced in later versions, such as:

    • var (local variable type inference)
    • Records
    • Sealed types
    • Switch expressions
  8. Perform asynchronous operations

    master

    The SDK provides two ways to perform asynchronous operations depending on which API you are using.

    Management API

    The Management API provides a dedicated AsyncManagementApi client. All operations on this client return a CompletableFuture.

    Authentication API

    The AuthAPI supports asynchronous execution via the .executeAsync() method on request objects, which returns a CompletableFuture.

    // Management API Async
    AsyncManagementApi asyncClient = new AsyncManagementApi(clientOptions);
    CompletableFuture<GetUserResponseContent> future = asyncClient.users().get("user_id");
    future.thenAccept(user -> {
        System.out.println(user.getEmail());
    });
    
    // Authentication API Async
    AuthAPI auth = AuthAPI.newBuilder("{YOUR_DOMAIN}", "{YOUR_CLIENT_ID}", "{YOUR_CLIENT_SECRET}").build();
    CompletableFuture<TokenHolder> future = auth.requestToken("https://{YOUR_DOMAIN}/api/v2/").executeAsync();
    future.thenAccept(holder -> {
        String accessToken = holder.getBody().getAccessToken();
    });
  9. Configure Branding Theme properties

    master

    When creating or updating a branding theme, you can customize several visual aspects using the following configuration objects:

    • BrandingThemeBorders: Controls the radius and weight of borders for buttons, inputs, and widgets. Supports styles like BrandingThemeBordersButtonsStyleEnum.PILL.
    • BrandingThemeColors: Defines the color palette for various UI elements including bodyText, error, header, primaryButton, widgetBackground, and inputBackground.
    • BrandingThemeFonts: Manages typography. You can set a global fontUrl and specify individual styles (bold, size) for bodyText, buttonsText, inputLabels, links, subtitle, and title.
    • BrandingThemePageBackground: Configures the page's appearance using backgroundColor, backgroundImageUrl, and pageLayout (e.g., BrandingThemePageBackgroundPageLayoutEnum.CENTER).
    • BrandingThemeWidget: Customizes the Auth0 widget, including logoUrl, logoHeight, logoPosition, headerTextAlignment, and socialButtonsLayout.
  10. Branch and Release naming conventions

    master

    The project uses specific prefixes for automated workflows:

    • Release Branches: Use the release/* prefix (e.g., release/1.2.3). The automated release workflow only triggers for merged Pull Requests whose head branch starts with this prefix.
    • Release Commits: Automated release commits are titled using the format Release X.Y.Z (e.g., Release 4.2.0).
    • SDK Regeneration: PRs resulting from automated SDK updates are typically titled SDK regeneration.