> ## Documentation Index
> Fetch the complete documentation index at: https://auth0.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Add Login to Your Java EE Application

> Add Auth0 login, logout, and user profile to a Java EE 8 web application using the Security API

> [accordion] Use AI to integrate Auth0
>
> If you use an AI coding assistant like Claude Code, Cursor, or GitHub Copilot, you can add Auth0 authentication automatically in minutes using [agent skills](https://agentskills.io/home).
>
> **Install:**
>
> ```bash theme={null}
> npx skills add auth0/agent-skills --skill auth0
> ```
>
> **Then ask your AI assistant:**
>
> ```text theme={null}
> Add Auth0 authentication to my Java EE app
> ```
>
> Your AI assistant will automatically create your Auth0 application, fetch credentials, add the Auth0 Java MVC Commons SDK dependency, configure authentication with the Java EE 8 Security API, and implement login/logout flows. [Full agent skills documentation →](https://auth0.com/docs/quickstart/agent-skills.md)

> [!NOTE]
>
> **Prerequisites:**
>
> * [Java Development Kit (JDK)](https://www.oracle.com/java/technologies/downloads/) 11 or newer
> * [Apache Maven](https://maven.apache.org/download.cgi) 3.x
> * A Java EE 8 compatible application server (e.g., [WildFly](https://www.wildfly.org/) 14+, [Payara](https://www.payara.fish/) 5+, or [GlassFish](https://glassfish.org/) 5+)
> * An Auth0 account — [sign up for free](https://auth0.com/signup)

## Get Started

Auth0 allows you to quickly add authentication and access user profile information in your application. This guide demonstrates how to integrate Auth0 with any new or existing Java EE application using the `auth0-java-mvc-common` SDK and the Java EE 8 Security API.

**1. Create a new project**

Generate a new Maven WAR project:

```shellscript theme={null}
mvn archetype:generate \
  -DgroupId=com.auth0.example \
  -DartifactId=java-ee-auth0-app \
  -DarchetypeArtifactId=maven-archetype-webapp \
  -DinteractiveMode=false
```

Navigate into the project directory:

```shellscript theme={null}
cd java-ee-auth0-app
```

Create the Java source directories:

```shellscript theme={null}
mkdir -p src/main/java/com/auth0/example/security
mkdir -p src/main/java/com/auth0/example/web
mkdir -p src/main/webapp/WEB-INF/jsp
```

**2. Install the Auth0 SDK**

Replace the contents of your `pom.xml` with the following:

```xml pom.xml expandable lines theme={null}
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
         http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.auth0.example</groupId>
    <artifactId>java-ee-auth0-app</artifactId>
    <packaging>war</packaging>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <failOnMissingWebXml>false</failOnMissingWebXml>
        <version.wildfly>23.0.2.Final</version.wildfly>
    </properties>

    <dependencies>
        <dependency>
            <groupId>com.auth0</groupId>
            <artifactId>mvc-auth-commons</artifactId>
            <version>[1.0, 2.0)</version>
        </dependency>
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-api</artifactId>
            <version>8.0.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.security.enterprise</groupId>
            <artifactId>javax.security.enterprise-api</artifactId>
            <version>1.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.16.0</version>
        </dependency>
    </dependencies>

    <build>
        <finalName>java-ee-auth0-app</finalName>
        <plugins>
            <plugin>
                <groupId>org.wildfly.plugins</groupId>
                <artifactId>wildfly-maven-plugin</artifactId>
                <version>4.2.0.Final</version>
                <configuration>
                    <version>${version.wildfly}</version>
                    <javaOpts>
                        <javaOpt>-Djboss.http.port=8080</javaOpt>
                    </javaOpts>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
```

The `javaee-api` and `javax.security.enterprise-api` dependencies are `provided` because the Java EE 8 application server supplies their implementations at runtime.

**3. Setup your Auth0 Application**

> [tab] Dashboard
>
> 1. Go to the [Auth0 Dashboard](https://manage.auth0.com/#/applications) and navigate to **Applications > Applications > Create Application**.
> 2. Enter a name for your application (e.g., "My Java EE App").
> 3. Select **Regular Web Applications** as the application type.
> 4. Choose **Create**.
> 5. Open the **Settings** tab.
> 6. Note the **Domain**, **Client ID**, and **Client Secret** values.
> 7. Scroll down to **Application URIs** and set:
>    * **Allowed Callback URLs**: `http://localhost:8080/callback`
>    * **Allowed Logout URLs**: `http://localhost:8080/`
> 8. Choose **Save Changes**.

> [!NOTE]
>
> Make sure to [set up connections](https://auth0.com/docs/get-started/applications/set-up-database-connections.md) for your application so users can log in using their preferred identity provider.

**4. Configure authentication**

Update your `web.xml` to store Auth0 configuration as JNDI environment entries. Replace the placeholder values with the **Domain**, **Client ID**, and **Client Secret** from your Auth0 Application Settings. Create a `jboss-web.xml` to configure the JASPIC security domain required by the Java EE 8 Security API, an `Auth0AuthenticationConfig.java` CDI bean to read the configuration from JNDI, and an `Auth0AuthenticationProvider.java` CDI producer to build the `AuthenticationController`.

> [!NOTE]
>
> Do not include `https://` in your `auth0.domain` value. Use only the domain and region. For example: `dev-abc123.us.auth0.com`.

**5. Implement Java EE Security**

The Java EE 8 Security API uses `HttpAuthenticationMechanism` to handle authentication. You need to provide custom implementations of several security interfaces. The `@AutoApplySession` annotation enables the container to create a session for the authenticated user, so they remain logged in across requests.

**6. Add login and logout functionality**

Create the servlets for login, callback, and logout. The `LoginServlet` builds the Auth0 authorization URL and redirects the user. The `CallbackServlet` handles the redirect after authentication — the `Auth0AuthenticationMechanism` intercepts this request first to exchange the authorization code for tokens, so the servlet only needs to redirect. The `LogoutServlet` clears the session and redirects to the Auth0 logout endpoint.

**7. Create the user interface**

Create the servlets and JSP pages for the home and profile views. The `HomeServlet` checks for an authenticated principal and sets the profile claims on the request. The `ProfileServlet` displays the user's profile and JWT claims, or redirects to login if not authenticated.

**8. Run your application**

Build and run the application using the WildFly Maven plugin:

```shellscript theme={null}
mvn clean wildfly:run
```

Your application should start and display the URL it's listening on:

```
INFO  [org.jboss.as] WFLYSRV0025: WildFly started
```

Open your browser to [http://localhost:8080](http://localhost:8080). Click the **Login** link in the navigation bar. You will be redirected to the Auth0 login page. After authenticating, you will be redirected to the [profile page](http://localhost:8080/profile) where your user information and JWT claims are displayed.

> [!NOTE]
>
> The sample uses JSP and is tested with the [WildFly](https://wildfly.org/) application server. You may need to adjust some steps if you are using a different Java EE 8 compatible container.

> [!TIP]
>
> **Checkpoint**
>
> You should now have a fully functional Auth0-protected Java EE application running on [http://localhost:8080](http://localhost:8080). Users can log in, view their profile, and log out.

***

## Advanced Usage

> [accordion] Access User Profile Information
>
> The `Auth0JwtPrincipal` is available via `request.getUserPrincipal()` in any servlet. The `ProfileServlet` demonstrates how to access the decoded ID token claims:
>
> ```java theme={null}
> Principal principal = request.getUserPrincipal();
>
> if (principal instanceof Auth0JwtPrincipal) {
>     Auth0JwtPrincipal auth0JwtPrincipal = (Auth0JwtPrincipal) principal;
>     DecodedJWT idToken = auth0JwtPrincipal.getIdToken();
>
>     String name = idToken.getClaim("name").asString();
>     String email = idToken.getClaim("email").asString();
>     String picture = idToken.getClaim("picture").asString();
>     String sub = idToken.getSubject();
> }
> ```
>
> Common claims available in the ID token:
>
> * `name` — user's full display name
> * `email` — user's email address
> * `picture` — URL to the user's profile picture
> * `sub` — unique identifier for the user (Auth0 user ID)

> [accordion] Customize Login Parameters
>
> Add custom parameters to the authorization URL when building it in your `LoginServlet`:
>
> ```java src/main/java/com/auth0/example/web/LoginServlet.java theme={null}
> String authURL = authenticationController
>         .buildAuthorizeUrl(request, response, callbackUrl)
>         .withScope(config.getScope())
>         .withAudience("https://your-api.example.com")
>         .withParameter("screen_hint", "signup")
>         .withParameter("ui_locales", "fr")
>         .build();
> ```
>
> Use `.withAudience()` to request an access token for a specific API. Use `.withParameter()` for any additional [authorization parameters](https://auth0.com/docs/api/authentication.md#authorize-application) supported by Auth0.

> [accordion] Store Tokens for API Calls
>
> To access the raw tokens for API calls, modify the `Auth0AuthenticationMechanism` to store tokens in the session:
>
> ```java src/main/java/com/auth0/example/security/Auth0AuthenticationMechanism.java theme={null}
> if (isCallbackRequest(httpServletRequest)) {
>     try {
>         Tokens tokens = authenticationController.handle(
>                 httpServletRequest, httpServletResponse);
>
>         httpServletRequest.getSession().setAttribute(
>                 "accessToken", tokens.getAccessToken());
>
>         Auth0JwtCredential auth0JwtCredential =
>                 new Auth0JwtCredential(tokens.getIdToken());
>         CredentialValidationResult result =
>                 identityStoreHandler.validate(auth0JwtCredential);
>         return httpMessageContext.notifyContainerAboutLogin(result);
>     } catch (IdentityVerificationException e) {
>         return httpMessageContext.responseUnauthorized();
>     }
> }
> ```
>
> Then retrieve the access token when calling a protected API:
>
> ```java theme={null}
> String accessToken = (String) request.getSession().getAttribute("accessToken");
> URL url = new URL("https://your-api.example.com/data");
> HttpURLConnection conn = (HttpURLConnection) url.openConnection();
> conn.setRequestProperty("Authorization", "Bearer " + accessToken);
> ```

> [accordion] Log In to an Organization
>
> Configure the `AuthenticationController` with an organization ID or name to restrict login to a specific [Auth0 Organization](https://auth0.com/docs/organizations.md):
>
> ```java src/main/java/com/auth0/example/security/Auth0AuthenticationProvider.java theme={null}
> @Produces
> public AuthenticationController authenticationController(Auth0AuthenticationConfig config) {
>     JwkProvider jwkProvider = new JwkProviderBuilder(config.getDomain()).build();
>     return AuthenticationController.newBuilder(
>                     config.getDomain(), config.getClientId(), config.getClientSecret())
>             .withJwkProvider(jwkProvider)
>             .withOrganization("org_YOUR_ORG_ID")
>             .build();
> }
> ```
>
> The SDK automatically validates the `org_id` or `org_name` claim in the ID token to ensure it matches the configured organization.

***

## Additional Resources

> [card] [Auth0 Java MVC SDK](https://github.com/auth0/auth0-java-mvc-common)
>
> Source code and issue tracker

> [card] [API Reference (JavaDoc)](https://javadoc.io/doc/com.auth0/mvc-auth-commons)
>
> Detailed API documentation

> [card] [Community Forum](https://community.auth0.com/)
>
> Get help from the Auth0 community

> [card] [Java EE Sample App](https://github.com/auth0-samples/auth0-java-ee-sample/tree/master/01-Login)
>
> Complete sample application on GitHub

***

## Common Issues

> [accordion] State mismatch error on callback
>
> If you receive an `a0.invalid_state` error after login, the state cookie was not found or does not match the state returned from Auth0.
>
> Verify that:
>
> * Your callback URL in the Auth0 Dashboard exactly matches the URL your application constructs, including the port number and protocol.
> * Your browser is not blocking third-party cookies.
> * No reverse proxy or middleware is stripping `Set-Cookie` headers from responses.
>
> Ensure you are using the three-argument version of both `buildAuthorizeUrl` and `handle`, which uses cookie-based state storage:
>
> ```java theme={null}
> // Correct — uses cookies for state
> authenticationController.buildAuthorizeUrl(request, response, callbackUrl)
> authenticationController.handle(httpServletRequest, httpServletResponse)
> ```

> [accordion] CDI beans not discovered
>
> If you see errors about injection failures or beans not being found, ensure that:
>
> * Your application server supports CDI 2.0 (part of Java EE 8)
> * All security classes (`Auth0AuthenticationConfig`, `Auth0AuthenticationProvider`, `Auth0JwtIdentityStore`, `Auth0AuthenticationMechanism`) are annotated with `@ApplicationScoped`
> * `src/main/webapp/WEB-INF/jboss-web.xml` exists with the `jaspitest` security domain configured
>
> ```xml src/main/webapp/WEB-INF/jboss-web.xml theme={null}
> <jboss-web>
>     <security-domain>jaspitest</security-domain>
>     <context-root>/</context-root>
> </jboss-web>
> ```
>
> The `jaspitest` security domain is required for WildFly to enable the JASPIC (Java Authentication SPI for Containers) integration that the Java EE 8 Security API depends on.

> [accordion] Application server compatibility
>
> This quickstart uses the `javax` namespace (Java EE 8). If you are using a server that has migrated to the `jakarta` namespace (Jakarta EE 9+), such as WildFly 27+ or Payara 6+, the code will not compile or run.
>
> Use a Java EE 8 compatible server:
>
> * WildFly 14 through 26
> * Payara 5
> * GlassFish 5
> * Open Liberty with Java EE 8 features

***

## Sample Application

A sample Java EE application integrated with Auth0 is available on GitHub:

> [card] [Java EE Sample Application](https://github.com/auth0-samples/auth0-java-ee-sample/tree/master/01-Login)
>
> Includes login, logout, user profile, and other examples.

Clone and run:

```bash theme={null}
git clone https://github.com/auth0-samples/auth0-java-ee-sample.git
cd auth0-java-ee-sample/01-Login
```

Update the Auth0 configuration values in `src/main/webapp/WEB-INF/web.xml`, then run:

```bash theme={null}
./mvnw clean wildfly:run
```

Point your browser to [http://localhost:8080](http://localhost:8080) and click **Login** to test.

***
