JWK Generation with a Micronaut Command Line Application

Learn how to generate a JSON Web Key (JWK) with a Micronaut CLI (Command Line interface) application

Authors: Sergio del Amo

Micronaut Version: 4.6.3

1. Getting Started

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

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. Writing the App

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

mn create-cli-app  example.micronaut.micronautguide --build=maven --lang=kotlin
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.

5. Code

5.1. JSON Web Key Generation

Create an interface to encapsulate the contract to generate a JWK (JSON Web Key)

src/main/kotlin/example/micronaut/JsonWebKeyGenerator.kt
package example.micronaut

import java.util.Optional

/**
 * [JSON Web Key](https://datatracker.ietf.org/doc/html/rfc7517)
 */
interface JsonWebKeyGenerator {

    fun generateJsonWebKey(kid: String?): Optional<String>
}

To generate a JWK, use Nimbus JOSE + JWT, an open source Java library to generate JSON Web Tokens (JWT).

Add the following dependency:

pom.xml
<dependency>
    <groupId>com.nimbusds</groupId>
    <artifactId>nimbus-jose-jwt</artifactId>
    <version>9.40</version>
    <scope>compile</scope>
</dependency>

Create an implementation of JsonWebKeyGenerator

src/main/kotlin/example/micronaut/RS256JsonWebKeyGenerator.kt
package example.micronaut

import com.nimbusds.jose.JOSEException
import com.nimbusds.jose.JWSAlgorithm.RS256
import com.nimbusds.jose.jwk.KeyUse.SIGNATURE
import com.nimbusds.jose.jwk.gen.RSAKeyGenerator
import jakarta.inject.Singleton
import org.slf4j.LoggerFactory
import java.util.Optional
import java.util.UUID

@Singleton (1)
class RS256JsonWebKeyGenerator : JsonWebKeyGenerator {

    override fun generateJsonWebKey(kid: String?): Optional<String> {
        return try {
            Optional.of(RSAKeyGenerator(2048)
                    .algorithm(RS256)
                    .keyUse(SIGNATURE) // indicate the intended use of the key
                    .keyID(kid ?: generateKid()) // give the key a unique ID
                    .generate()
                    .toJSONString())
        } catch (e: JOSEException) {
            LOG.warn("unable to generate RS256 key", e)
            Optional.empty()
        }
    }

    private fun generateKid(): String = UUID.randomUUID().toString().replace("-".toRegex(), "")

    companion object {
        private val LOG = LoggerFactory.getLogger(RS256JsonWebKeyGenerator::class.java)
    }
}
1 Use jakarta.inject.Singleton to designate a class as a singleton.

5.2. CLI Command

Micronaut CLI applications use Picocli.

Replace the contents of MicronautguideCommand:

src/main/kotlin/example/micronaut/MicronautguideCommand.kt
package example.micronaut

import io.micronaut.configuration.picocli.PicocliRunner
import jakarta.inject.Inject
import picocli.CommandLine.Command
import picocli.CommandLine.Option

@Command(name = "keysgen",
         description = ["Generates a Json Web Key (JWT) with RS256 algorithm."],
         mixinStandardHelpOptions = true) (1)
class MicronautguideCommand : Runnable {

    @Option(names = ["-kid"], (2)
            required = false,
            description = ["Key ID. Parameter is used to match a specific key. If not specified a random Key ID is generated."])
    private var kid: String? = null

    @Inject
    lateinit var jsonWebKeyGenerator: JsonWebKeyGenerator (3)

    override fun run() {
        jsonWebKeyGenerator.generateJsonWebKey(kid).ifPresent { jwk: String -> printlnJsonWebKey(jwk) }
    }

    private fun printlnJsonWebKey(jwk: String) {
        println("JWK: $jwk")
    }

