How to: test a REST endpoint with full OAuth2 security
If a test of a REST request should also pass through the OAuth2 resource part of the security chain, a valid OAuth2
access token must be created for the request, and a JWKS endpoint must be available to verify the signature of the
access token. The configuration class
JeapOAuth2IntegrationTestConfiguration
from the module jeap-spring-boot-security-starter-test makes both easy.
Steps
- Import the configuration
JeapOAuth2IntegrationTestConfigurationin the test. - Override the following two OAuth2 resource properties appropriately:
jeap.security.oauth2.resourceserver.authorization-server.jwk-set-urijeap.security.oauth2.resourceserver.authorization-server.issuer
- Create an OAuth2 access token suitable for the specific test case with the help of the
JwsBuilderFactory. - Pass the access token as bearer authorization token in the header of the HTTP request to the protected resource.
This test class gives examples of Spring Boot tests with full security. The example uses
REST Assured to implement the tests on the REST endpoints.
Setting the OAuth2 access token in the request is very simple: given().auth().oauth2("the-token")...
Details on how the test support provided by the JeapOAuth2IntegrationTestConfiguration works can be found in
Test support, in particular
JeapOAuth2IntegrationTestConfiguration
and ServletJwksEndpointMock.
Related
- Testing secured REST APIs — the test-support classes used above, and the other test use cases.
- How to: disable security in a Spring Boot test — the opposite case, where a Spring Boot test should leave security aspects out.
- Tokens in the Blueprint Microservice — structure and claims of the access tokens the
JwsBuilderFactorycreates.