Docs

Java

View on Github

Java

Gravatar for jim.anderson@auth0.com
By Jim Anderson

This tutorial demonstrates how to add user login to a Java Servlet application. We recommend you to Log in to follow this quickstart with examples configured for your account.

I want to explore a sample app

2 minutes

Get a sample configured with your account settings or check it out on Github.

View on Github
System requirements: Java 8 | Gradle 3.3 and up

New to Auth? Learn How Auth0 works, how it integrates with Regular Web Applications and which protocol it uses.

Configure Auth0

Get Your Application Keys

When you signed up for Auth0, a new application was created for you, or you could have created a new one.

You will need some details about that application to communicate with Auth0. You can get these details from the Application Settings section in the Auth0 dashboard.

You need the following information:

  • Domain
  • Client ID
  • Client Secret

If you download the sample from the top of this page these details are filled out for you.

If you have more than one application in your account, the sample comes with the values for your Default App.

App Dashboard

Configure Callback URLs

A callback URL is a URL in your application where Auth0 redirects the user after they have authenticated.

The callback URL for your app must be whitelisted in the Allowed Callback URLs field in your Application Settings. If this field is not set, users will be unable to log in to the application and will get an error.

If you are following along with the sample project you downloaded from the top of this page, the callback URL you need to whitelist in the Allowed Callback URLs field is http://localhost:3000/callback.

Configure Logout URLs

A logout URL is a URL in your application that Auth0 can return to after the user has been logged out of the authorization server. This is specified in the returnTo query parameter.

The logout URL for your app must be whitelisted in the Allowed Logout URLs field in your Application Settings. If this field is not set, users will be unable to log out from the application and will get an error.

If you are following along with the sample project you downloaded from the top of this page, the logout URL you need to whitelist in the Allowed Logout URLs field is http://localhost:3000/login.

Integrate Auth0 in your Application

Setup Dependencies

To integrate your Java application with Auth0, add the following dependencies:

  • javax.servlet-api: is the library that allows you to create Java Servlets. You then need to add a Server dependency like Tomcat or Gretty, which one is up to you. Check our sample code for more information.
  • auth0-java-mvc-commons: is the Java library that allows you to use Auth0 with Java for server-side MVC web apps. It generates the Authorize URL that you need to call in order to authenticate and validates the result received on the way back to finally obtain the Auth0 Tokens that identify the user.

If you are using Gradle, add them to your build.gradle:

// build.gradle

compile 'javax.servlet:javax.servlet-api:3.1.0'
compile 'com.auth0:mvc-auth-commons:1.+'

If you are using Maven, add them to your pom.xml:

<!-- pom.xml -->

<dependency>
  <groupId>com.auth0</groupId>
  <artifactId>mvc-auth-commons</artifactId>
  <version>1.+</version>
</dependency>
<dependency>
  <groupId>javax.servlet</groupId>
  <artifactId>javax.servlet-api</artifactId>
  <version>3.1.0</version>
</dependency>

Configure your Java App

Your Java App needs some information in order to authenticate against your Auth0 account. The samples read this information from the deployment descriptor file src/main/webapp/WEB-INF/web.xml, but you could store them anywhere else. The required information is:

<!-- src/main/webapp/WEB-INF/web.xml -->

<context-param>
    <param-name>com.auth0.domain</param-name>
    <param-value>YOUR_DOMAIN</param-value>
</context-param>

<context-param>
    <param-name>com.auth0.clientId</param-name>
    <param-value>YOUR_CLIENT_ID</param-value>
</context-param>

<context-param>
    <param-name>com.auth0.clientSecret</param-name>
    <param-value>YOUR_CLIENT_SECRET</param-value>
</context-param>

This information will be used to configure the auth0-java-mvc-commons library to enable users to login to your application. To learn more about the library, including its various configuration options, see the library's documentation.

Check populated attributes

If you downloaded this sample using the Download Sample button, the domain, clientId and clientSecret attributes will be populated for you. You should verify that the values are correct, especially if you have multiple Auth0 applications in your account.

Project Structure

The Login project sample has the following structure:

- src
-- main
---- java
------ com
-------- auth0
---------- example
------------ Auth0Filter.java
------------ AuthenticationControllerProvider.java
------------ HomeServlet.java
------------ CallbackServlet.java
------------ LoginServlet.java
------------ LogoutServlet.java
---- webapp
------ WEB-INF
-------- jsp
---------- home.jsp
-------- web.xml
- build.gradle

The project contains a single JSP: the home.jsp which will display the tokens associated with the user after a successful login and provide the option to logout.

