Secure a Micronaut application with Keycloak

Learn how to create a Micronaut application and secure it with an Authorization Server provided by Keycloak.

Authors: Sergio del Amo

Micronaut Version: 4.6.3

1. Getting Started

In this guide, we will create a Micronaut application written in Java.

2. What you will need

To complete this guide, you will need the following:

3. Solution

We recommend that you follow the instructions in the next sections and create the application step by step. However, you can go right to the completed example.

4. Run Keycloak on Docker

Replace the client creation in the tutorial with the steps illustrated following screenshots.

keycloak client step1
keycloak client step2

Set http://localhost:8081/oauth/callback/keycloak as Valid redirect URIs and http://localhost:8081/logout as Valid post logout redirect URIs.

keycloak client step3

5. Writing the Application

Create an application using the Micronaut Command Line Interface or with Micronaut Launch.

mn create-app example.micronaut.micronautguide \
    --features=yaml,views-thymeleaf,security-jwt,security-oauth2,graalvm \
    --build=gradle \
    --lang=java \
    --test=junit
If you don’t specify the --build argument, Gradle with the Kotlin DSL is used as the build tool.
If you don’t specify the --lang argument, Java is used as the language.
If you don’t specify the --test argument, JUnit is used for Java and Kotlin, and Spock is used for Groovy.

The previous command creates a Micronaut application with the default package example.micronaut in a directory named micronautguide.

If you use Micronaut Launch, select Micronaut Application as application type and add yaml, views-thymeleaf, security-jwt, security-oauth2, and graalvm features.

If you have an existing Micronaut application and want to add the functionality described here, you can view the dependency and configuration changes from the specified features, and apply those changes to your application.

5.1. Dev default environment

Modify Application to use dev as a default environment.

src/main/java/example/micronaut/Application.java
package example.micronaut;

import io.micronaut.core.annotation.NonNull;
import io.micronaut.context.ApplicationContextBuilder;
import io.micronaut.context.ApplicationContextConfigurer;
import io.micronaut.context.annotation.ContextConfigurer;
import io.micronaut.runtime.Micronaut;

public class Application {

    @ContextConfigurer
    public static class Configurer implements ApplicationContextConfigurer {
        @Override
        public void configure(@NonNull ApplicationContextBuilder builder) {
            builder.defaultEnvironments("dev");
        }
    }
    public static void main(String[] args) {
        Micronaut.run(Application.class, args);
    }
}

5.2. Start in Port 8081

Create src/main/resources/application-dev.yml. The Micronaut framework applies this configuration file only for the dev environment.

Configure the application to start in port 8081:

src/main/resources/application-dev.yml
micronaut:
  server:
    port: 8081

5.3. Views

Although the Micronaut framework is primarily designed around message encoding / decoding, there are occasions where it is convenient to render a view on the server side.

To use Thymeleaf Java template engine to render views in a Micronaut application add the following dependency on your classpath.

build.gradle
implementation("io.micronaut.views:micronaut-views-thymeleaf")

5.4. OAuth 2.0

To use OAuth 2.0 integration, add the following dependency:

build.gradle
implementation("io.micronaut.security:micronaut-security-oauth2")

Also add JWT Micronaut JWT support dependencies:

build.gradle
implementation("io.micronaut.security:micronaut-security-jwt")

5.5. OAuth 2.0 Configuration

Add the following OAuth2 Configuration:

src/main/resources/application-dev.yml
micronaut:
  security:
    authentication: idtoken (1)
    oauth2:
      clients:
        keycloak: (2)
          client-secret: '${OAUTH_CLIENT_SECRET:secret}' (3)
          client-id: '${OAUTH_CLIENT_ID:myclient}' (4)
          openid:
            issuer: '${OIDC_ISSUER_DOMAIN:`http://localhost:8080`}/realms/${KEYCLOAK_REALM:myrealm}' (5)
    endpoints:
      logout:
        get-allowed: true (6)
1 Set micronaut.security.authentication as idtoken. The idtoken provided by Keycloak when the OAuth 2.0 Authorization code flow ends will be saved in a cookie. The id token is a signed JWT. For every request, the Micronaut framework extracts the JWT from the Cookie and validates the JWT signature with the remote Json Web Key Set exposed by Keycloak. JWKS is exposed by the jws-uri entry of Keycloak .well-known/openid-configuration.
2 The provider identifier should match the last part of the URL you entered as a redirect URL /oauth/callback/keycloak
3 Client Secret. See previous screenshot.
4 Client ID. See previous screenshot.
5 issuer URL. It allows the Micronaut framework to discover the configuration of the OpenID Connect server.
6 Accept GET request to the /logout endpoint.

Check Keycloak realm’s OpenID configuration by visiting http://localhost:8080/realms/myrealm/.well-known/openid-configuration.

The previous configuration uses several placeholders. You will need to set up OAUTH_CLIENT_ID, OAUTH_CLIENT_SECRET, OIDC_ISSUER_DOMAIN and KEYCLOAK_REALM environment variables.

export OAUTH_CLIENT_ID=XXXXXXXXXX
export OAUTH_CLIENT_SECRET=YYYYYYYYYY
export OIDC_ISSUER_DOMAIN=ZZZZZ
export KEYCLOAK_REALM=myrealm

You can obtain the realm name, client id and client secret in the Keycloak UI:

keycloak clientid
keycloak clientsecret

We want to use an Authorization Code grant type flow which it is described in the following diagram:

diagramm

5.6. Home

Create a controller to handle the requests to /. You will display the email of the authenticated person if any. Annotate the controller endpoint with @View since we will use a Thymeleaf template.

