Micronaut JWT Authentication

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

Authors: Sergio del Amo

Micronaut Version: 4.4.0

1. 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 unsecure 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

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

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.

4.1. Configuration

Note the following configuration in the generated application.properties:

src/main/resources/application.properties
(1)
micronaut.security.authentication=bearer
(2)
micronaut.security.token.jwt.signatures.secret.generator.secret="${JWT_GENERATOR_SIGNATURE_SECRET:pleaseChangeThisSecretForANewOne}"'
1 Set authentication to bearer to receive a JSON response from the login endpoint.
2 Change this to your own secret and keep it safe (do not store this in your VCS).

4.2. Authentication Provider

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

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

import io.micronaut.core.annotation.NonNull
import io.micronaut.core.annotation.Nullable
import io.micronaut.http.HttpRequest
import io.micronaut.security.authentication.AuthenticationFailureReason
import io.micronaut.security.authentication.AuthenticationRequest
import io.micronaut.security.authentication.AuthenticationResponse
import io.micronaut.security.authentication.provider.HttpRequestAuthenticationProvider
import jakarta.inject.Singleton

@Singleton (1)
class AuthenticationProviderUserPassword<B> implements HttpRequestAuthenticationProvider<B> { (2)

    @Override
    AuthenticationResponse authenticate(
            @Nullable HttpRequest<B> httpRequest,
            @NonNull AuthenticationRequest<String, String> authenticationRequest
    ) {
        return authenticationRequest.identity == "sherlock" && authenticationRequest.secret == "password"
                ? AuthenticationResponse.success(authenticationRequest.getIdentity())
                : AuthenticationResponse.failure(AuthenticationFailureReason.CREDENTIALS_DO_NOT_MATCH)
    }
}
1 Use jakarta.inject.Singleton to designate a class as a singleton.
2 A Micronaut Authentication Provider implements the interface io.micronaut.security.authentication.provider.HttpRequestAuthenticationProvider.

4.3. Controller

Create HomeController which resolves the base URL /:

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

import groovy.transform.CompileStatic
import io.micronaut.http.MediaType
import io.micronaut.http.annotation.Controller
import io.micronaut.http.annotation.Get
import io.micronaut.http.annotation.Produces
import io.micronaut.security.annotation.Secured
import io.micronaut.security.rules.SecurityRule

import java.security.Principal

@CompileStatic
@Secured(SecurityRule.IS_AUTHENTICATED) (1)
@Controller (2)
class HomeController {

    @Produces(MediaType.TEXT_PLAIN)
    @Get (3)
    String index(Principal principal) { (4)
        principal.name
    }
}
1 Annotate with io.micronaut.security.Secured to configure secured access. The isAuthenticated() expression will allow access only to authenticated users.
2 Annotate with io.micronaut.http.annotation.Controller to designate the class as a Micronaut controller.
3 You can specify the HTTP verb that a controller action responds to. To respond to a GET request, use the io.micronaut.http.annotation.Get annotation.
4 If a user is authenticated, the Micronaut framework will bind the user object to an argument of type java.security.Principal (if present).

5. Tests

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

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

import com.nimbusds.jwt.JWTParser
import com.nimbusds.jwt.SignedJWT
import io.micronaut.http.HttpRequest
import io.micronaut.http.HttpResponse
import io.micronaut.http.client.HttpClient
import io.micronaut.http.client.annotation.Client
import io.micronaut.http.client.exceptions.HttpClientResponseException
import io.micronaut.security.authentication.UsernamePasswordCredentials
import io.micronaut.security.token.render.BearerAccessRefreshToken
import io.micronaut.test.extensions.spock.annotation.MicronautTest
import jakarta.inject.Inject
import spock.lang.Specification

import static io.micronaut.http.HttpStatus.OK
import static io.micronaut.http.HttpStatus.UNAUTHORIZED
import static io.micronaut.http.MediaType.TEXT_PLAIN

@MicronautTest (1)
class JwtAuthenticationSpec extends Specification {

    @Inject
    @Client("/")
    HttpClient client (2)

    void 'Accessing a secured URL without authenticating returns unauthorized'() {
        when:
        client.toBlocking().exchange(HttpRequest.GET('/').accept(TEXT_PLAIN))

        then:
        HttpClientResponseException e = thrown()
        e.status == UNAUTHORIZED (3)
    }

