micronaut logo
java logo

Authentication in Micronaut

Updated on June 7, 2024
Photo of Deepu K Sasidharan
Deepu K SasidharanDeveloper Advocate

This Micronaut tutorial can help you learn how to build a Micronaut web app that uses OpenID Connect for user authentication. The tutorial examples cover the following concepts:

  • How to build a Micronaut web app with Java.
  • How to secure your Micronaut web app and implement user log in with OpenID Connect.
  • How to add a user logout feature.

Why Use Micronaut to Build Apps?

Micronaut is a modern, JVM-based framework designed for building modular, easily testable microservice and serverless applications. It focuses on faster start-up time, high throughput and minimal memory consumption. It is cloud-native by default and includes a built-in testing framework.

OpenID Connect (OIDC) is an identity layer built on top of the OAuth 2.0 framework. It allows third-party applications to verify the identity of the end-user and to obtain basic user profile information.

In this guide, you'll learn how to use Java and Micronaut to build a simple app that's secured with OIDC. You'll also learn how to view and validate the access token you receive.

Set up a Development Environment

  • Use your favorite text editor or IDE. We recommend using IntelliJ IDEA.
  • Ensure that you have Java 17+ installed in your system. You can easily install it using SDKMAN!.
  • Windows commands in this guide are written for PowerShell.

Create an Auth0 account

If you already have an Auth0 account, you can log in to your tenant and continue to the next step.

Otherwise, sign up for a free Auth0 account.

During the sign-up process, you create something called an Auth0 Tenant, where you configure your use of Auth0.

Once you sign in, Auth0 takes you to the Auth0 Dashboard, where you can configure and manage Auth0 assets, such as applications, APIs, connections, and user profiles.

Set up the Auth0 CLI

If you are not familiar with the Auth0 CLI, you can follow the "Auth0 CLI Basics" lab to learn how to build, manage, and test your Auth0 integrations from the command line.

There are different ways to install the Auth0 CLI, depending on your operating system.

LOADING...

Install the Micronaut CLI

The Micronaut CLI is a command-line tool that helps you create, manage, and build Micronaut applications. You can install it using SDKMAN!.

COMMAND
sdk install micronaut

For more installation options, see the Micronaut documentation.

Create a Micronaut App

To create a new project using the Micronaut CLI, run the following command:

COMMAND
mn create-app demo --features=security-jwt,security-oauth2,views-thymeleaf

This will create a new project with Gradle as the build tool. If you prefer to use Maven, you can add --build=maven to the above command.

If you prefer to use a browser, navigate to https://micronaut.io/launch/ and create a Micronaut project with views-thymeleaf, security-jwt and security-oauth2 features.

If you try to run the app at this point, you will get a runtime error as the OAuth 2.0 details are not configured yet.

Secure Micronaut with OIDC

In a terminal, connect the Auth0 CLI to your Auth0 tenant.

COMMAND
auth0 login
Visit the Access Your Tenant section of the "Auth0 CLI Basics" lab to learn more about the auth0 login command.

Then, run the command below to create an OIDC application:

LOADING...

Copy the domain, client ID, and client secret of your app and paste it into the following input boxes:

When you enter a value in the input fields present on this page, any code snippet that uses such value updates to reflect it. Using the input fields makes copying and pasting code as you follow along easy.

For security, these configuration values are stored in memory and only used locally. They are gone as soon as you refresh the page!

Now, update the application-dev.properties file in the resources directory to configure the OIDC client. Replace the content in the file with the configuration below:

src/main/resources/application-dev.properties
micronaut.security.oauth2.clients.auth0.openid.issuer=https://AUTH0-DOMAIN/
micronaut.security.oauth2.clients.auth0.client-id=AUTH0-CLIENT-ID
micronaut.security.oauth2.clients.auth0.client-secret=${OAUTH_CLIENT_SECRET}
We recommend you DO NOT include the client secret in this file for security reasons. You can use environment variables instead.

Next, update the micronaut.security.authentication property in the application.properties file to idtoken:

src/main/resources/application.properties
micronaut.security.authentication=idtoken

Create a HomeController.java class next to Application.java:

LOADING...

Populate it with the following code:

src/main/java/demo/HomeController.java
package demo;
import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Get;
import io.micronaut.security.annotation.Secured;
import io.micronaut.security.rules.SecurityRule;
import io.micronaut.views.View;
import java.util.HashMap;
import java.util.Map;
@Controller
public class HomeController {
@Secured(SecurityRule.IS_ANONYMOUS)
@View("home")
@Get
public Map<String, Object> index() {
return new HashMap<>();
}
}

