Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

keycloak-tests

БесплатноБез исполняемых скриптовНе проверен

Use whenever an app uses self-hosted Keycloak and needs integration tests: a throwaway Keycloak per test class via Testcontainers, realm JSON imports, OIDC…

testlandот testland★ 18 звёзд на GitHub

Об этом скилле

keycloak-tests

Overview

Tests start their own Keycloak in a container, import a committed realm fixture, check the realm is up, then drive the real OIDC endpoints. A realm holds users, credentials, roles and groups; a client is an application that asks Keycloak to authenticate users ([Server Admin Guide][kc-admin]).

When to use

  • The app uses self-hosted Keycloak as its identity provider.
  • Tests need an isolated Keycloak per run instead of a shared dev or staging server.
  • A test covers client-credentials, authorization-code + PKCE, password (legacy only), token exchange, UMA permissions, or introspection.

Step 1 - Start Keycloak per run with a pinned tag

# tests/auth/conftest.py
import pytest
import requests
from testcontainers.keycloak import KeycloakContainer

@pytest.fixture(scope="session")
def keycloak():
    kc = KeycloakContainer("quay.io/keycloak/keycloak:26.0") \
        .with_realm_import_file("tests/auth/fixtures/test-realm.json")
    with kc:  # the context manager starts and stops the container
        yield kc

with_realm_import_file() mounts the file at /opt/keycloak/data/import/realm.json and adds --import-realm to the start-dev command; start() waits for /health/ready. The admin user comes from the container (test / test unless passed), not from environment variables pointing at another server ([testcontainers-python Keycloak module][tc-py]). The default image is latest, so always pass a tag.

Java ([testcontainers-keycloak][tc-java]):

@Container
static KeycloakContainer keycloak =
    new KeycloakContainer("quay.io/keycloak/keycloak:26.0")
        .withRealmImportFile("/test-realm.json");   // classpath resource

Every URL comes from the container (keycloak.get_url()); never a literal localhost:8080, which can hit a different server on a developer machine and nothing on CI.

Step 2 - Commit a sanitised realm fixture

Export the realm (Admin Console: Realm settings → Action → Partial export), then sanitise it with one repeatable command and commit the result:

jq '
  del(.smtpServer, .identityProviders, .identityProviderMappers)
  | del(.components["org.keycloak.keys.KeyProvider"])
  | del(.components["org.keycloak.storage.UserStorageProvider"])
  | (.clients[]? | select(.publicClient != true and .secret? != null) | .secret) = "test-secret"
' realm-export.json > tests/auth/fixtures/test-realm.json

This drops environment-coupled blocks (SMTP relay, external identity providers, LDAP user federation) that an isolated container cannot reach, drops signing keys so the container generates its own, and replaces each confidential client's secret with a fixed test value instead of deleting it (an imported confidential client still needs one). Add local test users with fixed passwords under users if tests log in. Then grep the output for anything that still looks live (secret, password, bindCredential, privateKey) before committing.

Step 3 - Check the realm is really there

Before any flow test, assert the started server serves the imported realm, so a bad import fails here and not as a 404 in every test:

@pytest.fixture(scope="session")
def realm(keycloak):
    base = keycloak.get_url()
    r = requests.get(f"{base}/realms/test/.well-known/openid-configuration", timeout=5)
    assert r.status_code == 200, f"realm 'test' not imported: {r.status_code}"
    disco = r.json()
    assert disco["token_endpoint"] == f"{base}/realms/test/protocol/openid-connect/token"
    assert "introspection_endpoint" in disco
    return disco

If it fails: check the container log for the import line, the realm name inside the JSON, and that the file path exists. Fix the fixture, not the paths: Keycloak 17+ serves /realms/... with no /auth prefix ([migrating to Quarkus][kc-upg]).

Step 4 - Client-credentials grant

def test_client_credentials(realm):
    r = requests.post(realm["token_endpoint"], data={
        "grant_type": "client_credentials",
        "client_id": "service-account-client",
        "client_secret": "test-secret",
    }, timeout=5)
    assert r.status_code == 200
    body = r.json()
    assert body["token_type"].lower() == "bearer"
    assert body["expires_in"] > 0

Pass the token to the app's protected endpoint and assert 200, and pass no token and an expired or tampered one and assert 401.

The password grant must not be used per RFC 9700 ([RFC 9700][rfc9700]). Keep an existing legacy password-grant test only while its client still allows it; write new user-login tests with authorization-code + PKCE (Step 6).

Step 5 - Token introspection in the resource server

The resource server must authenticate the introspection call with its own client credentials, not with the caller's token, and refuse the request on any answer other than "active": true (non-200, timeout, connection error). Recipe: references/endpoint-recipes.md.

Step

Полный SKILL.md на GitHub

Установить keycloak-tests в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

Вложенные файлы

.tessl-plugin/plugin.jsonevals/expired-token-still-opens-the-api/criteria.jsonevals/expired-token-still-opens-the-api/task.mdevals/mobile-login-test-copied-from-the-legacy-one/criteria.jsonevals/mobile-login-test-copied-from-the-legacy-one/task.mdevals/realm-export-about-to-be-committed-with-live-secrets/criteria.jsonevals/realm-export-about-to-be-committed-with-live-secrets/task.mdevals/token-requests-404-after-the-server-upgrade/criteria.jsonevals/token-requests-404-after-the-server-upgrade/task.mdevals/two-ci-builds-fighting-over-the-same-login-server/criteria.jsonevals/two-ci-builds-fighting-over-the-same-login-server/task.mdreferences/endpoint-recipes.mdreferences/flow-recipes.md

FAQ

Что делает скилл keycloak-tests?

Use whenever an app uses self-hosted Keycloak and needs integration tests: a throwaway Keycloak per test class via Testcontainers, realm JSON imports, OIDC discovery, token and introspection endpoints, the admin REST API, password, auth-code, client-credentials and token-exchange flows, and UMA.

Как установить скилл keycloak-tests?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл keycloak-tests запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить keycloak-tests с