    void "upon successful authentication, a JSON Web token is issued to the user"() {
        when: 'Login endpoint is called with valid credentials'
        UsernamePasswordCredentials creds = new UsernamePasswordCredentials("sherlock", "password")
        HttpRequest request = HttpRequest.POST('/login', creds) (4)
        HttpResponse<BearerAccessRefreshToken> rsp = client.toBlocking().exchange(request, BearerAccessRefreshToken) (5)

        then: 'the endpoint can be accessed'
        rsp.status == OK

        when:
        BearerAccessRefreshToken bearerAccessRefreshToken = rsp.body()

        then:
        bearerAccessRefreshToken.username == 'sherlock'
        bearerAccessRefreshToken.accessToken

        and: 'the access token is a signed JWT'
        JWTParser.parse(bearerAccessRefreshToken.accessToken) instanceof SignedJWT

        when: 'passing the access token as in the Authorization HTTP Header with the prefix Bearer allows the user to access a secured endpoint'
        String accessToken = bearerAccessRefreshToken.accessToken
        HttpRequest requestWithAuthorization = HttpRequest.GET('/' )
                .accept(TEXT_PLAIN)
                .bearerAuth(accessToken) (6)
        HttpResponse<String> response = client.toBlocking().exchange(requestWithAuthorization, String)

        then:
        response.status == OK
        response.body() == 'sherlock' (7)
    }
}
1 Annotate the class with @MicronautTest so the Micronaut framework will initialize the application context and the embedded server. More info.
2 Inject the HttpClient bean and point it to the embedded server.
3 When you include the security dependencies, security is considered enabled and every endpoint is secured by default.
4 To login, do a POST request to /login with your credentials as a JSON payload in the body of the request.
5 The Framework makes it easy to bind JSON responses into Java objects.
6 The Framework supports RFC 6750 Bearer Token specification out-of-the-box. We supply the JWT token in the Authorization HTTP Header.
7 Use .body() to retrieve the parsed payload.

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

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

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

import com.nimbusds.jwt.JWTParser
import com.nimbusds.jwt.SignedJWT
import io.micronaut.security.authentication.UsernamePasswordCredentials
import io.micronaut.security.token.render.BearerAccessRefreshToken
import io.micronaut.test.extensions.spock.annotation.MicronautTest
import jakarta.inject.Inject
import spock.lang.Specification

@MicronautTest
class DeclarativeHttpClientWithJwtSpec extends Specification {

    @Inject
    AppClient appClient (1)

    void "Verify JWT authentication works with declarative @Client"() {
        when: 'Login endpoint is called with valid credentials'
        UsernamePasswordCredentials creds = new UsernamePasswordCredentials("sherlock", "password")
        BearerAccessRefreshToken loginRsp = appClient.login(creds) (2)

        then:
        loginRsp
        loginRsp.accessToken
        JWTParser.parse(loginRsp.accessToken) instanceof SignedJWT

        when:
        String msg = appClient.home("Bearer $loginRsp.accessToken") (3)

        then:
        msg == 'sherlock'
    }
}
1 Inject AppClient bean from the application context.
2 To login, do a POST request to /login with your credentials as a JSON payload in the body of the request.
3 Supply the JWT to the HTTP Authorization header value to the @Client method.

6. 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
(1)
micronaut.security.token.jwt.generator.refresh-token.secret="${JWT_GENERATOR_SIGNATURE_SECRET:pleaseChangeThisSecretForANewOne}"'
1 To generate a refresh token your application must have beans of type: 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 secret to use SignedRefreshTokenGenerator which implements both RefreshTokenGenerator and RefreshTokenValidator.

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

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

import com.nimbusds.jwt.JWTParser
import com.nimbusds.jwt.SignedJWT
import io.micronaut.http.HttpRequest
import io.micronaut.http.client.HttpClient
import io.micronaut.http.client.annotation.Client
import io.micronaut.security.authentication.UsernamePasswordCredentials
import io.micronaut.security.token.render.BearerAccessRefreshToken
import io.micronaut.test.extensions.spock.annotation.MicronautTest
import jakarta.inject.Inject
import spock.lang.Specification