The project contains a WebFilter: the Auth0Filter.java which will check for existing tokens before giving the user access to our protected /portal/* path. If the tokens don't exist, the request will be redirected to the LoginServlet.

The project contains also four servlets:

  • LoginServlet.java: Invoked when the user attempts to log in. The servlet uses the client_id and domain parameters to create a valid Authorize URL and redirects the user there.
  • CallbackServlet.java: The servlet captures requests to our Callback URL and processes the data to obtain the credentials. After a successful login, the credentials are then saved to the request's HttpSession.
  • HomeServlet.java: The servlet reads the previously saved tokens and shows them on the home.jsp resource.
  • LogoutServlet.java: Invoked when the user clicks the logout link. The servlet invalidates the user session and redirects the user to the login page, handled by the LoginServlet.

Lastly, the project defines a helper class: the AuthenticationControllerProvider.java which will be in charge of creating new instances of AuthenticationController. Because this controller is very simple and doesn't keep any context it can be safely reused. You can also choose to create a new one every time it's needed.

Trigger Authentication

To enable users to authenticate, create an instance of the AuthenticationController provided by the auth0-java-mvc-commons SDK using the domain, clientId, and clientSecret. The sample below shows how to configure the component for use with tokens signed using the RS256 asymmetric signing algorithm, by specifying a JwkProvider to fetch the public key used to verify the token's signature. See the jwks-rsa-java repository to learn about additional configuration options. If you are using HS256, there is no need to configure the JwkProvider.

// src/main/java/com/auth0/example/AuthenticationControllerProvider.java

String domain = getServletConfig().getServletContext().getInitParameter("com.auth0.domain");
String clientId = getServletConfig().getServletContext().getInitParameter("com.auth0.clientId");
String clientSecret = getServletConfig().getServletContext().getInitParameter("com.auth0.clientSecret");

JwkProvider jwkProvider = new JwkProviderBuilder(domain).build();
AuthenticationController controller = AuthenticationController.newBuilder(domain, clientId, clientSecret)
                .withJwkProvider(jwkProvider)
                .build();

To enable users to login, your application will redirect them to the Universal Login page. Using the AuthenticationController instance, you can generate the redirect URL by calling the buildAuthorizeUrl(HttpServletRequest request, String redirectUrl) method. The redirect URL must be the URL that was added to the Allowed Callback URLs of your Auth0 Application.

// src/main/java/com/auth0/example/LoginServlet.java

@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse res) throws ServletException, IOException {
    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";

    String authorizeUrl = authenticationController.buildAuthorizeUrl(req, redirectUri)
            .build();
    res.sendRedirect(authorizeUrl);
}

After the user logs in, the result will be received in our CallbackServlet via either a GET or POST HTTP request. Because we are using the Authorization Code Flow (the default), a GET request will be sent. If you have configured the library for the Implicit Flow, a POST request will be sent instead.

The request holds the call context that the library previously set by generating the Authorize URL with the AuthenticationController. When passed to the controller, you get back either a valid Tokens instance or an Exception indicating what went wrong. In the case of a successful call, you need to save the credentials somewhere to access them later. You can use the HttpSession of the request by using the SessionsUtils class included in the library.

// src/main/java/com/auth0/example/CallbackServlet.java

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

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

private void handle(HttpServletRequest req, HttpServletResponse res) throws IOException {
    try {
        // Parse the request
        Tokens tokens = authenticationController.handle(req);
        SessionUtils.set(req, "accessToken", tokens.getAccessToken());
        SessionUtils.set(req, "idToken", tokens.getIdToken());
        res.sendRedirect(redirectOnSuccess);
    } catch (IdentityVerificationException e) {
        e.printStackTrace();
        res.sendRedirect(redirectOnFail);
    }
}

It is recommended to store the time in which we requested the tokens and the received expiresIn value, so that the next time when we are going to use the token we can check if it has already expired or if it's still valid. For the sake of this sample, we will skip that validation.

Display the Home Page

Now that the user is authenticated (the tokens exists), the Auth0Filter will allow them to access our protected resources. In the HomeServlet we obtain the tokens from the request's session and set them as the userId attribute so they can be used from the JSP code:

// src/main/java/com/auth0/example/HomeServlet.java

protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    final String accessToken = (String) SessionUtils.get(req, "accessToken");
    final String idToken = (String) SessionUtils.get(req, "idToken");
    if (accessToken != null) {
        req.setAttribute("userId", accessToken);
    } else if (idToken != null) {
        req.setAttribute("userId", idToken);
    }
    req.getRequestDispatcher("/WEB-INF/jsp/home.jsp").forward(req, res);
}

Handle Logout

To properly handle logout, we need to clear the session and log the user out of Auth0. This is handled in the LogoutServlet of our sample application.

First, we clear the session by calling request.getSession().invalidate(). We then construct the logout URL, being sure to include the returnTo query parameter, which is where the user will be redirected to after logging out. Finally, we redirect the response to our logout URL.

// src/main/java/com/auth0/example/LogoutServlet.java

@Override
protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
    if (request.getSession() != null) {
        request.getSession().invalidate();
    }

    String returnUrl = String.format("%s://%s", request.getScheme(), request.getServerName());
    if ((request.getScheme().equals("http") && request.getServerPort() != 80) || (request.getScheme().equals("https") && request.getServerPort() != 443)) {
        returnUrl += ":" + request.getServerPort();
    }
    returnUrl += "/login";

    // Build logout URL like:
    // https://{YOUR-DOMAIN}/v2/logout?client_id={YOUR-CLIENT-ID}&returnTo=http://localhost:3000/login
    String logoutUrl = String.format(
            "https://%s/v2/logout?client_id=%s&returnTo=%s",
            domain,
            clientId,
            returnUrl
    );
    response.sendRedirect(logoutUrl);
}

Run the Sample

To run the sample from a terminal, change the directory to the root folder of the project and execute the following line:

./gradlew clean appRun

After a few seconds, the application will be accessible on http://localhost:3000/. Try to access the protected resource http://localhost:3000/portal/home and note how you're redirected by the Auth0Filter to the Auth0 Login Page. The widget displays all the social and database connections that you have defined for this application in the dashboard.

Login using Lock

After a successful authentication, you'll be able to see the home page contents.

Display Token

Log out by clicking the Logout button at the top right of the home page.

Use Auth0 for FREE