How to: test a component with a given authentication
To verify the authorization "in isolation" on a component, without executing the HTTP request processing
chain, MockMvc (see How to: test a REST controller with MockMvc)
cannot be used. The JeapAuthenticationToken for the test call must therefore be provided to the Spring
Security context by other means.
Steps
- Add the test dependency
jeap-spring-boot-security-starter-testto the project (see Integration). This module provides a JUnit 5 extension with which a test method can be executed with a givenJeapAuthenticationToken. - Define a method on the test class that provides the
JeapAuthenticationTokento use for the test, for example built with the JeapAuthenticationTestTokenBuilder. - Activate this test functionality on the test method through the annotation @WithAuthentication, referencing the name of the method from step 2.
This example shows how to use this annotation in integration tests for components/services.
The example does not start a complete Spring Boot application but a Spring application context containing only the
elements required by the test. The Spring Boot autoconfiguration of the jeap-spring-boot-security-starter is not
executed, i.e. the property jeap.security.oauth2.resourceserver.authorization-server.issuer mentioned in
How to: test a REST controller with MockMvc is irrelevant for these tests.
Related
- Testing secured REST APIs — the test-support classes used above, and the other test use cases.
- How to: test a REST controller with MockMvc — the alternative for testing through the HTTP request processing chain.
- How to: test programmatic authorization checks in a unit test — the equivalent for tests that run outside a Spring application context.