Java
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.
I want to integrate with my app
15 minutesI want to explore a sample app
2 minutesGet a sample configured with your account settings or check it out on Github.
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
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.
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 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.
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.+'
Was this helpful?
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.0, 2.0)</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
Was this helpful?
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>{yourDomain}</param-value>
</context-param>
<context-param>
<param-name>com.auth0.clientId</param-name>
<param-value>{yourClientId}</param-value>
</context-param>
<context-param>
<param-name>com.auth0.clientSecret</param-name>
<param-value>YOUR_CLIENT_SECRET</param-value>
</context-param>
Was this helpful?
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
Was this helpful?
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 theclient_id
anddomain
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 thehome.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 theLoginServlet
.AuthenticationControllerProvider
: Responsible to create and manage a single instance of theAuthenticationController
Create the AuthenticationController
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 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
.
class AuthenticationControllerProvider {
private AuthenticationControllerProvider() {}
private static AuthenticationController INSTANCE;
// if multiple threads may call this, synchronize this method and consider double locking
static 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. Did you update src/main/webapp/WEB-INF/web.xml?");
}
// JwkProvider required for RS256 tokens. If using HS256, do not use.
JwkProvider jwkProvider = new JwkProviderBuilder(domain).build();
INSTANCE = AuthenticationController.newBuilder(domain, clientId, clientSecret)
.withJwkProvider(jwkProvider)
.build();
}
return INSTANCE;
}
Was this helpful?
Trigger Authentication
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, HttpServletResponse response, 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, res, redirectUri)
.build();
res.sendRedirect(authorizeUrl);
}
Was this helpful?
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, res);
SessionUtils.set(req, "accessToken", tokens.getAccessToken());
SessionUtils.set(req, "idToken", tokens.getIdToken());
res.sendRedirect(redirectOnSuccess);
} catch (IdentityVerificationException e) {
e.printStackTrace();
res.sendRedirect(redirectOnFail);
}
}
Was this helpful?
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);
}
Was this helpful?
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);
}
Was this helpful?
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
Was this helpful?
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.