@MicronautTest
class LoginIncludesRefreshTokenSpec extends Specification {

    @Inject
    @Client("/")
    HttpClient client

    void "upon successful authentication, the user gets an access token and a refresh token"() {
        when: 'Login endpoint is called with valid credentials'
        UsernamePasswordCredentials creds = new UsernamePasswordCredentials("sherlock", "password")
        HttpRequest request = HttpRequest.POST('/login', creds)
        BearerAccessRefreshToken rsp = client.toBlocking().retrieve(request, BearerAccessRefreshToken)

        then:
        rsp.username == 'sherlock'
        rsp.accessToken
        rsp.refreshToken (1)

        and: 'access token is a JWT'
        JWTParser.parse(rsp.accessToken) instanceof SignedJWT
    }
}
1 A refresh token is returned.

6.1. 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
<dependency> (1)
    <groupId>io.micronaut</groupId>
    <artifactId>micronaut-data-processor</artifactId>
    <scope>compile</scope>
</dependency>
<dependency> (2)
    <groupId>io.micronaut.data</groupId>
    <artifactId>micronaut-data-jdbc</artifactId>
    <scope>compile</scope>
</dependency>
<dependency> (3)
    <groupId>io.micronaut.sql</groupId>
    <artifactId>micronaut-jdbc-hikari</artifactId>
    <scope>compile</scope>
</dependency>
<dependency> (4)
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <scope>runtime</scope>
</dependency>
1 Micronaut data is a build time tool. You need to add the build time annotation processor
2 Add the Micronaut Data JDBC dependency
3 Add a Hikari connection pool
4 Add a JDBC driver. Add H2 driver

Create an entity to save the issued Refresh Tokens.

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

import groovy.transform.CompileStatic
import io.micronaut.core.annotation.NonNull
import io.micronaut.data.annotation.DateCreated
import io.micronaut.data.annotation.GeneratedValue
import io.micronaut.data.annotation.Id
import io.micronaut.data.annotation.MappedEntity

import jakarta.validation.constraints.NotBlank
import jakarta.validation.constraints.NotNull
import java.time.Instant

@CompileStatic
@MappedEntity (1)
class RefreshTokenEntity {

    @Id (2)
    @GeneratedValue (3)
    @NonNull
    Long id

    @NonNull
    @NotBlank
    String username

    @NonNull
    @NotBlank
    String refreshToken

    @NonNull
    @NotNull
    Boolean revoked

    @DateCreated (4)
    @NonNull
    @NotNull
    Instant dateCreated
}


import groovy.transform.CompileStatic
import io.micronaut.core.annotation.NonNull
import io.micronaut.data.annotation.DateCreated
import io.micronaut.data.annotation.GeneratedValue
import io.micronaut.data.annotation.Id
import io.micronaut.data.annotation.MappedEntity

import jakarta.validation.constraints.NotBlank
import jakarta.validation.constraints.NotNull
import java.time.Instant

@CompileStatic
@MappedEntity (1)
class RefreshTokenEntity {

    @Id (2)
    @GeneratedValue (3)
    @NonNull
    Long id

    @NonNull
    @NotBlank
    String username

    @NonNull
    @NotBlank
    String refreshToken

    @NonNull
    @NotNull
    Boolean revoked

    @DateCreated (4)
    @NonNull
    @NotNull
    Instant dateCreated

}
1 Specifies the entity is mapped to the database
2 Specifies the ID of an entity
3 Specifies that the property value is generated by the database and not included in inserts
4 Allows assigning a data created value (such as a java.time.Instant) prior to an insert

Create a CrudRepository to include methods to peform Create, Read, Updated and Delete operations with the RefreshTokenEntity.

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

import io.micronaut.core.annotation.NonNull
import io.micronaut.data.jdbc.annotation.JdbcRepository
import io.micronaut.data.repository.CrudRepository

import jakarta.transaction.Transactional
import jakarta.validation.constraints.NotBlank
import jakarta.validation.constraints.NotNull

import static io.micronaut.data.model.query.builder.sql.Dialect.H2

@JdbcRepository(dialect = H2) (1)
interface RefreshTokenRepository extends CrudRepository<RefreshTokenEntity, Long> { (2)

