Java

Sample Project

Download a sample project specific to this tutorial configured with your Auth0 API Keys.

System Requirements
  • Java 7 or above
  • Gradle 3.3 or above
Show requirements

This integration guide will walk you through setting up and managing authentication and authorization in your Java apps using Auth0.

Get Your Application Keys

When you signed up for Auth0, you were invited to create a new client.

There are some details about this client that your application needs to know about to properly communicate with Auth0, including your Client ID and Domain. You can retrieve these values from the settings area for your client in the Auth0 dashboard.

Please note that if you download the samples available for this tutorial, these keys will be pre-populated for you. If you have created more than one client in your account, the sample will come with the values for your Default App.

App Dashboard

Configure Callback URLs

A Callback URL is a URL that Auth0 invokes after the authentication process. Auth0 routes your application back to this URL and attaches some details to it including a token. Callback URLs can be manipulated on the fly which could be harmful. For security reasons, you will need to add your application's callback URL in the Allowed Callback URLs box in your app's Client Settings. This will allow Auth0 to recognize the URLs as valid. The same principle applies to Logout URLs. They must be whitelisted in the Auth0 Dashboard.

If you are following this guide directly, set the following for your Callback and Logout URLs:

  • Allowed Callback URLs: http://localhost:8080/callback
  • Allowed Logout URLs: http://localhost:8080/logout

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. You can always check the latest version in the library's GitHub.

If you are using Gradle, add them to your 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:

<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:

<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_CLIENT_ID</param-value>
</context-param>

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

The library we're using has this default behavior:

  • Request the scope openid, needed to call the /userinfo endpoint later to verify the User's identity.
  • Request the code Response Type and later perform a Code Exchange to obtain the tokens.
  • Use the HS256 Algorithm along with the Client Secret to verify the tokens.

But it also allows us to customize it's behavior:

  • To use the RS256 Algorithm along with the Public Key obtained dynamically from the Auth0 hosted JWKs file, pass a JwkProvider instance to the AuthenticationController builder.
  • To use a different Response Type, set the desired value in the AuthenticationController builder. Any combination of code token id_token is allowed.
  • To request a different scope, set the desired value in the AuthorizeUrl received after calling AuthenticationController#buildAuthorizeUrl().
  • To specify the audience, set the desired value in the AuthorizeUrl received after calling AuthenticationController#buildAuthorizeUrl().

Check populated attributes

If you download the seed using our Download Sample button then the domain, clientId and clientSecret attributes will be populated for you, unless you are not logged in or you do not have at least one registered client. In any case, you should verify that the values are correct if you have multiple clients in your account and you might want to use another than the one we set the information for.

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 to 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 login. 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.

Authenticate the User

Let's begin by creating the AuthenticationController instance. From any Servlet class we can obtain the ServletConfig instance and read the properties defined in the web.xml file. Let's read our client properties and create a new instance of this controller:

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

AuthenticationController controller = AuthenticationController.newBuilder(domain, clientId, clientSecret)
                .build();

To authenticate the users we will redirect them to the Auth0 Login Page which uses the best version available of Lock. This page is what we call the "Authorize URL". By using this library we can generate it with a simple method call. It will require a HttpServletRequest to store the call context in the session and the URI to redirect the authentication result to. This URI is normally the address where our app is running plus the path where the result will be parsed, which happens to be also the "Callback URL" whitelisted before. After we create the Authorize URL, we redirect the request there so the user can enter their credentials. The following code snippet is located on the LoginServlet class of our sample.

@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse res) throws ServletException, IOException {
    String redirectUri = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + "/callback";

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

After the user logs in the result will be received in our CallbackServlet, either via a GET or a POST Http method. The request holds the call context that we've previously set by generating the Authorize URL with the controller. When we pass it to the controller, we get back either a valid Tokens instance or an Exception indicating what went wrong. In the case of a successful call, we need to save the credentials somewhere we can access them later. We will use again the HttpSession of the request. A helper class called SessionUtils is included in the library to set and read values from a request's session.

public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
    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 it's 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:

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);
}

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:8080/. Try to access the protected resource http://localhost:8080/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 FREECreate free Account