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: 3.2.7

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:

  • Some time on your hands

  • A decent text editor or IDE

  • JDK 1.8 or greater installed with JAVA_HOME configured appropriately

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=java
If you don’t specify the --build argument, Gradle is used as the build tool.
If you don’t specify the --lang argument, Java is used as the language.

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

4.1. Enable annotation Processing

If you use Java or Kotlin and IntelliJ IDEA, make sure to enable annotation processing.

annotationprocessorsintellij

5. Code

5.1. JSON Web Key Generation

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

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

import io.micronaut.core.annotation.NonNull;
import io.micronaut.core.annotation.Nullable;

import java.util.Optional;

/**
 * <a href="https://datatracker.ietf.org/doc/html/rfc7517">JSON Web Key</a>
 */
public interface JsonWebKeyGenerator {

    @NonNull
    Optional<String> generateJsonWebKey(@Nullable String kid);
}

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.15.2</version>
    <scope>compile</scope>
</dependency>

Create an implementation of JsonWebKeyGenerator

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

import com.nimbusds.jose.JOSEException;
import com.nimbusds.jose.JWSAlgorithm;
import com.nimbusds.jose.jwk.KeyUse;
import com.nimbusds.jose.jwk.gen.RSAKeyGenerator;
import io.micronaut.core.annotation.NonNull;
import io.micronaut.core.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jakarta.inject.Singleton;
import java.util.Optional;
import java.util.UUID;

@Singleton (1)
public class RS256JsonWebKeyGenerator implements JsonWebKeyGenerator {

    private static final Logger LOG = LoggerFactory.getLogger(RS256JsonWebKeyGenerator.class);

    @Override
    @NonNull
    public Optional<String> generateJsonWebKey(@Nullable String kid) {
        try {
            return Optional.of(new RSAKeyGenerator(2048)
                    .algorithm(JWSAlgorithm.RS256)
                    .keyUse(KeyUse.SIGNATURE) // indicate the intended use of the key
                    .keyID(kid != null ? kid : generateKid()) // give the key a unique ID
                    .generate()
                    .toJSONString());

        } catch (JOSEException e) {
            LOG.warn("unable to generate RS256 key",  e);
        }
        return Optional.empty();
    }

    private String generateKid() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }
}
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/java/example/micronaut/MicronautguideCommand.java
package example.micronaut;

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

@Command(name = "keysgen",
        description = "Generates a Json Web Key (JWT) with RS256 algorithm.",
        mixinStandardHelpOptions = true)  (1)
public class MicronautguideCommand implements 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 String kid;

    @Inject
    public JsonWebKeyGenerator jsonWebKeyGenerator; (3)

    public static void main(String[] args) throws Exception {
        PicocliRunner.run(MicronautguideCommand.class, args);
    }

    public void run() {
        jsonWebKeyGenerator.generateJsonWebKey(kid).ifPresent(this::printlnJsonWebKey);
    }

    private void printlnJsonWebKey(String jwk) {
        System.out.println("JWK: " + jwk);
    }
}
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/java/example/micronaut/MicronautguideCommandTest.java
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 java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertNotNull;

public class MicronautguideCommandTest {

    @Test
    public void testGenerateJwk() throws Exception {
        final String jwkJsonRepresentation = executeCommand(MicronautguideCommand.class, new String[] {});
        assertNotNull(jwkJsonRepresentation);
        String prefix = "JWK: ";
        assertNotEquals(jwkJsonRepresentation.indexOf(prefix), -1);
        assertDoesNotThrow(() -> JWK.parse(jwkJsonRepresentation.substring(jwkJsonRepresentation.indexOf(prefix) + prefix.length())));
    }

    String executeCommand(Class commandClass, String[] args) { (1)
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        System.setOut(new PrintStream(baos));
        try (ApplicationContext ctx = ApplicationContext.run(Environment.CLI, Environment.TEST)) {
            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 Image with GraalVM

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

Compiling native images 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.

8.1. Native image generation

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

Java 11
$ sdk install java 21.3.0.r11-grl
If you still use Java 8, use the JDK11 version of GraalVM.
Java 17
$ sdk install java 21.3.0.r17-grl

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

After installing GraalVM, install the native-image component, which is not installed by default:

gu install native-image

To generate a native image using Maven, run:

./mvnw package -Dpackaging=native-image

The native image is created in the target directory and can be run with target/application.

9. Next steps

Read Picocli documentation.

Explore more features with Micronaut Guides.

10. Help with the Micronaut Framework

Object Computing, Inc. (OCI) sponsored the creation of this Guide. A variety of consulting and support services are available.