Skip to main content

AI Prompt

Using AI to integrate Auth0? Add this prompt to Cursor, Windsurf, Copilot, Claude Code or your favourite AI-powered IDE to speed up development.
You are integrating Auth0 into a Java EE 8 web application using the `auth0-java-mvc-common` SDK (`mvc-auth-commons`) and the Java EE 8 Security API (`HttpAuthenticationMechanism`, `IdentityStore`, CDI). The application uses Maven for builds and runs on a Java EE 8 compatible application server such as WildFly. Follow these instructions to add login, logout, and user profile functionality.
Prerequisites:

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:
mvn archetype:generate \
  -DgroupId=com.auth0.example \
  -DartifactId=java-ee-auth0-app \
  -DarchetypeArtifactId=maven-archetype-webapp \
  -DinteractiveMode=false
Navigate into the project directory:
cd java-ee-auth0-app
Create the Java source directories:
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:
pom.xml
<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

  1. Go to the Auth0 Dashboard 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. Click 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. Click Save Changes.
Make sure to set up connections 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.
Do not include https:// in your auth0.domain value. Use only the domain, e.g., 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:
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. 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 where your user information and JWT claims are displayed.
The sample uses JSP and is tested with the WildFly application server. You may need to adjust some steps if you are using a different Java EE 8 compatible container.
CheckpointYou should now have a fully functional Auth0-protected Java EE application running on http://localhost:8080. Users can log in, view their profile, and log out.

Advanced Usage

The Auth0JwtPrincipal is available via request.getUserPrincipal() in any servlet. The ProfileServlet demonstrates how to access the decoded ID token claims:
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)
Add custom parameters to the authorization URL when building it in your LoginServlet:
src/main/java/com/auth0/example/web/LoginServlet.java
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 supported by Auth0.
To access the raw tokens for API calls, modify the Auth0AuthenticationMechanism to store tokens in the session:
src/main/java/com/auth0/example/security/Auth0AuthenticationMechanism.java
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:
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);
Configure the AuthenticationController with an organization ID or name to restrict login to a specific Auth0 Organization:
src/main/java/com/auth0/example/security/Auth0AuthenticationProvider.java
@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


Common Issues

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:
// Correct — uses cookies for state
authenticationController.buildAuthorizeUrl(request, response, callbackUrl)
authenticationController.handle(httpServletRequest, httpServletResponse)
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
src/main/webapp/WEB-INF/jboss-web.xml
<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.
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:

Java EE Sample Application

Includes login, logout, user profile and other examples.
Clone and run:
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:
./mvnw clean wildfly:run
Point your browser to http://localhost:8080 and click Login to test.