Skip to content

jjmrocha/mock-oauth-server

Repository files navigation

OAuth Server Mock

OAuth2 mocked server for unit testing

Features

  • 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
Loading

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.

Requirements

  • Java >= 21

Quick Start

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>

How to Use

  1. Create an instance of the OAuthServerMock
private val mockedOauthServer = OAuthServerMock()
  1. Start the server
@BeforeEach
fun setUp() {
    mockedOauthServer.start()
    every { mockedAuthenticationConfig.jwksEndpoint } returns mockedOauthServer.getJwksUri()
}
  1. 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)
  1. Use the JWT on your request
mockMvc.perform(
    get("/your/endpoint")
        .header(AUTHORIZATION, "Bearer $jwtToken")
)
  1. 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

License

This project is licensed under the terms of the MIT license

About

Unit test oauth2 mocked server

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages