These tutorials target Micronaut Framework 3. Read, Guides for Micronaut Framework 4.

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

1. Getting Started

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

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=groovy
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.

5. Code

5.1. JSON Web Key Generation

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

src/main/groovy/example/micronaut/JsonWebKeyGenerator.groovy
package example.micronaut

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

/**
 * <a href="https://datatracker.ietf.org/doc/html/rfc7517">JSON Web Key</a>
 */
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>@nimbus-jose-jwtVersion@</version>
    <scope>compile</scope>
</dependency>

Create an implementation of JsonWebKeyGenerator

src/main/groovy/example/micronaut/RS256JsonWebKeyGenerator.groovy
package example.micronaut

import com.nimbusds.jose.JOSEException
import com.nimbusds.jose.jwk.gen.RSAKeyGenerator
import groovy.transform.CompileStatic
import groovy.util.logging.Slf4j
import io.micronaut.core.annotation.NonNull
import io.micronaut.core.annotation.Nullable
import jakarta.inject.Singleton

import static com.nimbusds.jose.JWSAlgorithm.RS256
import static com.nimbusds.jose.jwk.KeyUse.SIGNATURE

@Slf4j
@CompileStatic
@Singleton (1)
class RS256JsonWebKeyGenerator implements JsonWebKeyGenerator {

    @Override
    @NonNull
    Optional<String> generateJsonWebKey(@Nullable String kid) {
        try {
            Optional.of(new RSAKeyGenerator(2048)
                    .algorithm(RS256)
                    .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)
            Optional.empty()
        }
    }

    private String generateKid() {
        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/groovy/example/micronaut/MicronautguideCommand.groovy
package example.micronaut

import groovy.transform.CompileStatic
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)
@CompileStatic
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
    JsonWebKeyGenerator jsonWebKeyGenerator (3)

    static void main(String[] args) {
        PicocliRunner.run(MicronautguideCommand, args)
    }

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

    private void printlnJsonWebKey(String jwk) {
        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/groovy/example/micronaut/MicronautguideCommandSpec.groovy
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 spock.lang.Specification

class MicronautguideCommandSpec extends Specification {

    void testGenerateJwk() {
        when:
        String jwkJsonRepresentation = executeCommand(MicronautguideCommand, [] as String[])

        then:
        jwkJsonRepresentation != null

        when:
        String prefix = 'JWK: '

        then:
        jwkJsonRepresentation.indexOf(prefix) > -1

        when:
        JWK.parse(jwkJsonRepresentation.substring(jwkJsonRepresentation.indexOf(prefix) + prefix.length()))

        then:
        noExceptionThrown()
    }

    private String executeCommand(Class commandClass, String[] args) { (1)
        OutputStream baos = new ByteArrayOutputStream()
        System.setOut(new PrintStream(baos))
        try (ApplicationContext ctx = ApplicationContext.run(Environment.CLI, Environment.TEST)) {
            PicocliRunner.run(commandClass, ctx, args)
        }
        baos
    }
}
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. Next steps

Read Picocli documentation.

Explore more features with Micronaut Guides.

9. Help with the Micronaut Framework

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