Testing Micronaut Security

Learn how to test your application’s behavior when a user with specific roles is authenticated

Authors: Sergio del Amo

Micronaut Version: 4.10.7

1. Getting Started

In this guide, you will learn how to test your application’s behavior when a user with specific roles is authenticated.

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,graalvm \
    --build=maven \
    --lang=java \
    --test=junit
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, and graalvm 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. Controller

Given a controller that returns a different output depending on whether the user has a certain role or not:

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

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.authentication.Authentication;
import io.micronaut.security.rules.SecurityRule;

@Controller (1)
class PlanController {

    @Produces(MediaType.TEXT_PLAIN) (2)
    @Secured(SecurityRule.IS_AUTHENTICATED) (3)
    @Get("/plan") (4)
    String index(Authentication authentication) { (5)
        if (authentication.getRoles().contains("ROLE_EVIL_MASTERMIND")) {
            return "Kill Sherlock Holmes and his companions";
        }
        return "Plan New Year";
    }
}
1 The class is defined as a controller with the @Controller annotation mapped to the path /.
2 Set the response content-type to text/plain with the @Produces annotation.
3 Annotate with io.micronaut.security.Secured to configure secured access. The SecurityRule.IS_AUTHENTICATED expression allows only access to authenticated users.
4 The @Get annotation maps the index method to an HTTP GET request on /plan.
5 You can bind Authentication as a parameter in a controller method.

4.2. Tests

4.2.1. Test authentication required

You can write tests to verify the behavior of the controller.

The following test verifies that authentication is required to access the endpoint:

src/test/java/example/micronaut/PlanControllerRequiresAuthenticationTest.java
package example.micronaut;

import io.micronaut.http.HttpRequest;
import io.micronaut.http.HttpStatus;
import io.micronaut.http.MediaType;
import io.micronaut.http.client.BlockingHttpClient;
import io.micronaut.http.client.HttpClient;
import io.micronaut.http.client.annotation.Client;
import io.micronaut.http.client.exceptions.HttpClientResponseException;
import io.micronaut.test.extensions.junit5.annotation.MicronautTest;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.*;

@MicronautTest (1)
class PlanControllerRequiresAuthenticationTest {

    @Test
    void planControllerRequiresAuthentication(@Client("/") HttpClient httpClient) { (2)
        BlockingHttpClient client = httpClient.toBlocking();
        var ex = assertThrows(HttpClientResponseException.class,
                () -> client.exchange(HttpRequest.GET("/plan").accept(MediaType.TEXT_PLAIN)));
        assertEquals(HttpStatus.UNAUTHORIZED, ex.getStatus());
    }
}
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.

4.2.2. Test behavior with an authenticated user without roles

The following test verifies how the controller behaves when the authenticated user lacks the ROLE_EVIL_MASTERMIND role:

src/test/java/example/micronaut/PlanControllerAuthenticatedTest.java
package example.micronaut;

import io.micronaut.context.annotation.Property;
import io.micronaut.context.annotation.Requires;
import io.micronaut.core.async.publisher.Publishers;
import io.micronaut.http.HttpRequest;
import io.micronaut.http.HttpStatus;
import io.micronaut.http.MediaType;
import io.micronaut.http.client.BlockingHttpClient;
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.filters.AuthenticationFetcher;
import io.micronaut.test.extensions.junit5.annotation.MicronautTest;
import jakarta.inject.Singleton;
import org.junit.jupiter.api.Test;
import org.reactivestreams.Publisher;

import java.util.List;

import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;

@Property(name = "spec.name", value = "PlanControllerAuthenticatedTest") (1)
@MicronautTest (2)
class PlanControllerAuthenticatedTest {

    @Test
    void planControllerRequiresAuthentication(@Client("/") HttpClient httpClient) { (3)
        BlockingHttpClient client = httpClient.toBlocking();
        var response = assertDoesNotThrow(
                () -> client.retrieve(HttpRequest.GET("/plan").accept(MediaType.TEXT_PLAIN)));
        assertEquals("Plan New Year", response);
    }

    @Requires(property = "spec.name", value = "PlanControllerAuthenticatedTest") (1)
    @Singleton
    static class MockAuthenticationFetcher implements AuthenticationFetcher<HttpRequest<?>> {

        @Override
        public Publisher<Authentication> fetchAuthentication(HttpRequest<?> request) {
            return Publishers.just(Authentication.build("watson"));
        }
    }
}
1 Combine @Requires and properties (either via the @Property annotation or by passing properties when starting the context) to avoid bean pollution.
2 Annotate the class with @MicronautTest so the Micronaut framework will initialize the application context and the embedded server. More info.
3 Inject the HttpClient bean and point it to the embedded server.

4.2.3. Test behavior with an authenticated user with a role

The following test verifies how the controller behaves when the authenticated user has the ROLE_EVIL_MASTERMIND role:

src/test/java/example/micronaut/PlanControllerAuthenticatedWithRolesTest.java
package example.micronaut;

import io.micronaut.context.annotation.Property;
import io.micronaut.context.annotation.Requires;
import io.micronaut.core.async.publisher.Publishers;
import io.micronaut.http.HttpRequest;
import io.micronaut.http.MediaType;
import io.micronaut.http.client.BlockingHttpClient;
import io.micronaut.http.client.HttpClient;
import io.micronaut.http.client.annotation.Client;
import io.micronaut.security.authentication.Authentication;
import io.micronaut.security.filters.AuthenticationFetcher;
import io.micronaut.test.extensions.junit5.annotation.MicronautTest;
import jakarta.inject.Singleton;
import org.junit.jupiter.api.Test;
import org.reactivestreams.Publisher;

import java.util.List;

import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;

@Property(name = "spec.name", value = "PlanControllerAuthenticatedWithRolesTest") (1)
@MicronautTest (2)
class PlanControllerAuthenticatedWithRolesTest {

    @Test
    void planControllerRequiresAuthentication(@Client("/") HttpClient httpClient) { (3)
        BlockingHttpClient client = httpClient.toBlocking();
        var response = assertDoesNotThrow(
                () -> client.retrieve(HttpRequest.GET("/plan").accept(MediaType.TEXT_PLAIN)));
        assertEquals("Kill Sherlock Holmes and his companions", response);
    }

    @Requires(property = "spec.name", value = "PlanControllerAuthenticatedWithRolesTest") (1)
    @Singleton
    static class MockAuthenticationFetcher implements AuthenticationFetcher<HttpRequest<?>> {

        @Override
        public Publisher<Authentication> fetchAuthentication(HttpRequest<?> request) {
            return Publishers.just(Authentication.build("moriarty", List.of("ROLE_EVIL_MASTERMIND")));
        }
    }
}
1 Combine @Requires and properties (either via the @Property annotation or by passing properties when starting the context) to avoid bean pollution.
2 Annotate the class with @MicronautTest so the Micronaut framework will initialize the application context and the embedded server. More info.
3 Inject the HttpClient bean and point it to the embedded server.

5. Testing the Application

To run the tests:

./mvnw test

6. Next Steps

See the Micronaut security documentation to learn more.

7. Help with the Micronaut Framework

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

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