Перейти до основного вмісту

Динамічна реєстрація клієнтів

Цей посібник пояснює динамічну реєстрацію клієнтів (DCR): програмне забезпечення самостійно реєструється як OAuth 2.0-клієнт Casdoor за допомогою одного HTTP-запиту, і ніхто не створює додаток в адміністративній консолі. DCR підходить для інструментів, які ви поширюєте кінцевим користувачам, таких як MCP-клієнти, CLI та настільні додатки, які отримують свої облікові дані клієнта при першому запуску. Casdoor реалізує RFC 7591 та RFC 7592.


Результати навчання​

  • Дозволити DCR для організації.
  • Знайти кінцеву точку реєстрації та зареєструвати клієнта.
  • Читати, оновлювати та видаляти реєстрацію.
  • Розуміти, що може робити зареєстрований клієнт.
  • Приймати клієнтів, які ідентифікують себе за допомогою URL документа метаданих.

Що вам потрібно​

  • Глобальний доступ адміністратора до адміністративної консолі Casdoor
  • Клієнт, який може надсилати HTTP-запити

Дозволити DCR для організації​

DCR вимкнено за замовчуванням для кожної організації, включаючи built-in. Ендпоінт реєстрації не потребує автентифікації, тому Casdoor відкриває його лише після того, як ви увімкнете цю функцію.

  1. У адміністративній консолі Casdoor відкрийте сторінку редагування організації.
  2. Увімкніть Enable dynamic client registration.
  3. Збережіть організацію.

Лише глобальний адміністратор може змінити цей перемикач. Для адміністратора організації перемикач вимкнено, а Casdoor ігнорує зміни, надіслані через API.

Перемикач встановлює поле dcrPolicy організації:

dcrPolicyBehavior
disabled, or emptyCasdoor rejects registration requests
openAnyone 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 is https://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, які потрібні клієнту для керування своєю реєстрацією.

Параметри запиту​

ParameterRequiredDescription
redirect_urisYesArray of callback URLs that Casdoor may redirect to after sign-in
client_nameNoDisplay name of the client. Casdoor generates a name if you omit it
grant_typesNoGrant 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_methodNoHow the client authenticates at the token endpoint: none, client_secret_post, client_secret_basic, or private_key_jwt
jwks_uriWith private_key_jwtHTTPS URL of the key set whose keys sign the client_assertion of the client (RFC 7523)
application_typeNoweb for server-side clients, or native for desktop and mobile clients
logo_uriNoURL of the logo of the client
client_uriNoURL of the home page of the client
policy_uriNoURL of the privacy policy of the client
tos_uriNoURL of the terms of service of the client. Casdoor sets it as the Terms of Use of the application
scopeNoSpace-separated list of the scopes that the client requests

Помилки​

У разі невдачі Casdoor повертає помилку відповідно до RFC 7591, з кодом error та читабельним описом error_description:

ErrorCause
invalid_redirect_uriredirect_uris is missing, or an entry uses the javascript:, data:, or vbscript: scheme
invalid_client_metadataDCR вимкнено для організації, організація не існує або параметр має неправильний формат. logo_uri, client_uri, policy_uri та tos_uri мають бути абсолютними URL-адресами http або https

Керування реєстрацією​

Клієнт читає, оновлює та видаляє власну реєстрацію за адресою /api/oauth/register/<client-id>. Кожен запит надсилає registration_access_token з відповіді на реєстрацію в заголовку Authorization: Bearer <registration-access-token>:

RequestDescription
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.

Щоб користувачі могли одразу входити в систему через клієнт, для додатка увімкнено вхід за паролем, і він успадковує такі налаштування від додатка за замовчуванням цієї організації:

SettingInherited
Providers and sign-in methodsYes, so that at least one sign-in method works
BrandingThe theme, the footer HTML, and the form CSS. The logo too, unless the request contains logo_uri
Sign-in itemsThe layout of the sign-in form
Session and WebAuthn settingsEnableSigninSession and EnableWebAuthn
Token lifetimesToken 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_method is empty or none, for a public client with PKCE, or private_key_jwt with an HTTPS jwks_uri, for a client that signs a client_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.

Див. також​