• Stars
    star
    122
  • Rank 292,031 (Top 6 %)
  • Language
    Java
  • License
    Apache License 2.0
  • Created about 5 years ago
  • Updated 11 days ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

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

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.

Recent changes

Have a look at our release notes for recent releases and changes.

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.11.0</version>
</dependency>

or Gradle

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

like this:

import static com.tngtech.keycloakmock.api.ServerConfig.aServerConfig;

import com.tngtech.keycloakmock.api.KeycloakMock;

class Test {

  void checkSomething() {
    KeycloakMock mock = new KeycloakMock(aServerConfig().withPort(8000).withDefaultRealm("master").build());
    mock.start();

    // do your test stuff

    mock.stop();
  }

  void quarkusKeycloakMocks() {
    // to mock Keycloak without context path (v18.0.0+)
    KeycloakMock mockNoContextPath = new KeycloakMock(aServerConfig().withNoContextPath().build());
    // or to use custom one
    KeycloakMock mockCustomContextPath = new KeycloakMock(aServerConfig().withContextPath("/context-path").build());
    // if context path is not provided, '/auth' will be used as default due to backward compatibility reasons
    KeycloakMock mockDefaultContextPath = new KeycloakMock(aServerConfig().build());
    // ...
  }
}

You can also use the convenience wrapper mock-junit for JUnit4

import com.tngtech.keycloakmock.junit.KeycloakMockRule;

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

  // ...

}

or mock-junit5 for JUnit5

import com.tngtech.keycloakmock.junit5.KeycloakMockExtension;

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

  // ...

}

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());

  // ...

}

For a more in-detail test case, please have a look at the AuthenticationTest in our example backend project.

In addition to generating and signing tokens programmatically, the mock also offers

  • user login (using implicit or authorization code flow, including support for redirect to http://localhost and urn:ietf:wg:oauth:2.0:oob for desktop applications) ** instead of a password, you can enter the roles of the user
  • client credentials authentication
  • resource owner password credentials authentication (both for public and confidential clients)

Note that as this is a mock, all flows are allowed for any client. For simplicity all successful calls to the token endpoint return the same response including a refresh token, even for flows which should not contain it according to the specifications.

Developing / testing frontends

It is also possible to run the mock server as a stand-alone application. Just get the ( self-contained) standalone artifact, e.g. from Maven Central, and run it:

$ java -jar standalone.jar &
[main] INFO com.tngtech.keycloakmock.standalone.Main - Server is running on http://localhost:8000

The stand-alone server can be configured using command line parameters. You can call it with --help to get a list of all options.

You can even use it as a replacement in end-to-end tests, as the server is e.g. compatible with cypress-keycloak. Have a look at the example-frontend-react project on this can be set up.

License

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

More Repositories

1

ArchUnit

A Java architecture test library, to specify and assert architecture rules in plain Java
Java
3,181
star
2

ArchUnitNET

A C# architecture test library to specify and assert architecture rules in C# for automated testing.
C#
899
star
3

boost-python-examples

Some examples for the use of boost::python
C++
837
star
4

ArchUnit-Examples

Examples for ArchUnit (A Java architecture test library, to specify and assert architecture rules in plain Java)
Java
544
star
5

JGiven

Behavior-Driven Development in plain Java
Java
438
star
6

junit-dataprovider

A TestNG like dataprovider runner for JUnit with many additional features
Java
246
star
7

virtual-office

Virtual Office gives you transparency on what Zoom.us rooms are currently occupied and who is present
TypeScript
122
star
8

ngqp

Declaratively synchronize form controls with the URL
TypeScript
81
star
9

please-cli

An AI helper for creating CLI commands
Shell
66
star
10

elevation-of-privilege

An online multiplayer version of the threat modeling card games: Elevation of Privilege (EoP), OWASP Cornucopia, OWASP Cumulus, and Elevation of MLsec.
TypeScript
55
star
11

next-generation-scrum-poker

Prototype for a new Scrum Poker
TypeScript
49
star
12

cumulus

Cumulus. Threat modeling the Clouds.
TeX
30
star
13

ApiCenter

A repository for all your API specifications
TypeScript
25
star
14

momo-scheduler

A scheduler that persists jobs in MongoDB
TypeScript
19
star
15

gs-rs

Rust
17
star
16

svnfiltereddump

A tool to extract parts from Subversion repositories
Python
14
star
17

flink-connector-email

IMAP / SMTP connectors for Apache Flinkยฎ
Java
13
star
18

ngx-structurals

Structural utility directives for Angular
TypeScript
13
star
19

jgiven-intellij-plugin

IntelliJ Plugin for JGiven
Kotlin
13
star
20

mustard-cli

A command line interface for bitbucket to review, comment and approve pull requests
C++
12
star
21

sinon-helpers

Create easily configurable sinon stubs that mimic constructors and keep track of their instances
JavaScript
12
star
22

jiradeps

Graphically assess the dependencies of your Jira stories
Python
7
star
23

please-pwsh

An AI helper for creating CLI commands in Powershell
PowerShell
7
star
24

property-loader

Original PropertyLoader reworked
Java
7
star
25

openpgp-validation-server

Automated Validation of OpenPGP Keys
Go
7
star
26

value-provider

Java
5
star
27

rest-demo-jersey

Spring-boot and Jersey based REST service showing the integration of rest-schemagen.
Java
4
star
28

NextGenerationTranslatorBackend

A translation backend for AI translation models
Python
4
star
29

if-webpage-plugins

Impact Framework Plugins for Webpage Measurement (CommonJS)
TypeScript
3
star
30

java-virtual-thread-benchmark

A simple benchmark to compare the performance of Java Virtual Threads, Java Threads and Reactor Core, based on scenarios with jdbc and hibernate. This is the support repo for the Melbourne Java & JVM users group event.
Java
2
star
31

homebrew-please

A Homebrew tap for the Please CLI
Ruby
2
star
32

apt-please

2
star
33

karma-child-process

JavaScript
2
star
34

xtab-converter

Convert existing dbunit XLS files to XML data sets
Java
1
star
35

TNG

1
star
36

SnapToJsClipper

JavaScript
1
star