Skip to content

A Java library to test REST endpoints secured by Keycloak via OpenID connect.

License

Notifications You must be signed in to change notification settings

cloudfirst-dev/keycloak-mock

 
 

Repository files navigation

Java CI Github release date Github release Maven release Sonarcloud

Keycloak Mock

Keycloak is a single sign-on solution that supports the Open ID connect standard. However, it does not deliver any test support. This library is intended to fill that gap.

Usage

All artifacts are available on Maven Central Repository under the group ID com.tngtech.keycloakmock.

Testing authenticated backend calls

When testing a REST backend that is protected by a Keycloak adapter, the mock allows to generate valid access tokens with configurable content (e.g. roles).

You can create and start the mock directly from the mock artifact using Maven

<dependency>
    <groupId>com.tngtech.keycloakmock</groupId>
    <artifactId>mock</artifactId>
    <scope>test</scope>
    <version>0.3.0</version>
</dependency>

or Gradle

testImplementation 'com.tngtech.keycloakmock:mock:0.3.0'

like this:

import com.tngtech.keycloakmock.api.KeycloakVerificationMock;

class Test {

  KeycloakVerificationMock mock = new KeycloakVerificationMock(8000, "master");

  static {
    mock.start();
  }

}

Or you can use use the JUnit4 test rule from the mock-junit artifact

import com.tngtech.keycloakmock.api.junit.KeycloakMock;

public class Test {
  @ClassRule
  public static KeyCloakMock mock = new KeycloakMock();

  // ...
    
}

or the JUnit5 extension from the mock-junit5 module

import com.tngtech.keycloakmock.api.junit5.KeycloakMock;

class Test {
  @RegisterExtension
  static KeyCloakMock mock = new KeyCloakMock();

  // ...
    
}

to let JUnit start the mock for you.

You can then generate a token of your choosing by providing a TokenConfig:

import static com.tngtech.keycloakmock.api.TokenConfig.aTokenConfig;

class Test {

  String accessToken = mock.getAccessToken(aTokenConfig().withRole("ROLE_ADMIN").build());

  // ...

}

Developing / testing frontends

It is also possible to run a stand-alone mock server that provides a login page where a username and an optional list of roles can be specified. Just get the (self-contained) standalone artifact, e.g. from Maven Central, and run it:

$ java -jar standalone.jar &
Server is running on http://localhost:8000

Please note that currently, only the authorization code flow and the implicit flow are supported.

License

This project is licensed under the Apache 2.0 license (see LICENSE).

About

A Java library to test REST endpoints secured by Keycloak via OpenID connect.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • Java 83.1%
  • JavaScript 8.3%
  • FreeMarker 5.4%
  • HTML 1.9%
  • CSS 1.0%
  • Shell 0.2%
  • Batchfile 0.1%