    @Transactional
    RefreshTokenEntity save(@NonNull @NotBlank String username,
                            @NonNull @NotBlank String refreshToken,
                            @NonNull @NotNull Boolean revoked) (3)

    Optional<RefreshTokenEntity> findByRefreshToken(@NonNull @NotBlank String refreshToken) (4)

    long updateByUsername(@NonNull @NotBlank String username,
                          boolean revoked) (5)
}
1 The interface is annotated with @JdbcRepository and specifies a dialect of H2 used to generate queries
2 The CrudRepository interface has two generic arguments; the entity type (in this case RefreshTokenEntity) and the ID type (in this case Long)
3 When a new refresh token is issued we will use this method to persist it
4 Before issuing a new access token, we will use this method to check if the supplied refresh token exists
5 We can revoke the refresh tokens of a particular user with this method

6.2. 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:

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

import io.micronaut.security.authentication.Authentication
import io.micronaut.security.errors.OauthErrorResponseException
import io.micronaut.security.token.event.RefreshTokenGeneratedEvent
import io.micronaut.security.token.refresh.RefreshTokenPersistence
import jakarta.inject.Singleton
import org.reactivestreams.Publisher
import reactor.core.publisher.Flux
import reactor.core.publisher.FluxSink

import static io.micronaut.security.errors.IssuingAnAccessTokenErrorCode.INVALID_GRANT

@Singleton (1)
class CustomRefreshTokenPersistence implements RefreshTokenPersistence {

    private final RefreshTokenRepository refreshTokenRepository

    CustomRefreshTokenPersistence(RefreshTokenRepository refreshTokenRepository) { (2)
        this.refreshTokenRepository = refreshTokenRepository
    }

    @Override
    void persistToken(RefreshTokenGeneratedEvent event) { (3)
        if (event?.refreshToken && event?.authentication?.name) {
            String payload = event.refreshToken
            refreshTokenRepository.save(event.authentication.name, payload, false) (4)
        }
    }

    @Override
    Publisher<Authentication> getAuthentication(String refreshToken) {
        Flux.create(emitter -> {
            Optional<RefreshTokenEntity> tokenOpt = refreshTokenRepository.findByRefreshToken(refreshToken)
            if (tokenOpt.isPresent()) {
                RefreshTokenEntity token = tokenOpt.get()
                if (token.getRevoked()) {
                    emitter.error(new OauthErrorResponseException(INVALID_GRANT, "refresh token revoked", null)) (5)
                } else {
                    emitter.next(Authentication.build(token.username)) (6)
                    emitter.complete()
                }
            } else {
                emitter.error(new OauthErrorResponseException(INVALID_GRANT, "refresh token not found", null)) (7)
            }
        }, FluxSink.OverflowStrategy.ERROR)
    }
}
1 Use jakarta.inject.Singleton to designate a class as a singleton.
2 Constructor injection of RefreshTokenRepository.
3 When a new refresh token is issued, the application emits an event of type RefreshTokenGeneratedEvent. We listen for it and save the token in the database.
4 The event contains both the refresh token and the user details associated to the token.
5 Throw an exception if the token is revoked.
6 Return the user details associated to the refresh token, e.g. username, roles, attributes, etc.
7 Throw an exception if the token is not found.

6.3. Test Refresh Token

6.3.1. 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:

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

import io.micronaut.core.type.Argument
import io.micronaut.http.HttpRequest
import io.micronaut.http.client.HttpClient
import io.micronaut.http.client.annotation.Client
import io.micronaut.http.client.exceptions.HttpClientResponseException
import io.micronaut.security.endpoints.TokenRefreshRequest
import io.micronaut.security.token.render.BearerAccessRefreshToken
import io.micronaut.test.extensions.spock.annotation.MicronautTest
import jakarta.inject.Inject
import spock.lang.Specification

import static io.micronaut.http.HttpStatus.BAD_REQUEST

@MicronautTest
class UnsignedRefreshTokenSpec extends Specification {

    @Inject
    @Client("/")
    HttpClient client

