> ## Documentation Index
> Fetch the complete documentation index at: https://docs-staging-docs-event-stream-action-templates.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

> This quickstart demonstrates how to add Auth0 authentication to a Java servlet application. You'll build a secure web application with login, logout, and user profile features using the Auth0 Java MVC Commons SDK.

# Add Login to Your Java Servlet Application

export const HowToSchema = () => <script type="application/ld+json">
    {'{"@context":"https://schema.org","@type":"HowTo"}'}
  </script>;

export const AuthCodeGroup = ({children, dropdown}) => {
  const [processedChildren, setProcessedChildren] = useState(children);
  useEffect(() => {
    let unsubscribe = null;
    function init() {
      unsubscribe = window.autorun(() => {
        const processChildren = node => {
          if (typeof node === "string") {
            let processedNode = node;
            for (const [key, value] of window.rootStore.variableStore.values.entries()) {
              const escapedKey = key.replaceAll(/[.*+?^${}()|[\]\\]/g, (String.raw)`\$&`);
              processedNode = processedNode.replaceAll(new RegExp(escapedKey, "g"), value);
            }
            return processedNode;
          } else if (Array.isArray(node)) {
            return node.map(processChildren);
          } else if (node && node.props && node.props.children) {
            return {
              ...node,
              props: {
                ...node.props,
                children: processChildren(node.props.children)
              }
            };
          }
          return node;
        };
        setProcessedChildren(processChildren(children));
      });
    }
    if (window.rootStore) {
      init();
    } else {
      window.addEventListener("adu:storeReady", init);
    }
    return () => {
      window.removeEventListener("adu:storeReady", init);
      unsubscribe?.();
    };
  }, [children]);
  return <CodeGroup dropdown={dropdown}>{processedChildren}</CodeGroup>;
};

<HowToSchema />

