mn create-app example.micronaut.micronautguide \
--features=security \
--build=gradle \
--lang=groovy \
--test=spock
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:
-
Some time on your hands
-
A decent text editor or IDE (e.g. IntelliJ IDEA)
-
JDK 21 or greater installed with
JAVA_HOMEconfigured 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.
-
Download and unzip the source
4. Writing the Application
Create an application using the Micronaut Command Line Interface or with Micronaut Launch.
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 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:
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.authentication.Authentication
import io.micronaut.security.rules.SecurityRule
@CompileStatic
@Controller (1)
class PlanController {
@Produces(MediaType.TEXT_PLAIN) (2)
@Secured(SecurityRule.IS_AUTHENTICATED) (3)
@Get("/plan") (4)
String index(Authentication authentication) { (5)
if (authentication.roles.contains("ROLE_EVIL_MASTERMIND")) {
return "Kill Sherlock Holmes and his companions"
}
"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:
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.spock.annotation.MicronautTest
import jakarta.inject.Inject
import spock.lang.Specification
@MicronautTest (1)
class PlanControllerRequiresAuthenticationSpec extends Specification {
@Inject
@Client("/")
HttpClient httpClient (2)
void "plan controller requires authentication"() {
when:
httpClient.toBlocking().exchange(HttpRequest.GET("/plan").accept(MediaType.TEXT_PLAIN))
then:
HttpClientResponseException ex = thrown()
ex.status == HttpStatus.UNAUTHORIZED
}
}
| 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:
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.spock.annotation.MicronautTest
import jakarta.inject.Inject
import jakarta.inject.Singleton
import org.reactivestreams.Publisher
import spock.lang.Specification
@Property(name = "spec.name", value = "PlanControllerAuthenticatedSpec") (1)
@MicronautTest (2)
class PlanControllerAuthenticatedSpec extends Specification {
@Inject
@Client("/")
HttpClient httpClient (3)
void "plan controller returns default plan for authenticated user without evil mastermind role"() {
when:
String response = httpClient.toBlocking().retrieve(HttpRequest.GET("/plan").accept(MediaType.TEXT_PLAIN))
then:
response == "Plan New Year"
}
@Requires(property = "spec.name", value = "PlanControllerAuthenticatedSpec") (1)
@Singleton
static class MockAuthenticationFetcher implements AuthenticationFetcher<HttpRequest<?>> {
@Override
Publisher<Authentication> fetchAuthentication(HttpRequest<?> request) {
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:
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.spock.annotation.MicronautTest
import jakarta.inject.Inject
import jakarta.inject.Singleton
import org.reactivestreams.Publisher
import spock.lang.Specification
@Property(name = "spec.name", value = "PlanControllerAuthenticatedWithRolesSpec") (1)
@MicronautTest (2)
class PlanControllerAuthenticatedWithRolesSpec extends Specification {
@Inject
@Client("/")
HttpClient httpClient (3)
void "plan controller returns evil plan for authenticated user with evil mastermind role"() {
when:
String response = httpClient.toBlocking().retrieve(HttpRequest.GET("/plan").accept(MediaType.TEXT_PLAIN))
then:
response == "Kill Sherlock Holmes and his companions"
}
@Requires(property = "spec.name", value = "PlanControllerAuthenticatedWithRolesSpec") (1)
@Singleton
static class MockAuthenticationFetcher implements AuthenticationFetcher<HttpRequest<?>> {
@Override
Publisher<Authentication> fetchAuthentication(HttpRequest<?> request) {
Publishers.just(Authentication.build("moriarty", ["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:
./gradlew test
Then open build/reports/tests/test/index.html in a browser to see the results.
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…). |