    void 'Accessing a secured URL without authenticating returns unauthorized'() {

        given:
        String unsignedRefreshedToken = "foo" (1)

        when:
        Argument<BearerAccessRefreshToken> bodyArgument = Argument.of(BearerAccessRefreshToken)
        Argument<Map> errorArgument = Argument.of(Map)

        client.toBlocking().exchange(
                HttpRequest.POST("/oauth/access_token", new TokenRefreshRequest(TokenRefreshRequest.GRANT_TYPE_REFRESH_TOKEN, unsignedRefreshedToken)),
                bodyArgument,
                errorArgument)

        then:
        HttpClientResponseException e = thrown()
        e.status == BAD_REQUEST

        when:
        Optional<Map> mapOptional = e.response.getBody(Map)

        then:
        mapOptional.isPresent()

        when:
        Map m = mapOptional.get()

        then:
        m.error == 'invalid_grant'
        m.error_description == 'Refresh token is invalid'
    }
}
1 Use an unsigned token

6.3.2. Test Refresh Token Not Found

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

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

import io.micronaut.core.type.Argument
import io.micronaut.http.HttpRequest
import io.micronaut.http.client.HttpClient
import io.micronaut.http.client.annotation.Client
import io.micronaut.http.client.exceptions.HttpClientResponseException
import io.micronaut.security.authentication.Authentication
import io.micronaut.security.token.generator.RefreshTokenGenerator
import io.micronaut.security.endpoints.TokenRefreshRequest
import io.micronaut.security.token.render.BearerAccessRefreshToken
import io.micronaut.test.extensions.spock.annotation.MicronautTest
import jakarta.inject.Inject
import spock.lang.Specification

import static io.micronaut.http.HttpStatus.BAD_REQUEST

@MicronautTest
class RefreshTokenNotFoundSpec extends Specification {

    @Inject
    @Client("/")
    HttpClient client

    @Inject
    RefreshTokenGenerator refreshTokenGenerator

    void 'Accessing a secured URL without authenticating returns unauthorized'() {
        given:
        Authentication user = Authentication.build("sherlock")

        when:
        String refreshToken = refreshTokenGenerator.createKey(user)
        Optional<String> refreshTokenOptional = refreshTokenGenerator.generate(user, refreshToken)

        then:
        refreshTokenOptional.isPresent()

        when:
        String signedRefreshToken = refreshTokenOptional.get()  (1)
        Argument<BearerAccessRefreshToken> bodyArgument = Argument.of(BearerAccessRefreshToken)
        Argument<Map> errorArgument = Argument.of(Map)
        HttpRequest req = HttpRequest.POST("/oauth/access_token", new TokenRefreshRequest(TokenRefreshRequest.GRANT_TYPE_REFRESH_TOKEN, signedRefreshToken))
        client.toBlocking().exchange(req, bodyArgument, errorArgument)

        then:
        HttpClientResponseException e = thrown()
        e.status == BAD_REQUEST

        when:
        Optional<Map> mapOptional = e.response.getBody(Map)

        then:
        mapOptional.isPresent()

        when:
        Map m = mapOptional.get()

        then:
        m.error == 'invalid_grant'
        m.error_description == 'refresh token not found'
    }
}
1 Supply a signed token which was never saved.

6.3.3. Test Refresh Token Revocation

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

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

import io.micronaut.context.ApplicationContext
import io.micronaut.core.type.Argument
import io.micronaut.http.HttpRequest
import io.micronaut.http.client.HttpClient
import io.micronaut.http.client.exceptions.HttpClientResponseException
import io.micronaut.runtime.server.EmbeddedServer
import io.micronaut.security.authentication.Authentication
import io.micronaut.security.token.generator.RefreshTokenGenerator
import io.micronaut.security.endpoints.TokenRefreshRequest
import io.micronaut.security.token.render.BearerAccessRefreshToken
import spock.lang.AutoCleanup
import spock.lang.Shared
import spock.lang.Specification

import static io.micronaut.http.HttpStatus.BAD_REQUEST

class RefreshTokenRevokedSpec extends Specification {

    @AutoCleanup
    @Shared
    EmbeddedServer embeddedServer = ApplicationContext.run(EmbeddedServer, [:])

    @Shared
    HttpClient client = embeddedServer.applicationContext.createBean(HttpClient, embeddedServer.URL)