<Note>
  **Prerequisites:** Before you begin, ensure you have the following installed:

  * **Java Development Kit (JDK)**: Version 8 or higher
  * **Build Tool**: [Maven](https://maven.apache.org/download.cgi) 3.6+ or [Gradle](https://gradle.org/install/) 6.0+
  * **Application Server**: [Apache Tomcat](https://tomcat.apache.org/download-90.cgi) 9.0+ or any servlet container
  * **Auth0 Account**: [Sign up for free](https://auth0.com/signup) if you don't have one
</Note>

<Accordion title="Use AI to integrate Auth0" icon="microchip-ai" iconType="solid" defaultOpen>
  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-quickstart --skill auth0-java-mvc-common
  ```

  **Then ask your AI assistant:**

  ```text theme={null}
  Add Auth0 authentication to my Java servlet app
  ```

  Your AI assistant will automatically create your Auth0 application, fetch credentials, add the Auth0 Java MVC Commons SDK dependency, configure your web.xml, and implement login/logout flows with servlet filters. [Full agent skills documentation →](/docs/quickstart/agent-skills)
</Accordion>

## Get Started

This quickstart demonstrates how to add Auth0 authentication to a Java servlet application. You'll build a secure web application with login, logout, and user profile features using the Auth0 Java MVC Commons SDK.

<Steps>
  <Step title="Create a New Java Web Project" stepNumber={1}>
    Create a new Java web application project for this quickstart.

    <Tabs>
      <Tab title="Maven">
        ```bash theme={null}
        mvn archetype:generate \
          -DgroupId=com.auth0.example \
          -DartifactId=auth0-servlet-app \
          -DarchetypeArtifactId=maven-archetype-webapp \
          -DinteractiveMode=false
        ```

        Navigate to your project directory:

        ```bash theme={null}
        cd auth0-servlet-app
        ```
      </Tab>

      <Tab title="Gradle">
        Create a new directory and initialize a Gradle project:

        ```bash theme={null}
        mkdir auth0-servlet-app && cd auth0-servlet-app
        gradle init --type java-application
        ```
      </Tab>
    </Tabs>
  </Step>

  <Step title="Install the Auth0 Java MVC Commons SDK" stepNumber={2}>
    Add the Auth0 dependency to your project build file.

    <Tabs>
      <Tab title="Maven">
        Add the following dependency to your `pom.xml`:

        ```xml theme={null}
        <dependencies>
            <dependency>
                <groupId>com.auth0</groupId>
                <artifactId>mvc-auth-commons</artifactId>
                <version>1.11.1</version>
            </dependency>
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>javax.servlet-api</artifactId>
                <version>3.1.0</version>
                <scope>provided</scope>
            </dependency>
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>jstl</artifactId>
                <version>1.2</version>
            </dependency>
        </dependencies>
        ```
      </Tab>

      <Tab title="Gradle">
        Add the following dependencies to your `build.gradle`:

        ```gradle theme={null}
        plugins {
            id 'java'
            id 'war'
        }

        dependencies {
            implementation 'com.auth0:mvc-auth-commons:1.11.1'
            implementation 'javax.servlet:javax.servlet-api:3.1.0'
            implementation 'javax.servlet:jstl:1.2'
        }
        ```
      </Tab>
    </Tabs>
  </Step>

  <Step title="Setup Your Auth0 Application" stepNumber={3}>
    Next, you need to create a new application on your Auth0 tenant and add the configuration to your project.

    1. Head to the [Auth0 Dashboard](https://manage.auth0.com/dashboard)
    2. Click on **Applications** > **Applications** > **Create Application**
    3. In the popup, enter a name for your app, select **Regular Web Application** as the app type and click **Create**
    4. Switch to the **Settings** tab on the Application Details page
    5. Note down the **Domain**, **Client ID**, and **Client Secret** values from the dashboard
    6. Finally, on the **Settings** tab of your Application Details page, configure the following URLs:

    **Allowed Callback URLs:**

    ```
    http://localhost:8080/callback
    ```

    **Allowed Logout URLs:**

    ```
    http://localhost:8080/login
    ```

    **Allowed Web Origins:**

    ```
    http://localhost:8080
    ```

    <Note>
      * **Allowed Callback URLs** are a critical security measure to ensure users are safely returned to your application after authentication. Without a matching URL, the login process will fail, and users will be blocked by an Auth0 error page instead of accessing your app.
      * **Allowed Logout URLs** are essential for providing a seamless user experience upon signing out. Without a matching URL, users will not be redirected back to your application after logout and will instead be left on a generic Auth0 page.
      * **Allowed Web Origins** is critical for silent authentication. Without it, users will be logged out when they refresh the page or return to your app later.
    </Note>
  </Step>

  <Step title="Configure the Auth0 SDK" stepNumber={4}>
    Configure your servlet application to use the Auth0 SDK by setting up the web.xml configuration with the Auth0 credentials generated above.

    Create or update `src/main/webapp/WEB-INF/web.xml` and replace the placeholder values with your actual Auth0 application settings:

    ```xml expandable theme={null}
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
             http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
             version="3.1">

        <display-name>Auth0 Servlet Example</display-name>

        <!-- Auth0 Configuration -->
        <context-param>
            <param-name>com.auth0.domain</param-name>
            <param-value>YOUR_AUTH0_DOMAIN</param-value>
        </context-param>
        <context-param>
            <param-name>com.auth0.clientId</param-name>
            <param-value>YOUR_AUTH0_CLIENT_ID</param-value>
        </context-param>
        <context-param>
            <param-name>com.auth0.clientSecret</param-name>
            <param-value>YOUR_AUTH0_CLIENT_SECRET</param-value>
        </context-param>
    </web-app>
    ```

    **Important**: Replace `YOUR_AUTH0_DOMAIN`, `YOUR_AUTH0_CLIENT_ID`, and `YOUR_AUTH0_CLIENT_SECRET` with the actual values from your Auth0 application settings.
  </Step>

  <Step title="Create Authentication Components and Filter" stepNumber={5}>
    Create the necessary Java classes to handle authentication flows and protect secured pages.

    <AuthCodeGroup>
      ```java src/main/java/com/auth0/example/AuthenticationControllerProvider.java expandable lines theme={null}
      package com.auth0.example;

      import com.auth0.AuthenticationController;
      import com.auth0.jwk.JwkProvider;
      import com.auth0.jwk.JwkProviderBuilder;

      import javax.servlet.ServletConfig;
      import java.io.UnsupportedEncodingException;

      /**
       * Manages a singleton instance of AuthenticationController for the application.
       */
      public class AuthenticationControllerProvider {

          private AuthenticationControllerProvider() {}

          private static AuthenticationController INSTANCE;

          public static synchronized AuthenticationController getInstance(ServletConfig config)
                  throws UnsupportedEncodingException {
              if (INSTANCE == null) {
                  String domain = config.getServletContext().getInitParameter("com.auth0.domain");
                  String clientId = config.getServletContext().getInitParameter("com.auth0.clientId");
                  String clientSecret = config.getServletContext().getInitParameter("com.auth0.clientSecret");

                  if (domain == null || clientId == null || clientSecret == null) {
                      throw new IllegalArgumentException(
                          "Missing domain, clientId, or clientSecret. Check your web.xml configuration.");
                  }

                  // JwkProvider required for RS256 tokens
                  JwkProvider jwkProvider = new JwkProviderBuilder(domain).build();
                  INSTANCE = AuthenticationController.newBuilder(domain, clientId, clientSecret)
                          .withJwkProvider(jwkProvider)
                          .build();
              }
              return INSTANCE;
          }
      }
      ```

      ```java src/main/java/com/auth0/example/LoginServlet.java expandable lines theme={null}
      package com.auth0.example;

      import com.auth0.AuthenticationController;

      import javax.servlet.ServletConfig;
      import javax.servlet.ServletException;
      import javax.servlet.annotation.WebServlet;
      import javax.servlet.http.HttpServlet;
      import javax.servlet.http.HttpServletRequest;
      import javax.servlet.http.HttpServletResponse;
      import java.io.IOException;
      import java.io.UnsupportedEncodingException;

      @WebServlet(urlPatterns = {"/login"})
      public class LoginServlet extends HttpServlet {

          private AuthenticationController authenticationController;

          @Override
          public void init(ServletConfig config) throws ServletException {
              super.init(config);
              try {
                  authenticationController = AuthenticationControllerProvider.getInstance(config);
              } catch (UnsupportedEncodingException e) {
                  throw new ServletException("Couldn't create the AuthenticationController instance. Check the configuration.", e);
              }
          }

          @Override
          protected void doGet(HttpServletRequest req, HttpServletResponse res)
                  throws ServletException, IOException {
              // Build the callback URL
              String redirectUri = req.getScheme() + "://" + req.getServerName();
              if ((req.getScheme().equals("http") && req.getServerPort() != 80) ||
                  (req.getScheme().equals("https") && req.getServerPort() != 443)) {
                  redirectUri += ":" + req.getServerPort();
              }
              redirectUri += "/callback";

              // Generate Auth0 authorization URL
              String authorizeUrl = authenticationController.buildAuthorizeUrl(req, res, redirectUri)
                      .build();
              res.sendRedirect(authorizeUrl);
          }
      }
      ```

      ```java src/main/java/com/auth0/example/CallbackServlet.java expandable lines theme={null}
      package com.auth0.example;

      import com.auth0.AuthenticationController;
      import com.auth0.IdentityVerificationException;
      import com.auth0.SessionUtils;
      import com.auth0.Tokens;

      import javax.servlet.ServletConfig;
      import javax.servlet.ServletException;
      import javax.servlet.annotation.WebServlet;
      import javax.servlet.http.HttpServlet;
      import javax.servlet.http.HttpServletRequest;
      import javax.servlet.http.HttpServletResponse;
      import java.io.IOException;
      import java.io.UnsupportedEncodingException;

      @WebServlet(urlPatterns = {"/callback"})
      public class CallbackServlet extends HttpServlet {

          private AuthenticationController authenticationController;

          @Override
          public void init(ServletConfig config) throws ServletException {
              super.init(config);
              try {
                  authenticationController = AuthenticationControllerProvider.getInstance(config);
              } catch (UnsupportedEncodingException e) {
                  throw new ServletException("Couldn't create the AuthenticationController instance. Check the configuration.", e);
              }
          }

          @Override
          public void doGet(HttpServletRequest req, HttpServletResponse res)
                  throws IOException, ServletException {
              handleCallback(req, res);
          }

          @Override
          public void doPost(HttpServletRequest req, HttpServletResponse res)
                  throws IOException, ServletException {
              handleCallback(req, res);
          }

          private void handleCallback(HttpServletRequest req, HttpServletResponse res)
                  throws IOException {
              try {
                  // Process the authentication callback
                  Tokens tokens = authenticationController.handle(req, res);

                  // Store tokens in session
                  SessionUtils.set(req, "accessToken", tokens.getAccessToken());
                  SessionUtils.set(req, "idToken", tokens.getIdToken());

                  // Redirect to secure area
                  res.sendRedirect("/profile");
              } catch (IdentityVerificationException e) {
                  // Authentication failed
                  e.printStackTrace();
                  res.sendRedirect("/login?error=auth_failed");
              }
          }
      }
      ```

      ```java src/main/java/com/auth0/example/ProfileServlet.java expandable lines theme={null}
      package com.auth0.example;

      import com.auth0.SessionUtils;

      import javax.servlet.ServletException;
      import javax.servlet.annotation.WebServlet;
      import javax.servlet.http.HttpServlet;
      import javax.servlet.http.HttpServletRequest;
      import javax.servlet.http.HttpServletResponse;
      import java.io.IOException;

      @WebServlet(urlPatterns = {"/profile"})
      public class ProfileServlet extends HttpServlet {

          @Override
          protected void doGet(HttpServletRequest req, HttpServletResponse res)
                  throws ServletException, IOException {

              String accessToken = (String) SessionUtils.get(req, "accessToken");
              String idToken = (String) SessionUtils.get(req, "idToken");

              if (accessToken == null && idToken == null) {
                  res.sendRedirect("/login");
                  return;
              }

              // Forward to profile JSP
              req.setAttribute("accessToken", accessToken);
              req.setAttribute("idToken", idToken);
              req.getRequestDispatcher("/WEB-INF/jsp/profile.jsp").forward(req, res);
          }
      }
      ```

      ```java src/main/java/com/auth0/example/LogoutServlet.java expandable lines theme={null}
      package com.auth0.example;

      import com.auth0.SessionUtils;

      import javax.servlet.ServletException;
      import javax.servlet.annotation.WebServlet;
      import javax.servlet.http.HttpServlet;
      import javax.servlet.http.HttpServletRequest;
      import javax.servlet.http.HttpServletResponse;
      import java.io.IOException;

      @WebServlet(urlPatterns = {"/logout"})
      public class LogoutServlet extends HttpServlet {

          @Override
          protected void doGet(HttpServletRequest req, HttpServletResponse res)
                  throws ServletException, IOException {

              // Clear session
              SessionUtils.set(req, "accessToken", null);
              SessionUtils.set(req, "idToken", null);
              req.getSession().invalidate();

              // Redirect to login

              res.sendRedirect("/login");
          }
      }
      ```

      ```java src/main/java/com/auth0/example/AuthenticationFilter.java expandable lines theme={null}
      package com.auth0.example;

      import com.auth0.SessionUtils;

      import javax.servlet.*;
      import javax.servlet.annotation.WebFilter;
      import javax.servlet.http.HttpServletRequest;
      import javax.servlet.http.HttpServletResponse;
      import java.io.IOException;

      @WebFilter(urlPatterns = {"/profile"})
      public class AuthenticationFilter implements Filter {

          @Override
          public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
                  throws IOException, ServletException {

              HttpServletRequest req = (HttpServletRequest) request;
              HttpServletResponse res = (HttpServletResponse) response;

              String accessToken = (String) SessionUtils.get(req, "accessToken");
              String idToken = (String) SessionUtils.get(req, "idToken");

              if (accessToken == null && idToken == null) {
                  res.sendRedirect("/login");
                  return;
              }

              chain.doFilter(request, response);
          }

          @Override
          public void init(FilterConfig filterConfig) throws ServletException {
              // Initialize filter
          }

          @Override
          public void destroy() {
              // Clean up resources
          }
      }
      ```
    </AuthCodeGroup>
  </Step>

  <Step title="Create User Interface Pages" stepNumber={6}>
    Create the JSP pages and HTML files for your application.

    <AuthCodeGroup>
      ```jsp src/main/webapp/WEB-INF/jsp/profile.jsp expandable lines theme={null}
      <%@ page contentType="text/html;charset=UTF-8" language="java" %>
      <!DOCTYPE html>
      <html>
      <head>
          <title>Profile - Auth0 Example</title>
          <style>
              body { font-family: Arial, sans-serif; margin: 40px; }
              .profile-container { max-width: 600px; margin: 0 auto; }
              .token-section { margin: 20px 0; padding: 15px; background-color: #f5f5f5; border-radius: 5px; }
              .logout-btn {
                  background-color: #dc3545;
                  color: white;
                  padding: 10px 20px;
                  text-decoration: none;
                  border-radius: 5px;
                  display: inline-block;
                  margin-top: 20px;
              }
              .logout-btn:hover { background-color: #c82333; }
              code { background-color: #e9ecef; padding: 2px 4px; border-radius: 3px; }
          </style>
      </head>
      <body>
          <div class="profile-container">
              <h1>Welcome to Your Profile!</h1>
              <p>You have successfully authenticated with Auth0.</p>

              <div class="token-section">
                  <h3>Access Token</h3>
                  <p><code>${accessToken}</code></p>
              </div>

              <div class="token-section">
                  <h3>ID Token</h3>
                  <p><code>${idToken}</code></p>
              </div>

              <a href="/logout" class="logout-btn">Logout</a>
          </div>
      </body>
      </html>
      ```

      ```html src/main/webapp/index.html expandable lines theme={null}
      <!DOCTYPE html>
      <html>
        <head>
          <title>Auth0 Java Servlet Example</title>
          <style>
            body {
              font-family: Arial, sans-serif;
              margin: 0;
              padding: 40px;
              background-color: #f8f9fa;
            }
            .container {
              max-width: 600px;
              margin: 0 auto;
              text-align: center;
              background-color: white;
              padding: 40px;
              border-radius: 8px;
              box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            }
            .login-btn {
              background-color: #007bff;
              color: white;
              padding: 12px 30px;
              text-decoration: none;
              border-radius: 5px;
              display: inline-block;
              font-size: 16px;
              margin-top: 20px;
              transition: background-color 0.3s;
            }
            .login-btn:hover {
              background-color: #0056b3;
            }
            h1 {
              color: #333;
            }
            p {
              color: #666;
              line-height: 1.6;
            }
          </style>
        </head>
        <body>
          <div class="container">
            <h1>Auth0 Java Servlet Example</h1>
            <p>
              This example demonstrates how to add authentication to a Java servlet
              application using the Auth0 Java MVC Commons SDK.
            </p>
            <p>
              Click the button below to authenticate with Auth0 and access your
              profile.
            </p>

            <a href="/login" class="login-btn">Login with Auth0</a>
          </div>
        </body>
      </html>
      ```
    </AuthCodeGroup>
  </Step>

  <Step title="Build and Run Your Application" stepNumber={7}>
    Now you're ready to build and run your application.

    <Tabs>
      <Tab title="Maven">
        Build the application:

        ```bash theme={null}
        mvn clean compile war:war
        ```

        Deploy to Tomcat:

        ```bash theme={null}
        # Copy the WAR file to Tomcat webapps directory
        cp target/auth0-servlet-app.war $CATALINA_HOME/webapps/ROOT.war
        ```
      </Tab>

      <Tab title="Gradle">
        Build the application:

        ```bash theme={null}
        gradle clean build
        ```

        Deploy to Tomcat:

        ```bash theme={null}
        # Copy the WAR file to Tomcat webapps directory
        cp build/libs/auth0-servlet-app.war $CATALINA_HOME/webapps/
        ```
      </Tab>
    </Tabs>

    Start Tomcat (or your preferred servlet container):

    ```bash theme={null}
    $CATALINA_HOME/bin/startup.sh  # On Unix/Linux/Mac
    # or
    $CATALINA_HOME/bin/startup.bat  # On Windows
    ```
  </Step>
</Steps>

<Check>
  **Checkpoint**

  You should now have a fully functional Auth0-integrated servlet application running at [http://localhost:8080/](http://localhost:8080/)

  **Test your implementation:**

  1. Navigate to your application URL
  2. Click "Login with Auth0"
  3. Complete the Auth0 login process
  4. You should be redirected to your profile page showing the tokens
  5. Click "Logout" to clear the session
</Check>

***

## Advanced Usage

<Accordion title="Enhance Your Application">
  Now that you have basic authentication working, consider these enhancements:

  * **User Profile Information**: Decode the ID token to display user information
  * **API Calls**: Use the access token to call Auth0's Management API or your own APIs
  * **Role-Based Access**: Implement authorization using Auth0 roles and permissions
  * **Single Sign-On**: Configure SSO across multiple applications
</Accordion>

<Accordion title="Additional Resources">
  * [Auth0 Java MVC Commons
    Documentation](https://github.com/auth0/auth0-java-mvc-common) - [Auth0
    Dashboard](https://manage.auth0.com/) - Manage your Auth0 applications -
    [Auth0 Servlet Sample
    Repository](https://github.com/auth0-samples/auth0-servlet-sample) - Complete
    examples - [Auth0 Java SDK
    Documentation](https://auth0.com/docs/libraries/auth0-java) - Advanced SDK
    usage
</Accordion>

<Accordion title="Troubleshooting">
  **Common Issues**

  **Authentication fails with "Invalid callback URL"**

  * Verify that the callback URL in your Auth0 application settings matches exactly: `http://localhost:8080/callback`

  **"Missing domain, clientId, or clientSecret" error**

  * Check that your `web.xml` configuration has the correct Auth0 application values
  * Ensure the parameter names match exactly: `com.auth0.domain`, `com.auth0.clientId`, `com.auth0.clientSecret`

  **Application doesn't start**

  * Verify all required dependencies are in your classpath
  * Check that your servlet container supports Servlet API 3.0+
  * Review server logs for specific error messages

  **Session not persisting**

  * Ensure your servlet container is configured for session management
  * Check that cookies are enabled in your browser
  * Verify HTTPS is used in production environments

  For additional support, visit the [Auth0 Community](https://community.auth0.com/).
</Accordion>