The @Secured annotation is used to configure secure access. You can also use Jakarta Annotations. The SecurityRule.IS_ANONYMOUS expression will allow access without authentication.

Add a home view using Thymeleaf by creating a home.html file in the src/main/resources/views directory:

LOADING...

And populate with the following content:

src/main/resources/views/home.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Micronaut + Auth0</title>
</head>
<body>
<h1>Micronaut + Auth0 Example</h1>
<h2 th:if="${security}">
Hello,
<span th:text="${security.attributes.get('name')}"></span>
</h2>
<h2 th:unless="${security}">Hello, Anonymous</h2>
<nav>
<ul>
<li th:unless="${security}">
<a href="/oauth/login/auth0">Login</a>\
</li>
</ul>
</nav>
</body>
</html>

Note that we returned an empty model in the controller. But, we are accessing security attributes in the Thymeleaf template. The SecurityViewModelProcessor injects a security map with the authenticated user into the model.

Navigate to the demo directory, then, run the app with the following command:

GRADLE
MAVEN
OAUTH_CLIENT_SECRET=AUTH0-CLIENT-SECRET ./gradlew run

Open a browser and navigate to http://localhost:8080. Log in with your Auth0 credentials (or sign up as a new user), and you should see your name displayed. If you don't have a user in your tenant yet, you can sign up with Google or create a new user with the Auth0 CLI:

COMMAND
auth0 users create
For additional security against replay attacks, you might want to implement a CSRF protection filter.

Implement a Profile Page with Logout

Auth0 provides the OIDC end_session_endpoint to log out of your tenant. You can use this endpoint along with the default Logout Controller from Micronaut to log out of your application.

First, add the properties below to application-dev.properties:

src/main/resources/application-dev.properties
micronaut.security.oauth2.clients.auth0.openid.end-session.url=/oauth/logout
micronaut.security.endpoints.logout.get-allowed=true

Replace the code in home.html to add profile information and a logout button:

src/main/resources/views/home.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Micronaut + Auth0</title>
<link
rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css"
>
</head>
<body class="container p-5">
<h2>Micronaut + Auth0 Example</h2>
<div th:unless="${security}">
<p>Hello!</p>
<p>If you're viewing this page then you have successfully configured and
started this application.</p>
<p>This example shows you how to use the Micronaut OIDC Authorization
Code Flow in your application.</p>
<p>When you click the Login link below, you will be redirected to login.
After you authenticate, you will be returned to this application.</p>
</div>
<div th:if="${security}">
<p>Welcome home,
<span th:text="${security.attributes.get('name')}"></span>!
</p>
<p>You have successfully authenticated with Auth0,
and have been redirected back to this application.</p>
<p>Here are your user attributes:</p>
<table class="table table-striped">
<thead>
<tr>
<th>Claim</th>
<th>Value</th>
</tr>
</thead>
<tbody>
<tr th:each="item : ${security.attributes}">
<td th:text="${item.key}">Key</td>
<td th:id="${'claim-' + item.key}" th:text="${item.value}">
Value
</td>
</tr>
</tbody>
</table>
</div>
<form method="get" th:action="@{/oauth/login/auth0}" th:unless="${security}">
<button id="login" class="btn btn-primary" type="submit">Login</button>
</form>
<form method="get" th:action="@{/oauth/logout}" th:if="${security}">
<button id="logout" class="btn btn-danger" type="submit">Logout</button>
</form>
</body>
</html>

Restart your application and now you will be able to log in and log out.

GRADLE
MAVEN
OAUTH_CLIENT_SECRET=AUTH0-CLIENT-SECRET ./gradlew run

Recap

In this guide, you learned how to build a Micronaut app with Java, secure it with OIDC, and configure a logout feature. It's pretty sweet how you can create and configure a Micronaut app with Auth0 so fast!

COMMAND
mn create-app demo --features=security-jwt,security-oauth2,views-thymeleaf
auth0 apps create \
--name "Micronaut" \
--description "Micronaut Example" \
--type regular \
--callbacks http://localhost:8080/oauth/callback/auth0 \
--logout-urls http://localhost:8080/logout \
--reveal-secrets

Be sure to visit our other Micronaut guides Authorization in Micronaut and Role Based Access Control in Micronaut to learn more about Auth0 integration in Micronaut Java applications.