メインコンテンツまでスキップ

Keycloak

Keycloak server を Squid に接続して、データのクエリや更新、executable の呼び出しなどのユーザーアクションを認可します。​

Keycloak は、シングルサインオン、ユーザーフェデレーション、きめ細かな認可を提供するオープンソースの identity and access management ソリューションです。

Keycloak connector を Squid で使用するには、まず次の手順で Keycloak server を Squid に接続します。

  1. Squid Console に移動します。アプリと環境(dev または prod)を選択し、Integrations タブをクリックします。
  2. 次の情報を入力します。
  • Integration ID - integration を識別しやすい、簡潔な ID を選択します。
  • Domain - Keycloak server の URL(例: https://keycloak.example.com)。
  • Realm - Keycloak realm の名前。
  • Client ID - Keycloak realm で設定された OAuth 2.0 client ID。
  1. Add integration をクリックします。

Keycloak connector

Token の要件​

Squid は各 token の issuer と audience を検証するため、次の 2 つが一致する必要があります。

  • Issuer: token の iss claim は <Domain>/realms/<Realm> と一致する必要があります。Domain には、Keycloak が client に公開する issuer URL を設定してください。JWKS の提供にのみ使用される内部 hostname は使用できません。
  • Audience: token の aud claim には Client ID が含まれている必要があります。Keycloak の access token では、デフォルトで aud に client が含まれないことが多いため、client に Audience mapper を追加してください(Client scopes、client の専用 scope の順に移動し、Add mapper で type に Audience を選択します。included client audience に client を設定し、Add to access token をオンにします)。

いずれかの検証に失敗した token は、即座に拒否されるのではなく、未認証として扱われます。リクエストはユーザーなしで処理されるため、ユーザーを必要とする security rule では失敗しますが、公開 path は引き続き実行されます。client は token の有効期限が切れる少し前に token を更新してください。Squid が token の timestamp に対して許容する clock skew は 60 秒のみです。

Connector の使用​

Connector を作成したら、Squid Client SDK を使用して Keycloak token を Squid に渡すことができます。

Client code
import Keycloak from 'keycloak-js';

const keycloak = new Keycloak({
url: 'https://keycloak.example.com',
realm: 'your-realm',
clientId: 'your-client-id',
});

// Initialize Keycloak before setting the auth provider
await keycloak.init({ onLoad: 'login-required' });

squid.setAuthProvider({
integrationId: 'KEYCLOAK_INTEGRATION_ID',
getToken: () => keycloak.token,
});

Token が client に渡されると、Squid は backend function で使用できるように、ユーザーの認証情報を自動的に設定します。

Backend code
@secureCollection('users', 'read')
secureUsersRead(context: QueryContext<User>): boolean {
const userAuth = this.getUserAuth();
}