OAuth2 mocked server for unit testing
- Method for signed JWT creation, with user defined claims
- Http endpoint for retrieval of public keys
On a high level, the OAuth2's Client Credentials flow where the access token is a JWT, is the following:
sequenceDiagram
participant Client
participant Authorization Server
participant Your Application
activate Client
Client->>Authorization Server: Request Token
activate Authorization Server
Authorization Server->>Client: Return JWT
deactivate Authorization Server
Client->>Your Application: Use JWT in the Authorization header
activate Your Application
Your Application->>Authorization Server: Download public keys
activate Authorization Server
Authorization Server->>Your Application: Return public keys
deactivate Authorization Server
Your Application->>Your Application: Validate JWT with public keys
alt If clains are valid
Your Application->>Your Application: Process request
Your Application->>Client: Respond to request
else If claims or the JWT are invalid
Your Application->>Client: Reject request
end
deactivate Your Application
deactivate Client
The purpose of this library is to mock an Authorization Server for unit testing purposes, allowing you to generate JWTs with specific claims and validate them against a mocked server.
- Java >= 21
Gradle
testImplementation("net.uiqui:mock-oauth-server:1.1.3")
Maven
<dependency>
<groupId>net.uiqui</groupId>
<artifactId>mock-oauth-server</artifactId>
<version>1.1.3</version>
<scope>test</scope>
</dependency>
- Create an instance of the OAuthServerMock
private val mockedOauthServer = OAuthServerMock()
- Start the server
@BeforeEach
fun setUp() {
mockedOauthServer.start()
every { mockedAuthenticationConfig.jwksEndpoint } returns mockedOauthServer.getJwksUri()
}
- Generate a JWT with the required claims
val requiredClaims = mapOf(
"iss" to "OAuth-Server-Mock",
"aud" to "this-unit-test",
"appid" to "ad4fc666-c793-11ec-9d64-0242ac120002"
)
val jwtToken = mockedOauthServer.generateJWT(requiredClaims)
- Use the JWT on your request
mockMvc.perform(
get("/your/endpoint")
.header(AUTHORIZATION, "Bearer $jwtToken")
)
- Shutdown the server
@AfterEach
fun cleanUp() {
mockedOauthServer.shutdown()
}
You can find an example of an application using Spring Boot Security and mock-oauth-server here
This project is licensed under the terms of the MIT license