Kiges ID API
Integrate sign-in with Kiges ID and, when your client is authorized, access organization data and management APIs. This reference describes the public OAuth/OIDC and organization APIs implemented by this service.
Overview
API resources return JSON. Authentication depends on the endpoint: OAuth protocol and discovery endpoints have their own protocol rules, user and organization resource endpoints use OAuth bearer tokens, and some Kiges service integrations use separate credentials and are not part of this public reference.
Base URL
https://id.kiges.cc/api
Authentication
OAuth bearer token for protected user and organization resources
Content Type
JSON for API resources; OAuth token requests use form encoding
OIDC Discovery
/api/.well-known/openid-configuration
Quick Start
- Register an OAuth client and use the exact redirect URI registered for that client.
- Use Authorization Code with PKCE (S256). Generate and retain a unique verifier and state value for each sign-in attempt.
- Redirect to
https://id.kiges.cc/oauth/authorize, then exchange the returned code athttps://id.kiges.cc/api/oauth/token. - Validate state before exchanging the code. Include the original
code_verifierin the token request. - Call a protected endpoint with
Authorization: Bearer <access_token>.
PKCE S256 is supported by the server. The current authorization endpoint does not appear to require PKCE, so clients must enforce PKCE in their own flow and should not treat server support as proof that every authorization request used it.
Authentication
Protected user and organization API calls use an OAuth 2.0 access token in the Authorization: Bearer header. The authorization and token endpoints are used during sign-in; discovery and JWKS endpoints are public. Do not send bearer tokens in URLs.
Public and confidential clients
A browser-only application is a public client: use Authorization Code with PKCE and do not include a client secret. A secret shipped in JavaScript, a React bundle, or any publicly distributed app is not confidential. A confidential client can authenticate at the token endpoint only from a trusted server environment; keep its secret in server-side configuration or a secret manager.
Browser apps that call the token or resource endpoints cross-origin also need their origin permitted by the deployment's CORS allowlist. Confirm the registered browser origin with Kiges ID; do not treat CORS as API authorization.
Getting an Access Token
1. Redirect the user to the authorization endpoint:
https://id.kiges.cc/oauth/authorize
2. After the user authorizes, exchange the code at the token endpoint:
https://id.kiges.cc/api/oauth/token
POST https://id.kiges.cc/api/oauth/token
Content-Type: application/x-www-form-urlencoded
grant_type=authorization_code
&client_id=YOUR_CLIENT_ID
&client_secret=YOUR_SERVER_SIDE_CLIENT_SECRET
&redirect_uri=https://app.example/callback
&code=AUTHORIZATION_CODE
&code_verifier=PKCE_CODE_VERIFIER
{
"token_type": "Bearer",
"expires_in": 31536000,
"access_token": "<ACCESS_TOKEN>",
"refresh_token": "<REFRESH_TOKEN>",
"id_token": "<ID_TOKEN>"
}
Current implementation note: Passport currently defaults access tokens and refresh tokens to 31,536,000 seconds (one year). This is observed server behavior, not a security recommendation or a guaranteed lifetime; rely on the response's expires_in value. ID tokens are issued for one hour. Ask the Kiges ID operator about token lifetime policy before production use.
For a browser-based app, prefer a backend-for-frontend: keep access and refresh tokens on the server and expose an appropriately protected, secure, HttpOnly session cookie to the browser. If a browser client must hold tokens, never put them in localStorage; browser storage remains accessible to injected script. Refresh tokens are credentials: store them securely, rotate or replace them only as the token response directs, and do not log them. The token revocation behavior and endpoint are not documented here because they were not verified in this implementation.
Using the Token
Authorization: Bearer <ACCESS_TOKEN>
Refreshing an Access Token
The discovery document advertises the refresh_token grant. Send a refresh request to the same token endpoint using form encoding. Confidential clients must authenticate using their registered server-side client credentials; public clients must not send a secret.
POST https://id.kiges.cc/api/oauth/token
Content-Type: application/x-www-form-urlencoded
grant_type=refresh_token
&client_id=<CLIENT_ID>
&refresh_token=<REFRESH_TOKEN>
Scopes
Request specific scopes during the OAuth authorization to control what data your application can access. Include scopes as a space-separated list in the scope parameter.
| Scope | Description | Grants Access To |
|---|---|---|
openid | OIDC sign-in | Requests an ID token and identifies the user with sub. The custom /api/userinfo endpoint returns sub for any valid bearer token. |
profile | Basic profile | Name, surname, birthday, gender, phone, and language/locale claims. The Kiges-specific /api/user response also returns email with this scope; OIDC UserInfo email claims require email. |
email | Email address | email and email_verified on UserInfo; email claims in the ID token. |
name, surname, birthday, gender, phone, language | Individual profile claims | Request only the corresponding profile fields; profile grants the combined set. |
organizations | Organization memberships | Membership data in /api/user, /api/userinfo, /api/v1/me, and organization API reads. |
org:read | Read org data | Organization API read endpoints. Also enables membership data in the user endpoints. |
org:manage | Organization API writes | Required scope for write operations; also allows reads. Organization role permissions still apply. |
The discovery document also advertises app:read and app:manage. Application-management endpoints and client eligibility are outside this reference; consult the current discovery metadata and confirm access with Kiges ID before relying on them.
On UserInfo, Kiges maps birthday to birthdate, phone to phone_number (with phone_number_verified: false), and language to locale. gender and organizations are implementation-specific claims. The current ID token implementation does not include birthday, phone, or organization claims, even though discovery lists these claims as supported; obtain those values from UserInfo where authorized.
openid email organizations. Add profile only when the listed profile fields are needed. Add org:read or org:manage only for calls to the organization API.
https://id.kiges.cc/oauth/authorize?
client_id=YOUR_CLIENT_ID
&redirect_uri=https://app.example/callback
&response_type=code
&scope=openid profile email organizations org:read
&state=<ONE_TIME_SESSION_BOUND_RANDOM_STATE>
&code_challenge=PKCE_CHALLENGE
&code_challenge_method=S256
Error Handling
The API uses standard HTTP status codes and returns error details in JSON format.
| Code | Meaning | Description |
|---|---|---|
200 | OK | Request succeeded |
201 | Created | Resource was created |
204 | No Content | Successful deletion, no response body |
400 | Bad Request | Invalid request parameters |
401 | Unauthorized | Missing or invalid access token |
403 | Forbidden | Insufficient scope or organization permission |
404 | Not Found | Resource does not exist |
409 | Conflict | Resource already exists (duplicate member, etc.) |
422 | Unprocessable | Validation error — see errors field |
429 | Too Many Requests | Rate limit exceeded |
{
"error": "insufficient_scope",
"message": "The access token does not have the 'org:read' scope."
}
// Validation Error (422)
{
"message": "The given data was invalid.",
"errors": {
"name": ["The name field is required."]
}
}
Rate Limits
The general API limiter allows 60 requests per minute per authenticated user (or by IP when unauthenticated). OAuth token issuance has a separate limit of 30 requests per minute; individual endpoints may impose stricter limits. Limits are server configuration and can change. Throttled requests return HTTP 429; honor Retry-After when present.
| Header | Description |
|---|---|
X-RateLimit-Limit | Maximum requests per window |
X-RateLimit-Remaining | Requests remaining in current window |
Retry-After | Seconds until the rate limit resets (only on 429) |
User Context
GET /api/v1/me
Returns the authenticated user's profile along with their organization memberships, roles, and permissions. This is the primary endpoint your SaaS should call after authentication to get everything needed to set up the user's session.
{
"data": {
"uuid": "550e8400-e29b-41d4-a716-446655440000",
"name": "John",
"surname": "Doe",
"email": "john@example.com",
"email_verified": true,
"session_id": "<SESSION_ID>",
"session_version": 1,
"organizations": [
{
"uuid": "org-uuid-1",
"name": "Example Organization",
"slug": "acme-corp",
"role": "admin",
"permissions": ["manage_members", "manage_roles", "invite_members", ...],
"members_count": 42
}
]
}
}
GET /api/user
Returns user profile fields based on granted scopes. Lighter than /v1/me — returns only what your scopes allow.
OAuth bearer token required. Returns sub, numeric id, and updated_at at the top level. profile or an individual matching scope adds basic fields; email is gated by email or profile. Organization memberships are included for organizations, org:read, or org:manage. This response is Kiges-specific, not an OIDC UserInfo response.
GET /api/userinfo
Standard OpenID Connect UserInfo endpoint. Returns claims based on granted scopes using OIDC standard field names (given_name, family_name, email_verified, etc.).
/api/userinfo is a Kiges OIDC UserInfo endpoint. It always returns sub and a Unix timestamp updated_at. email gates email claims; profile or the matching individual profile scope gates profile claims. Organization claims are included with organizations, org:read, or org:manage. Kiges also returns gender, organizations, and updated_at as implementation-specific claims.
{
"sub": "<USER_UUID>",
"name": "Example User",
"given_name": "Example",
"family_name": "User",
"email": "user@example.com",
"email_verified": true,
"phone_number": "+10000000000",
"phone_number_verified": false,
"locale": "en",
"birthdate": "1990-01-01",
"gender": "<GENDER_VALUE>",
"organizations": [],
"updated_at": 1763200000
}
Organizations
The core organization, member, role, invitation, audit-log, and webhook-delivery endpoints require OAuth organization scopes. Reads accept org:read, org:manage, or (where membership data is returned) organizations. Writes require org:manage and enforce the current user's role permissions; scopes alone do not grant a role. Organization creation and membership may be subject to account or subscription limits.
List Organizations
Returns all organizations the authenticated user belongs to.
{
"data": [
{
"uuid": "550e8400-...",
"name": "Example Organization",
"slug": "acme-corp",
"description": "Our company workspace",
"is_active": true,
"members_count": 42,
"role": "admin",
"permissions": ["manage_members", "view_members", ...],
"created_at": "2026-01-15T10:30:00+00:00"
}
]
}
Create Organization
Request Body
| Field | Type | Required | Description |
|---|---|---|---|
name | string | Required | Organization name (max 255 chars) |
description | string | Optional | Description (max 1000 chars) |
{
"data": {
"uuid": "new-org-uuid",
"name": "My Organization",
"slug": "my-organization",
"description": "A workspace for my team",
"created_at": "2026-03-19T12:00:00+00:00"
}
}
Get Organization
Returns full organization details including roles, members, and your permissions. Requires membership.
Path Parameters
| Param | Description |
|---|---|
uuid | Organization UUID |
Update Organization
Request Body
| Field | Type | Required | Description |
|---|---|---|---|
name | string | Optional | New name |
description | string | Optional | New description |
Delete Organization
Permanently deletes an organization. Only the owner can perform this action.
Returns 204 No Content on success.
Members
List Members
{
"data": [
{
"user_uuid": "user-uuid-1",
"email": "john@example.com",
"name": "John",
"surname": "Doe",
"role": "admin",
"role_display_name": "Admin",
"permissions": ["manage_members", ...],
"joined_at": "2026-01-20T09:00:00+00:00"
}
]
}
Get Single Member
Returns the specified member's profile, role, and permissions within the organization.
Add Member
Request Body
| Field | Type | Required | Description |
|---|---|---|---|
email | string | Required | Email of a registered Kiges ID user |
role | string | Optional | Role name to assign (default: member) |
Returns 201 with the new member data. Returns 404 if user not found, 409 if already a member.
Update Member Role
Request Body
| Field | Type | Required | Description |
|---|---|---|---|
role | string | Required | New role name for the member |
Remove Member
Returns 204 No Content on success. The organization owner cannot be removed.
Roles
List Roles
{
"data": [
{
"id": 1,
"name": "owner",
"display_name": "Owner",
"permissions": ["manage_organization", "manage_members", ...],
"is_system": true,
"is_default": false,
"members_count": 1
}
]
}
Default System Roles
| Role | Permissions |
|---|---|
owner | All permissions |
admin | All except manage_organization |
member | view_members, invite_members |
viewer | view_members |
Available Permissions
| Permission | Description |
|---|---|
manage_organization | Update org name, description, settings |
manage_members | Add members, change roles |
manage_roles | Create, edit, delete custom roles |
invite_members | Send and manage invitations |
remove_members | Remove members from the organization |
view_members | View the member list |
view_audit_logs | Access the audit log |
manage_sso | Configure SAML SSO settings |
manage_scim | Configure SCIM provisioning |
manage_billing | Manage billing and subscriptions |
Get Role
Create Custom Role
Request Body
| Field | Type | Required | Description |
|---|---|---|---|
name | string | Required | Unique role identifier (will be slugified) |
display_name | string | Required | Human-readable role name |
permissions | string[] | Required | Array of permission strings |
{
"name": "project-manager",
"display_name": "Project Manager",
"permissions": ["manage_members", "invite_members", "view_members", "view_audit_logs"]
}
Update Role
Delete Role
Returns 204 No Content on success. Cannot delete system roles or roles with assigned members.
Invitations
List Invitations
{
"data": [
{
"uuid": "inv-uuid-1",
"email": "jane@example.com",
"role": "member",
"role_display_name": "Member",
"status": "pending",
"invited_by": "John Doe",
"expires_at": "2026-03-26T12:00:00+00:00",
"created_at": "2026-03-19T12:00:00+00:00"
}
]
}
Create Invitation
Sends an email invitation to join the organization. If the email belongs to a registered Kiges ID user, they'll receive a clickable link. The invitation expires after 7 days.
Request Body
| Field | Type | Required | Description |
|---|---|---|---|
email | string | Required | Email address to invite |
role | string | Optional | Role to assign (default: member) |
Cancel Invitation
Only pending invitations can be cancelled.
Permissions & Audit
Check Permissions
Check the authenticated user's permissions within an organization. This can inform your UI, but it is not a substitute for authorization checks on your own server. Kiges organization endpoints independently enforce scopes and role permissions.
Query Parameters
| Param | Type | Description |
|---|---|---|
permissions | string | Comma-separated list of permissions to check (e.g., manage_members,invite_members) |
// GET /api/v1/organizations/{uuid}/permissions?permissions=manage_members,manage_billing
{
"data": {
"is_member": true,
"role": "admin",
"permissions": ["manage_members", "manage_roles", "invite_members", ...],
"checked": {
"manage_members": true,
"manage_billing": false
}
}
}
Audit Logs
Retrieve the organization's audit log. Supports filtering and pagination.
Query Parameters
| Param | Type | Description |
|---|---|---|
event | string | Filter by event type (e.g., member.added) |
from | date | Start date (YYYY-MM-DD) |
to | date | End date (YYYY-MM-DD) |
per_page | integer | Items per page (max 100, default 25) |
page | integer | Page number |
Organization Notifications
Organization administrators can configure destinations and rules for organization notifications. Available destination types depend on what is enabled for the organization; discover them through the channel-types endpoint.
Destination types
Discover enabled types with GET /api/v1/notification-channel-types; includes web_push where enabled.
Routing rules
Filter by service, team, event wildcard, and minimum severity
Management API
OAuth-authenticated CRUD for destinations, rules, and delivery logs
manage_notifications organization permission.
Notification Destinations
Also available: GET /api/v1/notification-channel-types, which lists supported types and connection requirements. Types currently include Telegram, Slack, Discord, Google Chat, Microsoft Teams, webhook, email, and web_push; an organization may disable types.
Create a destination. The channel-types endpoint identifies fields for each type. Secrets and connection data are configuration fields; keep them server-side and out of logs.
Issue a new Telegram connection token. Treat the response as sensitive and send it only to the intended organization administrator.
Management routes also include GET, PUT, and DELETE /api/v1/organizations/{uuid}/notification-endpoints/{endpointUuid}; POST .../{endpointUuid}/test sends a test; POST .../{endpointUuid}/reconnect reconnects Telegram.
Notification Rules
Body: name, notification_endpoint_uuid, optional organization_team_id, saas_service_id, events array, minimum_severity.
Rules also support PUT /api/v1/organizations/{uuid}/notification-rules/{ruleId} and DELETE at the same path.
Notification Deliveries
Paginated delivery log. Filter with status and event; per_page accepts 1–100 (default 25). Test routing via POST /api/v1/organizations/{uuid}/notifications/test.
Integration Guide
Complete OAuth 2.0 Flow
Generate a fresh random state and PKCE verifier for every login attempt. Bind both to the initiating browser session, compare the returned state before exchanging the code, and consume both values once. The redirect URI in both requests must exactly match a URI registered for the client.
// Generate PKCE challenge
const randomBytes = (length) => crypto.getRandomValues(new Uint8Array(length));
const base64url = (bytes) => btoa(String.fromCharCode(...bytes))
.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/g, '');
const verifier = base64url(randomBytes(32));
const state = base64url(randomBytes(32));
const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier));
const challenge = base64url(new Uint8Array(digest));
// Keep these short-lived values only for the pending authorization transaction.
sessionStorage.setItem('kiges_oauth_pending', JSON.stringify({ state, verifier }));
const authUrl = new URL('https://id.kiges.cc/oauth/authorize');
authUrl.searchParams.set('client_id', '<PUBLIC_CLIENT_ID>');
authUrl.searchParams.set('redirect_uri', 'https://app.example/callback');
authUrl.searchParams.set('response_type', 'code');
authUrl.searchParams.set('scope', 'openid email');
authUrl.searchParams.set('state', state);
authUrl.searchParams.set('code_challenge', challenge);
authUrl.searchParams.set('code_challenge_method', 'S256');
window.location.href = authUrl.toString();
const returnedState = new URLSearchParams(location.search).get('state');
const code = new URLSearchParams(location.search).get('code');
const pending = JSON.parse(sessionStorage.getItem('kiges_oauth_pending') || 'null');
sessionStorage.removeItem('kiges_oauth_pending'); // consume once, including failed attempts
if (!pending || !returnedState || returnedState !== pending.state || !code) {
throw new Error('Invalid OAuth response');
}
const tokenResponse = await fetch('https://id.kiges.cc/api/oauth/token', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
grant_type: 'authorization_code', client_id: '<PUBLIC_CLIENT_ID>',
redirect_uri: 'https://app.example/callback', code,
code_verifier: pending.verifier,
}), // Public client: no client_secret
});
if (!tokenResponse.ok) throw new Error('Token exchange failed');
const tokens = await tokenResponse.json();
if (typeof tokens.access_token !== 'string') throw new Error('Missing access token');
// Keep the access token in memory only; prefer a BFF for longer-lived sessions.
const profileResponse = await fetch('https://id.kiges.cc/api/userinfo', {
headers: { Authorization: `Bearer ${tokens.access_token}` },
});
if (!profileResponse.ok) throw new Error('UserInfo request failed');
const profile = await profileResponse.json();
Route::get('/login/kiges', function (Request $request) {
$state = bin2hex(random_bytes(32));
$verifier = rtrim(strtr(base64_encode(random_bytes(32)), '+/', '-_'), '=');
$challenge = rtrim(strtr(base64_encode(hash('sha256', $verifier, true)), '+/', '-_'), '=');
$request->session()->put(['kiges_oauth_state' => $state, 'kiges_oauth_verifier' => $verifier]);
$query = http_build_query([
'client_id' => config('services.kiges.client_id'),
'redirect_uri' => config('services.kiges.redirect_uri'),
'response_type' => 'code', 'scope' => 'openid email',
'state' => $state, 'code_challenge' => $challenge,
'code_challenge_method' => 'S256',
], '', '&', PHP_QUERY_RFC3986);
return redirect(config('services.kiges.authorize_url') . '?' . $query);
});
// Store state and verifier in the server-side session when starting login.
// callback route; session storage must be server-side, not a client cookie store.
Route::get('/callback', function (Request $request) {
$expectedState = $request->session()->pull('kiges_oauth_state');
$verifier = $request->session()->pull('kiges_oauth_verifier');
abort_unless(is_string($expectedState) && is_string($request->query('state'))
&& hash_equals($expectedState, $request->query('state')), 403, 'Invalid state');
abort_unless(is_string($verifier) && is_string($request->query('code')), 400);
$response = Http::asForm()->post(config('services.kiges.token_url'), [
'grant_type' => 'authorization_code',
'client_id' => config('services.kiges.client_id'),
'client_secret' => config('services.kiges.client_secret'), // server-only confidential client
'redirect_uri' => config('services.kiges.redirect_uri'),
'code' => $request->query('code'),
'code_verifier' => $verifier,
]);
abort_unless($response->successful(), 401, 'Token exchange failed');
$tokens = $response->json();
abort_unless(is_string($tokens['access_token'] ?? null), 401);
// Keep tokens in a protected server-side session/token store; never return them to the page.
$request->session()->put('kiges_access_token', $tokens['access_token']);
if (is_string($tokens['refresh_token'] ?? null)) {
$request->session()->put('kiges_refresh_token', $tokens['refresh_token']);
}
return redirect('/dashboard');
});
const crypto = require('node:crypto');
app.get('/login/kiges', (req, res) => {
const state = crypto.randomBytes(32).toString('base64url');
const verifier = crypto.randomBytes(32).toString('base64url');
const challenge = crypto.createHash('sha256').update(verifier).digest('base64url');
req.session.kigesOauthState = state;
req.session.kigesOauthVerifier = verifier;
const url = new URL(process.env.KIGES_AUTHORIZE_URL);
url.search = new URLSearchParams({
client_id: process.env.KIGES_CLIENT_ID, redirect_uri: process.env.KIGES_REDIRECT_URI,
response_type: 'code', scope: 'openid email', state,
code_challenge: challenge, code_challenge_method: 'S256',
});
res.redirect(url.toString());
});
// Use a production server-side session store with secure, HttpOnly, SameSite cookies.
app.get('/callback', async (req, res) => {
const { code, state } = req.query;
const expectedState = req.session.kigesOauthState;
const verifier = req.session.kigesOauthVerifier;
delete req.session.kigesOauthState;
delete req.session.kigesOauthVerifier; // single use
if (typeof state !== 'string' || typeof expectedState !== 'string' || state !== expectedState ||
typeof code !== 'string' || typeof verifier !== 'string') return res.sendStatus(400);
const tokenRes = await fetch(process.env.KIGES_TOKEN_URL, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
grant_type: 'authorization_code', client_id: process.env.KIGES_CLIENT_ID,
client_secret: process.env.KIGES_CLIENT_SECRET, // server secret; omit for public clients
redirect_uri: process.env.KIGES_REDIRECT_URI, code, code_verifier: verifier,
}),
});
if (!tokenRes.ok) return res.sendStatus(401);
const tokens = await tokenRes.json();
if (typeof tokens.access_token !== 'string') return res.sendStatus(401);
// Store only in the protected server-side session/token store; never render tokens to the browser.
req.session.kigesAccessToken = tokens.access_token;
if (typeof tokens.refresh_token === 'string') req.session.kigesRefreshToken = tokens.refresh_token;
res.redirect('/dashboard');
});
For a public browser client, omit client_secret and send code_verifier from the same pending transaction. Do not persist access or refresh tokens in localStorage. The Laravel and Express examples above are confidential server clients and assume a server-side session store and secrets supplied through protected server configuration.
Organization Switching in Your SaaS
After authentication, the user may belong to multiple organizations. Here's how to implement organization switching in your SaaS.
function OrganizationSwitcher({ organizations, currentOrg, onSwitch }) {
return (
<select
value={currentOrg?.uuid || ''}
onChange={(e) => onSwitch(e.target.value)}
>
{organizations.map(org => (
<option key={org.uuid} value={org.uuid}>
{org.name} ({org.role})
</option>
))}
</select>
);
}
// When organization changes, re-fetch data scoped to that org
async function switchOrganization(orgUuid) {
// Store selected org in session/state
setCurrentOrg(orgUuid);
// Fetch org details + members from Kiges ID API
const orgRes = await fetch(`/api/kiges/organizations/${orgUuid}`);
const { data } = await orgRes.json();
// Check the user's permissions to show/hide UI elements
const canManage = (data.your_permissions || []).includes('manage_members');
setCanManageMembers(canManage);
}
// In your SaaS backend, proxy requests to Kiges ID API
Route::middleware('auth')->prefix('api/kiges')->group(function () {
Route::get('/organizations', function (Request $request) {
return Http::withToken($request->session()->get('kiges_access_token'))
->get('https://id.kiges.cc/api/v1/organizations')
->json();
});
Route::get('/organizations/{uuid}', function (Request $request, $uuid) {
return Http::withToken($request->session()->get('kiges_access_token'))
->get("https://id.kiges.cc/api/v1/organizations/{$uuid}")
->json();
});
Route::get('/organizations/{uuid}/members', function (Request $request, $uuid) {
return Http::withToken($request->session()->get('kiges_access_token'))
->get("https://id.kiges.cc/api/v1/organizations/{$uuid}/members")
->json();
});
Route::get('/organizations/{uuid}/permissions', function (Request $request, $uuid) {
$perms = $request->query('permissions', '');
return Http::withToken($request->session()->get('kiges_access_token'))
->get("https://id.kiges.cc/api/v1/organizations/{$uuid}/permissions", [
'permissions' => $perms,
])
->json();
});
});
Webhooks
Overview
Kiges ID sends real-time HTTP POST notifications (webhooks) to your application whenever important events occur. Webhooks are delivered asynchronously with automatic retries on failure.
Automatic Setup
Configure your webhook URL when creating an OAuth client. A signing secret is auto-generated.
Signed Payloads
Every delivery is signed with HMAC-SHA256 so you can verify authenticity.
Automatic Retries
The sender is configured for five attempts total. After the first four failed attempts, automatic retry delays are 30 seconds, 2 minutes, 10 minutes, and 30 minutes.
Delivery Logs
Full delivery history with status, response, and manual retry via API.
Common event examples
| Event | Triggered When |
|---|---|
user.updated | A user updates their profile (name, email, etc.) |
organization.created | A new organization is created |
organization.updated | Organization name or description changes |
organization.deleted | An organization is deleted |
member.added | A user joins an organization (direct add, invitation, or invite link) |
member.updated | A member's role is changed |
member.removed | A member is removed from an organization |
role.created | A new custom role is created |
role.updated | A role's permissions or display name changes |
role.deleted | A custom role is deleted |
invitation.created | An invitation is sent |
invitation.accepted | An invitation is accepted |
invitation.declined | An invitation is declined |
invitation.cancelled | An invitation is cancelled by an admin |
GET /api/v1/webhook-events: user.created, user.updated, user.deleted, user.banned, user.unbanned, session.created, session.ended, session.revoked, waitlist.joined, waitlist.approved, organization.created, organization.updated, organization.deleted, member.added, member.updated, member.removed, role.created, role.updated, role.deleted, invitation.created, invitation.accepted, invitation.declined, and invitation.cancelled. A configured test delivery also emits application.test, which is not included in that discovery response. Event delivery depends on the client webhook configuration and granted organization scopes.
Delivery Headers
Each webhook request includes these custom headers:
| Header | Description |
|---|---|
X-Kiges-Event | The event type (e.g., member.added) |
X-Kiges-Delivery | Unique delivery UUID (for idempotency) |
X-Kiges-Signature-256 | HMAC-SHA256 signature: sha256=<hex> |
X-Kiges-Timestamp | Unix timestamp of the delivery attempt |
User-Agent | KigesID-Webhook/1.0 |
Content-Type | application/json |
Signature Verification
Each delivery is signed using the application's webhook secret. Verify the exact raw request body before parsing JSON. The signature is sha256=<hex> for HMAC-SHA256 over timestamp + "." + raw_body. Reject malformed or stale timestamps and signatures. Persist each X-Kiges-Delivery ID with a unique constraint before processing so retries cannot apply an event twice.
// processDeliveryOnce must persist delivery IDs and commit successful work atomically.
Route::post('/webhooks/kiges', function (Request $request) {
$secret = config('services.kiges.webhook_secret');
$timestamp = (string) $request->header('X-Kiges-Timestamp', '');
$signature = (string) $request->header('X-Kiges-Signature-256', '');
$deliveryId = (string) $request->header('X-Kiges-Delivery', '');
if (!$secret || !preg_match('/^\d{1,12}$/', $timestamp)
|| !preg_match('/^sha256=[a-f0-9]{64}$/i', $signature) || $deliveryId === '') {
return response('Malformed webhook headers', 400);
}
if (abs(time() - (int) $timestamp) > 300) return response('Stale webhook', 403);
$body = $request->getContent();
$expected = 'sha256=' . hash_hmac('sha256', $timestamp . '.' . $body, $secret);
if (!hash_equals($expected, $signature)) return response('Invalid signature', 403);
try { $payload = json_decode($body, true, 512, JSON_THROW_ON_ERROR); }
catch (\JsonException $e) { return response('Invalid JSON', 400); }
if (!processDeliveryOnce($deliveryId, fn () => processKigesEvent($request->header('X-Kiges-Event'), $payload))) {
return response('Already processed', 200);
}
return response('OK', 200);
});
const crypto = require('node:crypto');
app.post('/webhooks/kiges', express.raw({ type: 'application/json' }), async (req, res) => {
const secret = process.env.KIGES_WEBHOOK_SECRET;
const timestamp = req.headers['x-kiges-timestamp'];
const signature = req.headers['x-kiges-signature-256'];
const deliveryId = req.headers['x-kiges-delivery'];
if (!secret || typeof timestamp !== 'string' || !/^\d{1,12}$/.test(timestamp) ||
typeof signature !== 'string' || !/^sha256=[a-f0-9]{64}$/i.test(signature) ||
typeof deliveryId !== 'string') return res.sendStatus(400);
if (Math.abs(Date.now() / 1000 - Number(timestamp)) > 300) return res.sendStatus(403);
const digest = crypto.createHmac('sha256', secret)
.update(Buffer.concat([Buffer.from(timestamp + '.'), req.body])).digest();
const supplied = Buffer.from(signature.slice(7), 'hex');
if (supplied.length !== digest.length || !crypto.timingSafeEqual(digest, supplied)) return res.sendStatus(403);
let payload;
try { payload = JSON.parse(req.body.toString('utf8')); }
catch { return res.sendStatus(400); }
await processDeliveryOnce(deliveryId, () => processKigesEvent(req.headers['x-kiges-event'], payload));
res.sendStatus(200);
});
import hashlib
import hmac
import json
import os
import re
import time
from flask import Flask, request, abort
app = Flask(__name__)
WEBHOOK_SECRET = os.environ['KIGES_WEBHOOK_SECRET']
@app.route('/webhooks/kiges', methods=['POST'])
def handle_webhook():
timestamp = request.headers.get('X-Kiges-Timestamp', '')
signature = request.headers.get('X-Kiges-Signature-256', '')
delivery_id = request.headers.get('X-Kiges-Delivery', '')
if not re.fullmatch(r'\d{1,12}', timestamp) or not re.fullmatch(r'sha256=[a-fA-F0-9]{64}', signature) or not delivery_id:
abort(400, 'Malformed webhook headers')
if abs(time.time() - int(timestamp)) > 300:
abort(403, 'Stale webhook')
body = request.get_data() # verify raw bytes before parsing JSON
expected = 'sha256=' + hmac.new(WEBHOOK_SECRET.encode(), timestamp.encode() + b'.' + body, hashlib.sha256).hexdigest()
if not hmac.compare_digest(expected, signature):
abort(403, 'Invalid signature')
try:
payload = json.loads(body)
except (ValueError, UnicodeDecodeError):
abort(400, 'Invalid JSON')
process_delivery_once(delivery_id, lambda: process_kiges_event(request.headers.get('X-Kiges-Event'), payload))
return 'OK', 200
The 300-second freshness window is a client-side example (also the Node SDK default), not a server-enforced guarantee. Implement processDeliveryOnce as an idempotent inbox/transaction: mark a delivery complete only after processing succeeds, and leave failures eligible for retry. Webhook event bodies can include personal data such as member email and name; apply your data retention and access controls accordingly.
Payload Examples
member.added
{
"event": "member.added",
"timestamp": "2026-03-19T14:30:00+00:00",
"organization": {
"uuid": "550e8400-e29b-41d4-a716-446655440000",
"name": "Example Organization",
"slug": "acme-corp"
},
"member": {
"user_uuid": "user-uuid-123",
"email": "john@example.com",
"name": "John",
"surname": "Doe",
"role": "member",
"permissions": ["view_members", "invite_members"]
},
"data": {
"role": "member",
"source": "invitation"
}
}
member.updated (role change)
{
"event": "member.updated",
"timestamp": "2026-03-19T14:35:00+00:00",
"organization": {
"uuid": "550e8400-...",
"name": "Example Organization",
"slug": "acme-corp"
},
"member": {
"user_uuid": "user-uuid-123",
"email": "john@example.com",
"name": "John",
"surname": "Doe",
"role": "admin",
"permissions": ["manage_members", "manage_roles", ...]
},
"data": {
"old_role": "member",
"new_role": "admin"
}
}
organization.updated
{
"event": "organization.updated",
"timestamp": "2026-03-19T15:00:00+00:00",
"organization": {
"uuid": "550e8400-...",
"name": "Example Organization",
"slug": "acme-corp",
"description": "Updated description",
"is_active": true
},
"data": {
"name": "Example Organization"
}
}
role.created
{
"event": "role.created",
"timestamp": "2026-03-19T15:10:00+00:00",
"organization": {
"uuid": "550e8400-...",
"name": "Example Organization",
"slug": "acme-corp"
},
"role": {
"id": 5,
"name": "project-manager",
"display_name": "Project Manager",
"permissions": ["manage_members", "invite_members", "view_members"]
}
}
invitation.accepted
{
"event": "invitation.accepted",
"timestamp": "2026-03-19T16:00:00+00:00",
"organization": {
"uuid": "550e8400-...",
"name": "Example Organization",
"slug": "acme-corp"
},
"invitation": {
"uuid": "inv-uuid-123",
"email": "jane@example.com",
"role": "member"
}
}
List Webhook Deliveries
Query Parameters
| Param | Type | Description |
|---|---|---|
event | string | Filter by event type (e.g., member.added) |
status | string | Filter by status: pending, success, or failed |
per_page | integer | Items per page (max 100, default 25) |
Get Webhook Delivery
Returns full details of a webhook delivery, including the payload, response body, and error information.
{
"data": {
"uuid": "del-uuid-123",
"event": "member.added",
"url": "https://app.example/webhooks/kiges",
"payload": { ... },
"status": "success",
"status_code": 200,
"response_body": "OK",
"error_message": null,
"attempt": 1,
"max_attempts": 5,
"next_retry_at": null,
"completed_at": "2026-03-19T14:30:01+00:00",
"created_at": "2026-03-19T14:30:00+00:00"
}
}
Retry Delivery
Manually retry an unsuccessful webhook delivery. A successful delivery cannot be retried. This resets the attempt counter and immediately queues a new attempt.
{
"message": "Webhook delivery queued for retry",
"data": {
"uuid": "del-uuid-123",
"status": "pending"
}
}
Full Integration Examples
Python / Flask
import requests
KIGES_API = 'https://id.kiges.cc/api'
def get_user_with_orgs(access_token):
"""Fetch user profile and organizations in one call."""
r = requests.get(f'{KIGES_API}/v1/me', headers={
'Authorization': f'Bearer {access_token}',
'Accept': 'application/json',
})
r.raise_for_status()
return r.json()['data']
def get_org_members(access_token, org_uuid):
"""Fetch all members of an organization."""
r = requests.get(f'{KIGES_API}/v1/organizations/{org_uuid}/members', headers={
'Authorization': f'Bearer {access_token}',
'Accept': 'application/json',
})
r.raise_for_status()
return r.json()['data']
def check_user_permissions(access_token, org_uuid, permissions):
"""Check if the user has specific permissions in an organization."""
r = requests.get(
f'{KIGES_API}/v1/organizations/{org_uuid}/permissions',
params={'permissions': ','.join(permissions)},
headers={
'Authorization': f'Bearer {access_token}',
'Accept': 'application/json',
}
)
r.raise_for_status()
return r.json()['data']['checked']
# Usage
user = get_user_with_orgs(token)
for org in user['organizations']:
print(f"Org: {org['name']}, Role: {org['role']}")
perms = check_user_permissions(token, org['uuid'], ['manage_members', 'manage_billing'])
print(f" Can manage members: {perms['manage_members']}")
print(f" Can manage billing: {perms['manage_billing']}")
cURL Examples
# Get user profile + organizations
curl -H "Authorization: Bearer YOUR_TOKEN" \
https://id.kiges.cc/api/v1/me
# List all organizations
curl -H "Authorization: Bearer YOUR_TOKEN" \
https://id.kiges.cc/api/v1/organizations
# Get organization details
curl -H "Authorization: Bearer YOUR_TOKEN" \
https://id.kiges.cc/api/v1/organizations/ORG_UUID
# List members
curl -H "Authorization: Bearer YOUR_TOKEN" \
https://id.kiges.cc/api/v1/organizations/ORG_UUID/members
# Check specific permissions
curl -H "Authorization: Bearer YOUR_TOKEN" \
"https://id.kiges.cc/api/v1/organizations/ORG_UUID/permissions?permissions=manage_members,manage_billing"
# Invite a new member
curl -X POST \
-H "Authorization: Bearer YOUR_TOKEN" \
-H "Content-Type: application/json" \
-d '{"email":"jane@example.com","role":"member"}' \
https://id.kiges.cc/api/v1/organizations/ORG_UUID/invitations
# Create a custom role
curl -X POST \
-H "Authorization: Bearer YOUR_TOKEN" \
-H "Content-Type: application/json" \
-d '{"name":"editor","display_name":"Editor","permissions":["view_members","invite_members"]}' \
https://id.kiges.cc/api/v1/organizations/ORG_UUID/roles
Security Best Practices
- Use HTTPS and register the exact redirect URI for each client.
- Use Authorization Code with PKCE S256 and validate one-time, session-bound state on every callback.
- Keep confidential client secrets and access/refresh tokens in protected server-side storage; never ship client secrets or store tokens in browser
localStorage. - Request only the scopes needed. Treat organization email, member data, audit logs, and webhook payloads as sensitive personal data.
- Use the permission check to shape the interface, but rely on server-side authorization for actions. Kiges organization APIs enforce role permissions independently.
- Verify webhook signatures against the raw body, check timestamp freshness, and process delivery IDs idempotently.