Groovy / Maven

Micronaut JWT Authentication

Learn how to secure a Micronaut application using JWT (JSON Web Token) Authentication.

Sergio del Amo
On this guide
In this section

Getting Started

The Micronaut framework ships with security capabilities based on JSON Web Token (JWT). JWT is an IETF standard which defines a secure way to encapsulate arbitrary data that can be sent over insecure URLs.

In this guide you will create a Micronaut application written in Groovy and secure it with JWT.

The following sequence illustrates the authentication flow:

jwt bearer token

What you will need

To complete this guide, you will need the following:

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.

Writing the Application

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

mn create-app example.micronaut.micronautguide \
    --features=security-jwt,data-jdbc,reactor,validation \
    --build=maven \
    --lang=groovy \
    --test=spock
Note
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 security-jwt, data-jdbc, reactor, and validation features.

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

Configuration

Note the following configuration in the generated application.properties:

src/main/resources/application.properties

Authentication Provider

To keep this guide simple, create a naive AuthenticationProvider to simulate user authentication.

groovy/src/main/groovy/example/micronaut/AuthenticationProviderUserPassword.groovy

Controller

Create HomeController which resolves the base URL /:

groovy/src/main/groovy/example/micronaut/HomeController.groovy

Tests

Create a test to verify a user is able to login and access a secured endpoint.

groovy/src/test/groovy/example/micronaut/JwtAuthenticationSpec.groovy

Use the Micronaut HTTP Client and JWT

To access a secured endpoint, you can also use a Micronaut HTTP Client and supply the JWT token in the Authorization header.

First create a @Client with a method home which accepts an Authorization HTTP header.

groovy/src/test/groovy/example/micronaut/AppClient.groovy
package example.micronaut

import groovy.transform.CompileStatic
import io.micronaut.http.annotation.Body
import io.micronaut.http.annotation.Consumes
import io.micronaut.http.annotation.Get
import io.micronaut.http.annotation.Header
import io.micronaut.http.annotation.Post
import io.micronaut.http.client.annotation.Client
import io.micronaut.security.authentication.UsernamePasswordCredentials
import io.micronaut.security.token.render.BearerAccessRefreshToken

import static io.micronaut.http.HttpHeaders.AUTHORIZATION
import static io.micronaut.http.MediaType.TEXT_PLAIN

@CompileStatic
@Client("/")
interface AppClient {

    @Post("/login")
    BearerAccessRefreshToken login(@Body UsernamePasswordCredentials credentials)

    @Consumes(TEXT_PLAIN)
    @Get
    String home(@Header(AUTHORIZATION) String authorization)
}

Create a test which uses the previous @Client

groovy/src/test/groovy/example/micronaut/DeclarativeHttpClientWithJwtSpec.groovy

Issuing a Refresh Token

Access tokens expire. You can control the expiration with micronaut.security.token.jwt.generator.access-token.expiration. In addition to the access token, you can configure your login endpoint to also return a refresh token. You can use the refresh token to obtain a new access token.

First, add the following configuration:

src/main/resources/application.properties

RefreshTokenGenerator, RefreshTokenValidator, and RefreshTokenPersistence. We will deal with the latter in the next section. For the generator and validator, Micronaut Security ships with SignedRefreshTokenGenerator. It creates and verifies a JWS (JSON Web Signature) encoded object whose payload is a UUID with a hash-based message authentication code (HMAC). You need to provide a secret to use SignedRefreshTokenGenerator, which implements both RefreshTokenGenerator and RefreshTokenValidator.

Create a test to verify the login endpoint responds with both an access token and a refresh token:

groovy/src/test/groovy/example/micronaut/LoginIncludesRefreshTokenSpec.groovy

Save Refresh Token

We may want to save a refresh token issued by the application, for example, to revoke a user’s refresh tokens, so that a particular user cannot obtain a new access token, and thus access the application’s endpoints.

Persist the refresh tokens with help of Micronaut Data.

Micronaut Data is a database access toolkit that uses Ahead of Time (AoT) compilation to pre-compute queries for repository interfaces that are then executed by a thin, lightweight runtime layer.

In particular, use Micronaut JDBC

Micronaut Data JDBC is an implementation that pre-computes native SQL queries (given a particular database dialect) and provides a repository implementation that is a simple data mapper between a JDBC ResultSet and an object.

The data-jdbc feature adds the following dependencies:

pom.xml

Create an entity to save the issued refresh tokens.

groovy/src/main/groovy/example/micronaut/RefreshTokenEntity.groovy

Create a CrudRepository to include methods to perform Create, Read, Update, and Delete operations with the RefreshTokenEntity.

groovy/src/main/groovy/example/micronaut/RefreshTokenRepository.groovy

Refresh Controller

Enable the Refresh Controller via configuration and provide an implementation of RefreshTokenPersistence.

To enable the refresh controller, create a bean of type RefreshTokenPersistence which leverages the Micronaut Data repository we coded in the previous section:

groovy/src/main/groovy/example/micronaut/CustomRefreshTokenPersistence.groovy

Test Refresh Token

Test Refresh Token Validation

Refresh tokens issued by SignedRefreshTokenGenerator, the default implementation of RefreshTokenGenerator, are signed.

SignedRefreshTokenGenerator implements both RefreshTokenGenerator and RefreshTokenValidator.

The bean of type RefreshTokenValidator is used by the Refresh Controller to ensure the refresh token supplied is valid.

Create a test for this:

groovy/src/test/groovy/example/micronaut/UnsignedRefreshTokenSpec.groovy

Test Refresh Token Not Found

Create a test to verify that sending a valid refresh token that was not persisted returns HTTP Status 400.

groovy/src/test/groovy/example/micronaut/RefreshTokenNotFoundSpec.groovy

Test Refresh Token Revocation

Generate a valid refresh token, save it but flag it as revoked. Expect a 400.

groovy/src/test/groovy/example/micronaut/RefreshTokenRevokedSpec.groovy

Test Access Token Refresh

Login, obtain both access token and refresh token, with the refresh token obtain a different access token:

groovy/src/test/groovy/example/micronaut/OauthAccessTokenSpec.groovy

Testing the Application

To run the tests:

./mvnw test

Running the Application

To run the application, use the ./mvnw mn:run command, which starts the application on port 8080.

Send a request to the login endpoint:

curl -X "POST" "http://localhost:8080/login" -H 'Content-Type: application/json' -d $'{"username": "sherlock","password": "password"}'
{"username":"sherlock","access_token":"eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJzaGVybG9jayIsIm5iZiI6MTYxNDc2NDEzNywicm9sZXMiOltdLCJpc3MiOiJjb21wbGV0ZSIsImV4cCI6MTYxNDc2NzczNywiaWF0IjoxNjE0NzY0MTM3fQ.cn8bOjlccFqeUQA7x7MnfacMNPjSVAtWP65z1c8eaJc","refresh_token":"eyJhbGciOiJIUzI1NiJ9.NDI1ZjAxZTktYTRmYS00MmU5LTllYjctOWU2ZTNhNTI5YmQ1.RUc2iCfZdPQdwg2U0Nw_LLzZQIIDp5_Is2UWeHVZT7E","token_type":"Bearer","expires_in":3600}

Next Steps

Learn more about JWT Authentication in the official documentation.

Help with the Micronaut Framework

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

License

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