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 integrate with my app15 minutes
I want to explore a sample app2 minutes
Get a sample configured with your account settings or check it out on Github.
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:
- Client ID
- Client Secret
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.
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.
Integrate Auth0 in your Application
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
If you are using Maven, add them to your
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:
The library we're using has this default behavior:
- Request the scope
openid, needed to call the
/userinfoendpoint later to verify the User's identity.
- Request the
codeResponse Type and later perform a Code Exchange to obtain the tokens.
- Use the
HS256Algorithm along with the Client Secret to verify the tokens.
But it also allows us to customize its behavior:
- To use the
RS256Algorithm along with the Public Key obtained dynamically from the Auth0 hosted JWKs file, pass a
JwkProviderinstance to the
- To use a different Response Type, set the desired value in the
AuthenticationControllerbuilder. Any combination of
code token id_tokenis allowed.
- To request a different
scope, set the desired value in the
AuthorizeUrlreceived after calling
- To specify the
audience, set the desired value in the
AuthorizeUrlreceived after calling
Check populated attributes
If you download the seed using our Download Sample button then the
clientSecret attributes will be populated for you, unless you are not logged in or you do not have at least one registered application. In any case, you should verify that the values are correct if you have multiple applications in your account and you might want to use another than the one we set the information for.
The Login project sample has the following structure:
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
The project contains also four servlets:
LoginServlet.java: Invoked when the user attempts to login. The servlet uses the
domainparameters 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
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
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.
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 application properties and create a new instance of this controller:
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. Finally, we will request the "User Info" audience in order to obtain an Open ID Connect compliant response. 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.
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.
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:
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.
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:
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.
After a successful authentication you'll be able to see the home page contents.
Log out by clicking the Logout button at the top right of the home page.