    companion object {
        @JvmStatic fun main(args: Array<String>) {
            PicocliRunner.run(MicronautguideCommand::class.java, *args)
        }
    }
}
1 Annotate with @Command and provide the command description.
2 Create an optional Picocli Option for the key identifier.
3 You can use dependency injection in your CLI application.

Replace the contents of MicronautguideCommandTest:

src/test/kotlin/example/micronaut/MicronautguideCommandTest.kt
package example.micronaut

import com.nimbusds.jose.jwk.JWK
import io.micronaut.configuration.picocli.PicocliRunner
import io.micronaut.context.ApplicationContext
import io.micronaut.context.env.Environment
import org.junit.jupiter.api.Assertions.assertDoesNotThrow
import org.junit.jupiter.api.Assertions.assertNotEquals
import org.junit.jupiter.api.Assertions.assertNotNull
import org.junit.jupiter.api.Test
import java.io.ByteArrayOutputStream
import java.io.OutputStream
import java.io.PrintStream

class MicronautguideCommandTest {

    @Test
    fun testGenerateJwk() {
        val jwkJsonRepresentation = executeCommand(MicronautguideCommand::class.java, arrayOf())
        assertNotNull(jwkJsonRepresentation)

        val prefix = "JWK: "
        assertNotEquals(jwkJsonRepresentation.indexOf(prefix), -1)
        assertDoesNotThrow<JWK> {
            JWK.parse(jwkJsonRepresentation.substring(jwkJsonRepresentation.indexOf(prefix) + prefix.length))
        }
    }

    private fun executeCommand(commandClass: Class<MicronautguideCommand>, args: Array<String>): String { (1)
        val baos: OutputStream = ByteArrayOutputStream()
        System.setOut(PrintStream(baos))
        ApplicationContext.run(Environment.CLI, Environment.TEST).use { ctx ->
            PicocliRunner.run(commandClass, ctx, *args)
        }
        return baos.toString()
    }
}
1 Annotate the class with @MicronautTest so the Micronaut framework will initialize the application context and the embedded server. More info.

6. Testing the Application

To run the tests:

./mvnw test

7. Running the CLI App

Create an executable jar including all dependencies:

./mvnw package

Execute the CLI with the help argument.

java -jar target/micronautguide-0.1.jar --help
12:14:47.355 [main] INFO  i.m.context.env.DefaultEnvironment - Established active environments: [cli]
Usage: keysgen [-hV] [-kid=<kid>]
Generates a Json Web Key (JWT) with RS256 algorithm.
  -h, --help       Show this help message and exit.
      -kid=<kid>   Key ID. Parameter is used to match a specific key. If not
                     specified a random Key ID is generated.
  -V, --version    Print version information and exit.

8. Generate a Micronaut Application Native Executable with GraalVM

We will use GraalVM, an advanced JDK with ahead-of-time Native Image compilation, to generate a native executable of this Micronaut application.

Compiling Micronaut applications ahead of time with GraalVM significantly 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.

8.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

For installation on Windows, or for a 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

8.2. Native Executable Generation

To generate a native executable using Maven, run:

./mvnw package -Dpackaging=native-image

The native executable is created in the target directory and can be run with target/micronautguide.

It is possible to customize the name of the native executable or pass additional build arguments using the Maven plugin for GraalVM Native Image building. Declare the plugin as following:

pom.xml
<plugin>
    <groupId>org.graalvm.buildtools</groupId>
    <artifactId>native-maven-plugin</artifactId>
    <version>0.10.3</version>
    <configuration>
        <!-- <1> -->
        <imageName>mn-graalvm-application</imageName> (1)
        <buildArgs>
              <!-- <2> -->
          <buildArg>-Ob</buildArg>
        </buildArgs>
    </configuration>
</plugin>
1 The native executable name will now be mn-graalvm-application.
2 It is possible to pass extra build arguments to native-image. For example, -Ob enables the quick build mode.

9. Next Steps

Read Picocli documentation.

Explore more features with Micronaut Guides.

10. Help with the Micronaut Framework

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

11. 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…​).