By Jim Anderson
This tutorial demonstrates how to add user login to a Java Servlet application.We recommend that you log in to follow this quickstart with examples configured for your account.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.
- Domain
- Client ID
- Client Secret
If you download the sample from the top of this page, these details are filled out for you.
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 added to 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 add to 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 thereturnTo query parameter. The logout URL for your app must be added to 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 add to 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.
build.gradle:
pom.xml:
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 filesrc/main/webapp/WEB-INF/web.xml, but you could store them anywhere else. The required information is:
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, thedomain, 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: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 theclient_idanddomainparameters 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 thehome.jspresource.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 theLoginServlet.AuthenticationControllerProvider: Responsible to create and manage a single instance of theAuthenticationController
Create the AuthenticationController
To enable users to authenticate, create an instance of theAuthenticationController provided by the auth0-java-mvc-commons SDK using the domain, clientId, and clientSecret. The sample 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.
The
AuthenticationController does not store any context, and is inteded to be reused. Unneccessary creation may result in additonal resources being created which could impact performance.Trigger Authentication
To enable users to login, your application will redirect them to the Universal Login page. Using theAuthenticationController instance, you can generate the redirect URL by calling the buildAuthorizeUrl(HttpServletRequest request, HttpServletResponse response, String redirectUrl) method. The redirect URL must be the URL that was added to the Allowed Callback URLs of your Auth0 Application.
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.
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), theAuth0Filter 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:
Handle Logout
To properly handle logout, we need to clear the session and log the user out of Auth0. This is handled in theLogoutServlet 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.
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: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.