    @Shared
    RefreshTokenGenerator refreshTokenGenerator = embeddedServer.applicationContext.getBean(RefreshTokenGenerator)

    @Shared
    RefreshTokenRepository refreshTokenRepository = embeddedServer.applicationContext.getBean(RefreshTokenRepository)

    void 'Accessing a secured URL without authenticating returns unauthorized'() {
        given:
        Authentication user = Authentication.build("sherlock")

        when:
        String refreshToken = refreshTokenGenerator.createKey(user)
        Optional<String> refreshTokenOptional = refreshTokenGenerator.generate(user, refreshToken)

        then:
        refreshTokenOptional.isPresent()

        when:
        String signedRefreshToken = refreshTokenOptional.get()
        refreshTokenRepository.save(user.name, refreshToken, true) (1)

        then:
        refreshTokenRepository.count() == old(refreshTokenRepository.count()) + 1

        when:
        Argument<BearerAccessRefreshToken> bodyArgument = Argument.of(BearerAccessRefreshToken)
        Argument<Map> errorArgument = Argument.of(Map)
        client.toBlocking().exchange(
                HttpRequest.POST("/oauth/access_token", new TokenRefreshRequest(TokenRefreshRequest.GRANT_TYPE_REFRESH_TOKEN, signedRefreshToken)),
                bodyArgument,
                errorArgument)

        then:
        HttpClientResponseException e = thrown()
        e.status == BAD_REQUEST

        when:
        Optional<Map> mapOptional = e.response.getBody(Map)

        then:
        mapOptional.isPresent()

        when:
        Map m = mapOptional.get()

        then:
        m.error == 'invalid_grant'
        m.error_description == 'refresh token revoked'

        cleanup:
        refreshTokenRepository.deleteAll()
    }
}
1 Save the token but flag it as revoked

6.3.4. Test Access Token Refresh

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

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

import io.micronaut.http.HttpRequest
import io.micronaut.http.client.HttpClient
import io.micronaut.http.client.annotation.Client
import io.micronaut.security.authentication.UsernamePasswordCredentials
import io.micronaut.security.endpoints.TokenRefreshRequest
import io.micronaut.security.token.render.AccessRefreshToken
import io.micronaut.security.token.render.BearerAccessRefreshToken
import io.micronaut.test.extensions.spock.annotation.MicronautTest
import jakarta.inject.Inject
import spock.lang.Shared
import spock.lang.Specification
import spock.util.concurrent.PollingConditions

@MicronautTest(rollback = false) (1)
class OauthAccessTokenSpec extends Specification {

    @Inject
    @Client("/")
    HttpClient client (2)

    @Shared
    @Inject
    RefreshTokenRepository refreshTokenRepository

    void "Verify JWT access token refresh works"() {
        given:
        String username = 'sherlock'

        when: 'login endpoint is called with valid credentials'
        def creds = new UsernamePasswordCredentials(username, "password")
        HttpRequest request = HttpRequest.POST('/login', creds)
        BearerAccessRefreshToken rsp = client.toBlocking().retrieve(request, BearerAccessRefreshToken)

        then: 'the refresh token is saved to the database'
        new PollingConditions().eventually {
            assert refreshTokenRepository.count() == old(refreshTokenRepository.count()) + 1
        }

        and: 'response contains an access token token'
        rsp.accessToken

        and: 'response contains a refresh token'
        rsp.refreshToken

        when:
        sleep(1_000) // sleep for one second to give time for the issued at `iat` Claim to change
        AccessRefreshToken refreshResponse = client.toBlocking().retrieve(HttpRequest.POST('/oauth/access_token',
                new TokenRefreshRequest(TokenRefreshRequest.GRANT_TYPE_REFRESH_TOKEN, rsp.refreshToken)), AccessRefreshToken) (1)

        then:
        refreshResponse.accessToken
        refreshResponse.accessToken != rsp.accessToken (2)

        cleanup:
        refreshTokenRepository.deleteAll()
    }
}
1 Make a POST request to /oauth/access_token with the refresh token in the JSON payload to get a new access token
2 A different access token is retrieved.

7. Testing the Application

To run the tests:

./mvnw test

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

9. Next steps

Learn more about JWT Authentication in the official documentation.

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