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=kotlin \
    --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/kotlin/example/micronaut/PlanController.kt
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)
    fun index(authentication: Authentication): String = (5)
        if ("ROLE_EVIL_MASTERMIND" in authentication.roles) {
            "Kill Sherlock Holmes and his companions"
        } else {
            "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/kotlin/example/micronaut/PlanControllerRequiresAuthenticationTest.kt
package example.micronaut

import io.micronaut.http.HttpRequest
import io.micronaut.http.HttpStatus
import io.micronaut.http.MediaType
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.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertThrows
import org.junit.jupiter.api.Test

@MicronautTest (1)
class PlanControllerRequiresAuthenticationTest(@Client("/") val httpClient: HttpClient) { (2)

    @Test
    fun planControllerRequiresAuthentication() {
        val client = httpClient.toBlocking()
        val ex = assertThrows(HttpClientResponseException::class.java) {
            client.exchange<String, String>(HttpRequest.GET<String>("/plan").accept(MediaType.TEXT_PLAIN))
        }
        assertEquals(HttpStatus.UNAUTHORIZED, ex.status)
    }
}
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/kotlin/example/micronaut/PlanControllerAuthenticatedTest.kt
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.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.Assertions.assertDoesNotThrow
import org.junit.jupiter.api.function.ThrowingSupplier
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
import org.reactivestreams.Publisher

@Property(name = "spec.name", value = "PlanControllerAuthenticatedTest") (1)
@MicronautTest (2)
class PlanControllerAuthenticatedTest(@Client("/") val httpClient: HttpClient) { (3)

    @Test
    fun planControllerReturnsDefaultPlanForAuthenticatedUser() {
        val client = httpClient.toBlocking()
        val response = assertDoesNotThrow(ThrowingSupplier {
            client.retrieve(HttpRequest.GET<String>("/plan").accept(MediaType.TEXT_PLAIN))
        })
        assertEquals("Plan New Year", response)
    }

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

        override fun fetchAuthentication(request: HttpRequest<*>?): Publisher<Authentication> =
            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/kotlin/example/micronaut/PlanControllerAuthenticatedWithRolesTest.kt
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.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.Assertions.assertDoesNotThrow
import org.junit.jupiter.api.function.ThrowingSupplier
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
import org.reactivestreams.Publisher

@Property(name = "spec.name", value = "PlanControllerAuthenticatedWithRolesTest") (1)
@MicronautTest (2)
class PlanControllerAuthenticatedWithRolesTest(@Client("/") val httpClient: HttpClient) { (3)

    @Test
    fun planControllerReturnsEvilPlanForAuthenticatedUserWithRole() {
        val client = httpClient.toBlocking()
        val response = assertDoesNotThrow(ThrowingSupplier {
            client.retrieve(HttpRequest.GET<String>("/plan").accept(MediaType.TEXT_PLAIN))
        })
        assertEquals("Kill Sherlock Holmes and his companions", response)
    }

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

        override fun fetchAuthentication(request: HttpRequest<*>?): Publisher<Authentication> =
            Publishers.just(Authentication.build("moriarty", listOf("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…​).