src/main/java/example/micronaut/HomeController.java
package example.micronaut;

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 (1)
public class HomeController {

    @Secured(SecurityRule.IS_ANONYMOUS) (2)
    @View("home") (3)
    @Get (4)
    public Map<String, Object> index() {
        return new HashMap<>();
    }
}
1 The class is defined as a controller with the @Controller annotation mapped to the path /.
2 Annotate with io.micronaut.security.Secured to configure secured access. The SecurityRule.IS_ANONYMOUS expression will allow access without authentication.
3 Use View annotation to specify which template to use to render the response.
4 The @Get annotation maps the index method to GET / requests.

Create a thymeleaf template:

src/main/resources/views/home.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Home</title>
</head>
<body>
<h1>Micronaut - Keycloak example</h1>

<h2 th:if="${security}">username: <span th:text="${security.attributes.get('preferred_username')}"></span></h2>
<h2 th:unless="${security}">username: Anonymous</h2>

<nav>
    <ul>
        <li th:unless="${security}"><a href="/oauth/login/keycloak">Enter</a></li>
        <li th:if="${security}"><a href="/oauth/logout">Logout</a></li>
    </ul>
</nav>
</body>
</html>

Also, note that we return an empty model in the controller. However, we are accessing security in the thymeleaf template.

5.7. EndSessionEndpointResolver

Create an EndSessionEndpointResolver replacement to logout from Keycloak.

src/main/java/example/micronaut/EndSessionEndpointResolverReplacement.java
package example.micronaut;

import io.micronaut.context.BeanContext;
import io.micronaut.context.annotation.Replaces;
import io.micronaut.security.config.SecurityConfiguration;
import io.micronaut.security.oauth2.client.OpenIdProviderMetadata;
import io.micronaut.security.oauth2.configuration.OauthClientConfiguration;
import io.micronaut.security.oauth2.endpoint.endsession.request.EndSessionEndpoint;
import io.micronaut.security.oauth2.endpoint.endsession.request.EndSessionEndpointResolver;
import io.micronaut.security.oauth2.endpoint.endsession.request.OktaEndSessionEndpoint;
import io.micronaut.security.oauth2.endpoint.endsession.response.EndSessionCallbackUrlBuilder;
import io.micronaut.security.token.reader.TokenResolver;
import jakarta.inject.Singleton;

import java.util.Optional;
import java.util.function.Supplier;

@Singleton
@Replaces(EndSessionEndpointResolver.class)
public class EndSessionEndpointResolverReplacement extends EndSessionEndpointResolver {
    private final TokenResolver tokenResolver;
    private final SecurityConfiguration securityConfiguration;
    /**
     * @param beanContext The bean context
     */
    public EndSessionEndpointResolverReplacement(BeanContext beanContext,
                                                 SecurityConfiguration securityConfiguration,
                                                 TokenResolver tokenResolver) {
        super(beanContext);
        this.tokenResolver = tokenResolver;
        this.securityConfiguration = securityConfiguration;
    }

    @Override
    public Optional<EndSessionEndpoint> resolve(OauthClientConfiguration oauthClientConfiguration,
                                                Supplier<OpenIdProviderMetadata> openIdProviderMetadata,
                                                EndSessionCallbackUrlBuilder endSessionCallbackUrlBuilder) {
        return Optional.of(new OktaEndSessionEndpoint(endSessionCallbackUrlBuilder,
                oauthClientConfiguration,
                openIdProviderMetadata,
                securityConfiguration,
                tokenResolver));
    }

}

6. Running the Application

To run the application, use the ./gradlew run command, which starts the application on port 8081.

keycloak

7. Generate a Micronaut Application Native Executable with GraalVM

We will use GraalVM, the polyglot embeddable virtual machine, to generate a native executable of our Micronaut application.

Compiling native executables ahead of time with GraalVM improves startup time and reduces the memory footprint of JVM-based applications.

Only Java and Kotlin projects support using GraalVM’s native-image tool. Groovy relies heavily on reflection, which is only partially supported by GraalVM.

7.1. GraalVM installation

The easiest way to install GraalVM on Linux or Mac is to use SDKMan.io.

Java 21
sdk install java 21.0.5-graal
Java 21
sdk use java 21.0.5-graal

For installation on Windows, or for manual installation on Linux or Mac, see the GraalVM Getting Started documentation.

The previous command installs Oracle GraalVM, which is free to use in production and free to redistribute, at no cost, under the GraalVM Free Terms and Conditions.

Alternatively, you can use the GraalVM Community Edition:

Java 21
sdk install java 21.0.2-graalce
Java 21
sdk use java 21.0.2-graalce

7.2. Native executable generation

To generate a native executable using Gradle, run:

./gradlew nativeCompile

The native executable is created in build/native/nativeCompile directory and can be run with build/native/nativeCompile/micronautguide.

It is possible to customize the name of the native executable or pass additional parameters to GraalVM:

build.gradle
graalvmNative {
    binaries {
        main {
            imageName.set('mn-graalvm-application') (1)
            buildArgs.add('--verbose') (2)
        }
    }
}
1 The native executable name will now be mn-graalvm-application
2 It is possible to pass extra arguments to build the native executable

After you execute the native image, navigate to localhost:8081 and authenticate with Keycloak.

8. Next steps

Read Micronaut OAuth 2.0 documentation to learn more.

Checkout Keycloak website.

9. Help with the Micronaut Framework

The Micronaut Foundation sponsored the creation of this Guide. A variety of consulting and support services are available.

10. License

All guides are released with an Apache license 2.0 license for the code and a Creative Commons Attribution 4.0 license for the writing and media (images…​).