Динамічна реєстрація клієнтів
Цей посібник пояснює динамічну реєстрацію клієнтів (DCR): програмне забезпечення самостійно реєструється як OAuth 2.0-клієнт Casdoor за допомогою одного HTTP-запиту, і ніхто не створює додаток в адміністративній консолі. DCR підходить для інструментів, які ви поширюєте кінцевим користувачам, таких як MCP-клієнти, CLI та настільні додатки, які отримують свої облікові дані клієнта при першому запуску. Casdoor реалізує RFC 7591 та RFC 7592.
Результати навчання
- Дозволити DCR для організації.
- Знайти кінцеву точку реєстрації та зареєструвати клієнта.
- Читати, оновлювати та видаляти реєстрацію.
- Розуміти, що може робити зареєстрований клієнт.
- Приймати клієнтів, які ідентифікують себе за допомогою URL документа метаданих.
Що вам потрібно
- Глобальний доступ адміністратора до адміністративної консолі Casdoor
- Клієнт, який може надсилати HTTP-запити
Дозволити DCR для організації
DCR вимкнено за замовчуванням для кожної організації, включаючи built-in. Ендпоінт реєстрації не потребує автентифікації, тому Casdoor відкриває його лише після того, як ви увімкнете цю функцію.
- У адміністративній консолі Casdoor відкрийте сторінку редагування організації.
- Увімкніть Enable dynamic client registration.
- Збережіть організацію.
Лише глобальний адміністратор може змінити цей перемикач. Для адміністратора організації перемикач вимкнено, а Casdoor ігнорує зміни, надіслані через API.
Перемикач встановлює поле dcrPolicy організації:
dcrPolicy | Behavior |
|---|---|
disabled, or empty | Casdoor rejects registration requests |
open | Anyone can register an application in the organization, without authentication |
Увімкніть DCR лише для організацій, які цього потребують. Багато конфігурацій працюють із додатками, створеними адміністратором вручну, а вимкнення DCR усуває спосіб зловживання вашим екземпляром Casdoor.
Знайдіть ендпоінт реєстрації
Ендпоінт реєстрації — це /api/oauth/register. Він приймає необов’язковий параметр запиту organization, що вказує на організацію, у якій Casdoor створює клієнта. За замовчуванням використовується built-in.
Документ виявлення (discovery document) публікує кінцеву точку, коли для організації, у якій реєструються клієнти, увімкнено Enable dynamic client registration, і не вказує registration_endpoint у протилежному випадку, щоб клієнти запитували ID клієнта замість того, щоб зазнавати помилки при реєстрації. Запитайте його:
curl https://your-casdoor.com/.well-known/openid-configuration
Прочитайте значення registration_endpoint:
{
"issuer": "https://your-casdoor.com",
"authorization_endpoint": "https://your-casdoor.com/login/oauth/authorize",
"token_endpoint": "https://your-casdoor.com/api/login/oauth/access_token",
"registration_endpoint": "https://your-casdoor.com/api/oauth/register",
...
}
Global discovery document has no organization parameter, so clients register in built-in. Two other discovery documents return https://your-casdoor.com/api/oauth/register?organization=<organization>, so that a client registers in that organization:
- The discovery document of an application,
/.well-known/<application>/openid-configuration, with the organization of the application. - The discovery document of an organization that has Use organization issuer turned on,
/.well-known/oauth-authorization-server/orgs/<organization>or/.well-known/openid-configuration/orgs/<organization>. Its issuer ishttps://your-casdoor.com/orgs/<organization>. The MCP gateway names this issuer as the authorization server of the MCP servers of the organization.
Зареєструвати клієнта
Надішліть запит POST з метаданими клієнта у форматі JSON на ендпоінт реєстрації:
curl -X POST https://your-casdoor.com/api/oauth/register \
-H "Content-Type: application/json" \
-d '{
"client_name": "Claude Desktop",
"redirect_uris": ["http://localhost:3000/callback"],
"grant_types": ["authorization_code", "refresh_token"],
"token_endpoint_auth_method": "none",
"application_type": "native"
}'
Відповідь містить облікові дані нового клієнта:
{
"client_id": "a1b2c3d4e5f6",
"client_secret": "secret_xyz789...",
"client_id_issued_at": 1737799294,
"client_secret_expires_at": 0,
"redirect_uris": ["http://localhost:3000/callback"],
"grant_types": ["authorization_code", "refresh_token"],
"token_endpoint_auth_method": "none",
"application_type": "native"
}
Безпечно зберігайте client_id та client_secret. Клієнт використовує їх в усіх подальших процесах OAuth 2.0. Відповідь також містить registration_client_uri та registration_access_token, які потрібні клієнту для керування своєю реєстрацією.
Параметри запиту
| Parameter | Required | Description |
|---|---|---|
redirect_uris | Yes | Array of callback URLs that Casdoor may redirect to after sign-in |
client_name | No | Display name of the client. Casdoor generates a name if you omit it |
grant_types | No | Grant types that the client uses: authorization_code, refresh_token, urn:ietf:params:oauth:grant-type:device_code, or urn:ietf:params:oauth:grant-type:jwt-bearer, which a registered client can use only to redeem an ID-JAG. Casdoor drops any other value without an error. The default is ["authorization_code"] |
token_endpoint_auth_method | No | How the client authenticates at the token endpoint: none, client_secret_post, client_secret_basic, or private_key_jwt |
jwks_uri | With private_key_jwt | HTTPS URL of the key set whose keys sign the client_assertion of the client (RFC 7523) |
application_type | No | web for server-side clients, or native for desktop and mobile clients |
logo_uri | No | URL of the logo of the client |
client_uri | No | URL of the home page of the client |
policy_uri | No | URL of the privacy policy of the client |
tos_uri | No | URL of the terms of service of the client. Casdoor sets it as the Terms of Use of the application |
scope | No | Space-separated list of the scopes that the client requests |
Помилки
У разі невдачі Casdoor повертає помилку відповідно до RFC 7591, з кодом error та читабельним описом error_description:
| Error | Cause |
|---|---|
invalid_redirect_uri | redirect_uris is missing, or an entry uses the javascript:, data:, or vbscript: scheme |
invalid_client_metadata | DCR вимкнено для організації, організація не існує або параметр має неправильний формат. logo_uri, client_uri, policy_uri та tos_uri мають бути абсолютними URL-адресами http або https |
Керування реєстрацією
Клієнт читає, оновлює та видаляє власну реєстрацію за адресою /api/oauth/register/<client-id>. Кожен запит надсилає registration_access_token з відповіді на реєстрацію в заголовку Authorization: Bearer <registration-access-token>:
| Request | Description |
|---|---|
GET /api/oauth/register/<client-id> | Returns the current metadata of the client |
PUT /api/oauth/register/<client-id> | Updates the metadata |
DELETE /api/oauth/register/<client-id> | Deletes the client |
Що таке зареєстрований клієнт і що він може робити
Casdoor створює додаток для кожного зареєстрованого клієнта. Додаток має такі властивості:
- Він належить до організації ендпоінту реєстрації та з’являється у списку додатків із тегом
dcr, категорієюAgentта типомMCP. - Його секрет клієнта не має терміну дії. Адміністратор може видалити додаток у будь-який час.
- Він працює під обмеженою роллю
app-dcr. Використовуючи свої облікові дані клієнта, він може викликати лише ендпоінти процесу входу:/api/login/oauth/*,/api/get-oauth-token,/api/userinfoта/api/get-application. Він не може викликати API керування. - Токен, отриманий користувачем через клієнт, і сесія, яка з ним пов’язана, можуть викликати лише
/api/userinfo,/api/user,/api/mcp,/api/login/oauthта/api/server/*. Casdoor відхиляє інші запити з таким токеном. Якщо браузер надсилає лише cookie сесії, залишений таким запитом, Casdoor завершує цю сесію та обробляє запит як анонімний. Будь-хто може зареєструвати клієнт і попросити користувачів авторизувати його, тому клієнт не може використовувати їхні токени для керування Casdoor.
Щоб користувачі могли одразу входити в систему через клієнт, для додатка увімкнено вхід за паролем, і він успадковує такі налаштування від додатка за замовчуванням цієї організації:
| Setting | Inherited |
|---|---|
| Providers and sign-in methods | Yes, so that at least one sign-in method works |
| Branding | The theme, the footer HTML, and the form CSS. The logo too, unless the request contains logo_uri |
| Sign-in items | The layout of the sign-in form |
| Session and WebAuthn settings | EnableSigninSession and EnableWebAuthn |
| Token lifetimes | Token expire, Refresh token expire, and Cookie expire, when they are above 0. Otherwise, the access token lasts 168 hours, and the refresh token and the cookie last 720 hours |
Формат токенів та поля токенів не беруться з додатка за замовчуванням. Вони беруться з Default token format та Default token fields організації. Див. Організації.
Приймати клієнтів, ідентифікованих за URL-адресою документа метаданих
Клієнт може пропустити реєстрацію та використовувати як свій client_id HTTPS URL-адресу, що вказує на документ метаданих ID клієнта, як це роблять клієнти MCP. Цей документ є файлом JSON з такими самими метаданими, як у запиті на реєстрацію. Casdoor дотримується специфікації draft-ietf-oauth-client-id-metadata-document.
Яка організація
One and the same client, such as ChatGPT, Claude, or VS Code, has one client ID URL for all the Casdoor instances and organizations that it connects to. Casdoor therefore keeps one application per URL, shared by all organizations, and serves it as an application of the organization that the user signs in to:
- Організація визначається з параметра
organizationзапиту авторизації. У документі виявлення додатка та організації з увімкненою опцією Use organization issuer організація вказується у шляхіauthorization_endpoint, наприклад,https://your-casdoor.com/orgs/acme/login/oauth/authorize, що перенаправляє на сторінку входу зorganization=acme. Без цієї опції використовується організаціяbuilt-in. - Casdoor accepts the URL only when Enable dynamic client registration is on for that organization. Otherwise, the authorization request fails with "client ID metadata documents are not accepted, enable dynamic client registration of the organization:
first". The discovery document shows the setting in client_id_metadata_document_supported. - The user signs in on the sign-in page of the organization, and the tokens carry the issuer of the user's organization, also after a refresh.
The application belongs to built-in, has Is shared turned on, the URL as its client ID, a name that starts with cimd_, and the tag cimd. An application that an earlier version of Casdoor added to another organization becomes such a shared application on its next fetch.
Документ
URL-адреса client_id повинна використовувати протокол https, мати шлях, відмінний від /, і не містити інформації про користувача, фрагмента #, а також сегментів . або ...
За адресою /login/oauth/authorize Casdoor отримує документ за допомогою запиту GET. Запит має тайм-аут 5 секунд, не переходить за перенаправленнями та виконується лише до публічних інтернет-адрес. Документ повинен відповідати таким правилам:
- Відповідь має код HTTP 200, є валідним JSON і має розмір не більше 16 КБ.
client_idдорівнює URL-адресі, іclient_secretвідсутній.token_endpoint_auth_methodis empty ornone, for a public client with PKCE, orprivate_key_jwtwith an HTTPSjwks_uri, for a client that signs aclient_assertion, such as ChatGPT.redirect_urisмістить принаймні одну повну URL-адресу.- Інші метадані відповідають правилам запиту на реєстрацію.
grant_typesза замовчуванням дорівнює["authorization_code"].
The application uses the same defaults and inherited settings as a registered client, taken from the default application of built-in. The display name is <client_name> (<host>), or the host. The home page is client_uri when it is on the same host, and https://<host> otherwise.
On later authorization requests, Casdoor fetches the document again at most once an hour and updates the name, the home page, the redirect URLs, the grant types, the terms of use, the logo, and the key set. If an application without the tag cimd already has the URL as its client ID, Casdoor uses that application as it is.
Приклад: клієнт MCP
Наступний JavaScript код виявляє кінцеву точку реєстрації та реєструє клієнта:
// Discover the registration endpoint
const discovery = await fetch('https://your-casdoor.com/.well-known/openid-configuration')
.then(r => r.json());
// Register the application
const registration = await fetch(discovery.registration_endpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
client_name: 'MCP Client',
redirect_uris: ['http://127.0.0.1:6437/callback'],
grant_types: ['authorization_code', 'refresh_token'],
token_endpoint_auth_method: 'none',
application_type: 'native'
})
}).then(r => r.json());
// Store credentials for OAuth flows
const { client_id, client_secret } = registration;
Маючи облікові дані, клієнт виконує потік коду авторизації: користувач входить у браузері, Casdoor перенаправляє на URL callback із кодом авторизації, а клієнт обмінює код на токени. Див. OAuth 2.0.