diff --git a/i18n/de/docusaurus-plugin-content-docs/current/integrate-logto/protected-app.mdx b/i18n/de/docusaurus-plugin-content-docs/current/integrate-logto/protected-app.mdx index 78ea4a1d767..fd6ff2035ef 100644 --- a/i18n/de/docusaurus-plugin-content-docs/current/integrate-logto/protected-app.mdx +++ b/i18n/de/docusaurus-plugin-content-docs/current/integrate-logto/protected-app.mdx @@ -1,45 +1,45 @@ --- -description: Füge deinen Web-Apps mit Logto's innovativer Protected App, unterstützt von Cloudflare, einfach eine No-Code-Authentifizierung hinzu. Unterstützt HTTP Basic Authentication und JWT-Validierung. +description: Füge deinen Webanwendungen ganz einfach eine No-Code-Authentifizierung mit der innovativen Protected App von Logto hinzu, unterstützt durch Cloudflare. Unterstützt HTTP Basic Authentifizierung und JWT-Validierung. sidebar_label: Protected App sidebar_position: 2 --- -# Protected App — Nicht-SDK-Authentifizierungsintegration +# Protected App — Nicht-SDK Authentifizierungsintegration -Die Protected App wurde entwickelt, um die Komplexität von [SDK-Integrationen](/quick-starts) zu beseitigen, indem die [Authentifizierung](https://auth.wiki/authentication) von deiner Anwendung getrennt wird. Wir übernehmen die Authentifizierung, sodass du dich auf deine Kernfunktionalität konzentrieren kannst. Sobald ein Benutzer authentifiziert ist, liefert die Protected App die Inhalte von deinem Server aus. +Die Protected App wurde entwickelt, um die Komplexität von [SDK-Integrationen](/quick-starts) zu beseitigen, indem die [Authentifizierung (Authentication)](https://auth.wiki/authentication) von deiner Anwendung getrennt wird. Wir übernehmen die Authentifizierung, sodass du dich auf deine Kernfunktionalität konzentrieren kannst. Sobald ein Benutzer authentifiziert ist, liefert die Protected App die Inhalte von deinem Server aus. -## Wie die Protected App funktioniert \{#how-protected-app-works} +## Wie Protected App funktioniert \{#how-protected-app-works} -Die von Cloudflare unterstützte Protected App arbeitet global auf Edge-Netzwerken und gewährleistet niedrige Latenz und hohe Verfügbarkeit für deine Anwendung. +Die Protected App, unterstützt durch Cloudflare, arbeitet weltweit auf Edge-Netzwerken und sorgt so für geringe Latenz und hohe Verfügbarkeit deiner Anwendung. -Die Protected App verwaltet den Sitzungsstatus und die Benutzerinformationen. Wenn ein Benutzer nicht authentifiziert ist, leitet die Protected App ihn zur Anmeldeseite weiter. Sobald er authentifiziert ist, versieht die Protected App die Anfrage des Benutzers mit Authentifizierungs- und Benutzerinformationen und leitet sie dann an den Ursprungsserver weiter. +Die Protected App verwaltet den Sitzungsstatus und die Benutzerinformationen. Ist ein Benutzer nicht authentifiziert, leitet die Protected App ihn zur Anmeldeseite weiter. Nach erfolgreicher Authentifizierung versieht die Protected App die Anfrage des Benutzers mit Authentifizierungs- und Benutzerinformationen und leitet sie dann an den Ursprungsserver weiter. Dieser Prozess wird im folgenden Flussdiagramm visualisiert: ```mermaid graph LR - A("Client
(Browser)") -->|Request| B(Logto
Protected App) - B --> Condition{{Route
matches?}} - Condition -->|Yes| Matched{{Is authenticated?}} - Matched -->|Yes| C(Origin server) - Matched -->|No| D(Logto sign-in) - Condition -->|No| C + A("Client
(Browser)") -->|Anfrage| B(Logto
Protected App) + B --> Condition{{Route
passt?}} + Condition -->|Ja| Matched{{Ist authentifiziert?}} + Matched -->|Ja| C(Ursprungsserver) + Matched -->|Nein| D(Logto Anmeldung) + Condition -->|Nein| C ``` ## Schütze deinen Ursprungsserver \{#protect-your-origin-server} -Der Ursprungsserver, der entweder ein physisches oder virtuelles Gerät sein kann, das nicht von Logto's Protected App verwaltet wird, ist der Ort, an dem deine Anwendungsinhalte gespeichert sind. Ähnlich wie ein Content Delivery Network (CDN)-Server verwaltet die Protected App Authentifizierungsprozesse und ruft Inhalte von deinem Ursprungsserver ab. Wenn Benutzer jedoch direkten Zugriff auf deinen Ursprungsserver erhalten, können sie die Authentifizierung umgehen und deine Anwendung ist nicht mehr geschützt. +Der Ursprungsserver, der entweder ein physisches oder virtuelles Gerät sein kann und nicht der Protected App von Logto gehört, ist der Ort, an dem sich deine Anwendungsinhalte befinden. Ähnlich wie ein Content Delivery Network (CDN)-Server verwaltet die Protected App die Authentifizierungsprozesse und ruft Inhalte von deinem Ursprungsserver ab. Wenn Benutzer jedoch direkten Zugriff auf deinen Ursprungsserver erhalten, können sie die Authentifizierung umgehen und deine Anwendung ist nicht mehr geschützt. -Es ist daher wichtig, Ursprungsverbindungen zu sichern, um zu verhindern, dass Angreifer deinen Ursprungsserver ohne Authentifizierung entdecken und darauf zugreifen. Es gibt mehrere Möglichkeiten, dies zu tun: +Daher ist es wichtig, die Ursprungsverbindungen abzusichern, um zu verhindern, dass Angreifer deinen Ursprungsserver ohne Authentifizierung entdecken und darauf zugreifen. Es gibt mehrere Möglichkeiten, dies zu tun: 1. HTTP-Header-Validierung -2. JSON Web Tokens (JWT) Validierung +2. JSON Web Token (JWT)-Validierung ### HTTP-Header-Validierung \{#http-header-validation} -Die Sicherung deines Ursprungsservers kann durch die Verwendung von [HTTP Basic Authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication#basic_authentication_scheme) erreicht werden. +Die Absicherung deines Ursprungsservers kann durch [HTTP Basic Authentifizierung](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication#basic_authentication_scheme) erfolgen. -Jede Anfrage von der Protected App enthält den folgenden Header: +Jede Anfrage von der Protected App enthält folgenden Header: ``` Authorization: Basic base64(appId:appSecret) @@ -47,32 +47,32 @@ Authorization: Basic base64(appId:appSecret) Durch die Validierung dieses Headers kannst du bestätigen, dass die Anfrage von der Protected App stammt, und alle Anfragen ablehnen, die diesen Header nicht enthalten. -Wenn du Nginx oder Apache verwendest, kannst du auf die folgenden Anleitungen verweisen, um HTTP Basic Authentication auf deinem Ursprungsserver zu implementieren: +Wenn du Nginx oder Apache verwendest, kannst du die folgenden Anleitungen nutzen, um HTTP Basic Authentifizierung auf deinem Ursprungsserver zu implementieren: -1. Nginx: [Konfigurieren von HTTP Basic Authentication](https://docs.nginx.com/nginx/admin-guide/security-controls/configuring-http-basic-authentication/) +1. Nginx: [HTTP Basic Authentifizierung konfigurieren](https://docs.nginx.com/nginx/admin-guide/security-controls/configuring-http-basic-authentication/) 2. Apache: [Authentifizierung und Autorisierung](https://httpd.apache.org/docs/2.4/howto/auth.html) -Um die Header innerhalb deiner Anwendung zu überprüfen, kannst du das von Cloudflare bereitgestellte [HTTP Basic Authentication Beispiel](https://developers.cloudflare.com/workers/examples/basic-auth/) verwenden, um zu lernen, wie man den Zugriff mit dem HTTP Basic Schema einschränkt. +Um die Header innerhalb deiner Anwendung zu prüfen, siehe das [HTTP Basic Authentication Beispiel](https://developers.cloudflare.com/workers/examples/basic-auth/) von Cloudflare, um zu lernen, wie du den Zugriff mit dem HTTP Basic Schema einschränkst. -### JSON Web Tokens (JWT) Validierung \{#json-web-tokens-jwt-validation} +### JSON Web Token (JWT)-Validierung \{#json-web-tokens-jwt-validation} -Eine weitere Möglichkeit, deinen Ursprungsserver zu sichern, ist die Verwendung von JSON Web Tokens (JWT). +Eine weitere Möglichkeit, deinen Ursprungsserver abzusichern, ist die Verwendung von JSON Web Tokens (JWT). -Jede authentifizierte Anfrage von der Protected App enthält den folgenden Header: +Jede authentifizierte Anfrage von der Protected App enthält folgenden Header: ``` Logto-ID-Token: ``` -Das JWT wird [ID-Token](https://auth.wiki/id-token) genannt, das von Logto signiert ist und Benutzerinformationen enthält. Durch die Validierung dieses JWT kannst du bestätigen, dass die Anfrage von der Protected App stammt, und alle Anfragen ablehnen, die diesen Header nicht enthalten. +Das JWT wird als [ID-Token (ID token)](https://auth.wiki/id-token) bezeichnet, das von Logto signiert ist und Benutzerinformationen enthält. Durch die Validierung dieses JWT kannst du bestätigen, dass die Anfrage von der Protected App stammt, und alle Anfragen ablehnen, die diesen Header nicht enthalten. -Das Token ist als [JWS](https://auth.wiki/jws) Token verschlüsselt und signiert. +Das Token ist verschlüsselt und als [JWS](https://auth.wiki/jws)-Token signiert. Die Validierungsschritte: -1. [Validierung eines JWT](https://datatracker.ietf.org/doc/html/rfc7519#section-7.2) -2. [Validierung der JWS-Signatur](https://datatracker.ietf.org/doc/html/rfc7515#section-5.2) -3. Der Aussteller des Tokens ist `https:///oidc` (ausgestellt von deinem Logto-Auth-Server) +1. [Ein JWT validieren](https://datatracker.ietf.org/doc/html/rfc7519#section-7.2) +2. [Die JWS-Signatur validieren](https://datatracker.ietf.org/doc/html/rfc7515#section-5.2) +3. Der Aussteller (Issuer) des Tokens ist `https:///oidc` (ausgestellt von deinem Logto Auth-Server) ```js const express = require('express'); @@ -95,11 +95,11 @@ const getKey = (header, callback) => { const verifyToken = (req, res, next) => { const token = req.headers['Logto-ID-Token']; - // Stelle sicher, dass die eingehende Anfrage unseren Token-Header hat + // Stelle sicher, dass die eingehende Anfrage unseren Token-Header enthält if (!token) { return res .status(403) - .send({ status: false, message: 'fehlender erforderlicher Logto-ID-Token-Header' }); + .send({ status: false, message: 'fehlender erforderlicher Logto-ID-Token Header' }); } jwt.verify(token, getKey, { issuer: ISSUER }, (err, decoded) => { @@ -117,7 +117,7 @@ const app = express(); app.use(verifyToken); app.get('/', (req, res) => { - res.send('Hello World!'); + res.send('Hallo Welt!'); }); app.listen(3000); @@ -125,9 +125,9 @@ app.listen(3000); ## Authentifizierungsstatus und Benutzerinformationen abrufen \{#get-authentication-state-and-user-information} -Wenn du Authentifizierungs- und Benutzerinformationen für deine Anwendung benötigst, kannst du auch den `Logto-ID-Token` Header verwenden. +Wenn du Authentifizierungs- und Benutzerinformationen für deine Anwendung benötigst, kannst du ebenfalls den `Logto-ID-Token` Header verwenden. -Wenn du das Token nur dekodieren möchtest, kannst du den folgenden Code verwenden: +Wenn du das Token nur dekodieren möchtest, kannst du folgenden Code verwenden: ```js const express = require('express'); @@ -138,7 +138,7 @@ const decodeIdToken = (req, res, next) => { if (!token) { return res.status(403).send({ status: false, - message: 'fehlender erforderlicher Logto-ID-Token-Header', + message: 'fehlender erforderlicher Logto-ID-Token Header', }); } @@ -166,26 +166,43 @@ app.get('/', (req, res) => { app.listen(3000); ``` +## ID-Token-Ansprüche anpassen \{#customize-id-token-claims} + +Standardmäßig enthält der `Logto-ID-Token` Header die Standard-OIDC-Ansprüche (z. B. `sub`, `name` und `email`). Um [erweiterte Ansprüche](/developers/custom-id-token#extended-claims) wie Rollen oder Organisationsdaten einzuschließen, müssen beide folgenden Punkte konfiguriert werden: + +1. **Mandanten-Umschalter**: Aktiviere den Anspruch in Konsole > Custom JWT > ID-Token. +2. **Protected App Scopes**: Wähle in deinen Protected App Einstellungen den passenden Scope unter **ID-Token-Ansprüche** > **Zusätzliche Scopes** aus. + +Erweiterte Ansprüche werden nur dann im weitergeleiteten ID-Token enthalten, wenn der Anspruch in Custom JWT aktiviert und der entsprechende Scope für die Protected App ausgewählt ist. Siehe [Custom ID-Token](/developers/custom-id-token) für die vollständige Liste der erweiterten Scopes und Ansprüche. + +| Scope | Ansprüche | +| ------------------------------------ | ------------------------------------ | +| `custom_data` | `custom_data` | +| `identities` | `identities`, `sso_identities` | +| `roles` | `roles` | +| `urn:logto:scope:organizations` | `organizations`, `organization_data` | +| `urn:logto:scope:organization_roles` | `organization_roles` | + ## Den ursprünglichen Host abrufen \{#get-the-original-host} -Wenn du den ursprünglichen Host abrufen musst, der vom Client angefordert wurde, kannst du den `Logto-Host` oder `x-forwarded-host` Header verwenden. +Wenn du den ursprünglichen Host benötigst, der vom Client angefragt wurde, kannst du den `Logto-Host` oder `x-forwarded-host` Header verwenden. ## Authentifizierungsregeln anpassen \{#customize-authentication-rules} -Standardmäßig schützt die Protected App alle Routen. Wenn du die Authentifizierungsregeln anpassen musst, kannst du das Feld "Benutzerdefinierte Authentifizierungsregeln" in der Konsole festlegen. +Standardmäßig schützt die Protected App alle Routen. Wenn du die Authentifizierungsregeln anpassen möchtest, kannst du das Feld „Benutzerdefinierte Authentifizierungsregeln“ in der Konsole setzen. -Es unterstützt reguläre Ausdrücke, hier sind zwei Fallbeispiele: +Es werden reguläre Ausdrücke unterstützt, hier zwei Anwendungsfälle: 1. Um nur die Routen `/admin` und `/privacy` mit Authentifizierung zu schützen: `^/(admin|privacy)/.*` 2. Um JPG-Bilder von der Authentifizierung auszuschließen: `^(?!.*\.jpg$).*$` ## Lokale Entwicklung \{#local-development} -Die Protected App ist darauf ausgelegt, mit deinem Ursprungsserver zu arbeiten. Wenn dein Ursprungsserver jedoch nicht öffentlich zugänglich ist, kannst du ein Tool wie [ngrok](https://ngrok.com/) oder [Cloudflare Tunnels](https://developers.cloudflare.com/pages/how-to/preview-with-cloudflare-tunnel/) verwenden, um deinen lokalen Server im Internet verfügbar zu machen. +Die Protected App ist darauf ausgelegt, mit deinem Ursprungsserver zu arbeiten. Ist dein Ursprungsserver jedoch nicht öffentlich erreichbar, kannst du ein Tool wie [ngrok](https://ngrok.com/) oder [Cloudflare Tunnels](https://developers.cloudflare.com/pages/how-to/preview-with-cloudflare-tunnel/) verwenden, um deinen lokalen Server ins Internet zu bringen. -## Übergang zur SDK-Integration \{#transition-to-sdk-integration} +## Umstieg auf SDK-Integration \{#transition-to-sdk-integration} -Die Protected App wurde entwickelt, um den Authentifizierungsprozess zu vereinfachen. Wenn du jedoch zur SDK-Integration für bessere Kontrolle und Anpassung wechseln möchtest, kannst du [eine neue Anwendung erstellen](/integrate-logto/integrate-logto-into-your-application) in Logto und die [SDK-Integration](/quick-starts) konfigurieren. Für einen reibungslosen Übergang kannst du die Anwendungskonfigurationen von der Protected App wiederverwenden. Die Protected App ist tatsächlich eine "Traditionelle Web-App" in Logto, du kannst die "[AppId](/integrate-logto/application-data-structure#application-id)" und "[AppSecret](/integrate-logto/application-data-structure#application-secret)" in den Anwendungseinstellungen finden. Nach Abschluss des Übergangs kannst du die Protected App aus deiner Anwendung entfernen. +Die Protected App wurde entwickelt, um den Authentifizierungsprozess zu vereinfachen. Wenn du jedoch für mehr Kontrolle und Anpassung auf eine SDK-Integration umsteigen möchtest, kannst du [eine neue Anwendung erstellen](/integrate-logto/integrate-logto-into-your-application) und die [SDK-Integration konfigurieren](/quick-starts). Für einen reibungslosen Übergang kannst du die Anwendungskonfigurationen aus der Protected App wiederverwenden. Die Protected App ist tatsächlich eine „Traditionelle Web-App“ in Logto, du findest die "[AppId](/integrate-logto/application-data-structure#application-id)" und "[AppSecret](/integrate-logto/application-data-structure#application-secret)" in den Anwendungseinstellungen. Nach Abschluss des Umstiegs kannst du die Protected App aus deiner Anwendung entfernen. ## Verwandte Ressourcen \{#related-resources} diff --git a/i18n/de/docusaurus-plugin-content-docs/current/logto-cloud/README.mdx b/i18n/de/docusaurus-plugin-content-docs/current/logto-cloud/README.mdx index c198530684a..1b9f3a3d8cc 100644 --- a/i18n/de/docusaurus-plugin-content-docs/current/logto-cloud/README.mdx +++ b/i18n/de/docusaurus-plugin-content-docs/current/logto-cloud/README.mdx @@ -3,6 +3,7 @@ import Developer from '@site/src/assets/developer.svg'; import TenantMemberManagement from '@site/src/assets/gear.svg'; import PricingAndBilling from '@site/src/assets/key.svg'; import McpIcon from '@site/src/assets/mcp.svg'; +import TenantAutomation from '@site/src/assets/robot.svg'; import CustomDomains from '@site/src/assets/search.svg'; import SystemLimit from '@site/src/assets/security.svg'; @@ -41,7 +42,7 @@ Wenn du Fragen zu Cloud-Diensten hast und zusätzliche Unterstützung benötigst label: 'Mandanten-Mitgliederverwaltung', href: '/logto-cloud/tenant-member-management', description: - 'Der Mandanten-Admin kann Mitglieder einladen und verwalten sowie deren Rollen aktualisieren.', + 'Der Mandanten-Admin kann Mitglieder einladen, verwalten und deren Rollen aktualisieren.', customProps: { icon: , }, @@ -51,7 +52,7 @@ Wenn du Fragen zu Cloud-Diensten hast und zusätzliche Unterstützung benötigst label: 'Eigene Domains', href: '/logto-cloud/custom-domain', description: - 'Verwende deine eigene Domain für deinen Logto-Mandanten, um ein konsistentes Branding in deiner Endbenutzererfahrung zu gewährleisten.', + 'Nutze deine eigene Domain für deinen Logto-Mandanten, um ein konsistentes Branding in der Endbenutzererfahrung zu gewährleisten.', customProps: { icon: , }, @@ -75,6 +76,16 @@ Wenn du Fragen zu Cloud-Diensten hast und zusätzliche Unterstützung benötigst icon: , }, }, + { + type: 'link', + label: 'Mandantenverwaltung automatisieren', + href: '/logto-cloud/automate-tenant-creation', + description: + 'Erstelle und verwalte Mandanten programmatisch mit Logto Cloud API und Management API.', + customProps: { + icon: , + }, + }, { type: 'link', label: 'Logto MCP Server', diff --git a/i18n/de/docusaurus-plugin-content-docs/current/logto-cloud/automate-tenant-creation.mdx b/i18n/de/docusaurus-plugin-content-docs/current/logto-cloud/automate-tenant-creation.mdx new file mode 100644 index 00000000000..b4bb26e85b5 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/logto-cloud/automate-tenant-creation.mdx @@ -0,0 +1,242 @@ +--- +id: automate-tenant-creation +title: Mandantenverwaltung automatisieren +sidebar_position: 8 +--- + +# Mandantenverwaltung automatisieren + +Du kannst Logto Cloud-Mandanten programmatisch verwalten, einschließlich der Erstellung von Mandanten und der weiteren Konfiguration, ohne zur Konsole wechseln zu müssen. + +Das ist nützlich, wenn du Mandanten aus deinem eigenen Onboarding-Flow, einer internen Plattform, einem KI-Agenten oder einer Integrationsautomatisierung bereitstellen musst. + +Der Automatisierungsablauf ist: + +1. Verwende ein **Logto Cloud Personal Access Token (PAT)**, um die Logto Cloud API aufzurufen. +2. Erstelle einen Mandanten mit `POST /api/tenants`. +3. Lies die Standard-Maschine-zu-Maschine (M2M)-Anwendungsdaten aus der Antwort zur Erstellung aus. +4. Verwende die Standard-M2M-Anwendung, um ein Management API Zugangstoken für den neuen Mandanten zu erhalten. +5. Rufe die Management API des neuen Mandanten auf, um die Bereitstellung von Anwendungen, Benutzern, Rollen, Ressourcen, Organisationen und weiteren Einstellungen fortzusetzen. + +## Bevor du beginnst \{#before-you-start} + +Bereite die folgenden Werte vor: + +| Variable | Beschreibung | +| -------------------- | -------------------------------------------------------------------------------- | +| `CLOUD_API_ENDPOINT` | Der Logto Cloud API-Endpunkt. Für Logto Cloud verwende `https://cloud.logto.io`. | +| `LOGTO_CLOUD_PAT` | Ein PAT für dein Logto Cloud-Konto. | +| `TENANT_NAME` | Der Anzeigename des zu erstellenden Mandanten. | +| `TENANT_TAG` | Der Mandantentyp. Verwende `development` oder `production`. | +| `REGION_NAME` | Der Regionsbezeichner für den Mandanten. | + +Setze sie als Umgebungsvariablen: + +```bash +export CLOUD_API_ENDPOINT="https://cloud.logto.io" +export LOGTO_CLOUD_PAT="" +export TENANT_NAME="Mein automatisierter Mandant" +export TENANT_TAG="development" +export REGION_NAME="" +``` + +## Verfügbare Regionen abrufen \{#get-available-regions} + +Bevor du einen Mandanten erstellst, rufe die für dein Logto Cloud-Konto verfügbaren Regionen ab: + +```bash +curl "$CLOUD_API_ENDPOINT/api/me/regions" \ + -H "Authorization: Bearer $LOGTO_CLOUD_PAT" +``` + +Die Antwort enthält die verfügbaren Regionen. Verwende den Wert von `name` als `REGION_NAME`, wenn du den Mandanten erstellst. + +Beispielantwort: + +```json +{ + "regions": [ + { + "name": "EU", + "displayName": "Europe" + }, + { + "name": "US", + "displayName": "United States" + } + ] +} +``` + +## Einen Mandanten erstellen \{#create-a-tenant} + +Rufe `POST /api/tenants` mit dem Logto Cloud PAT auf: + +```bash +curl "$CLOUD_API_ENDPOINT/api/tenants" \ + -X POST \ + -H "Authorization: Bearer $LOGTO_CLOUD_PAT" \ + -H "Content-Type: application/json" \ + -d '{ + "name": "'"$TENANT_NAME"'", + "tag": "'"$TENANT_TAG"'", + "regionName": "'"$REGION_NAME"'" + }' +``` + +Die Antwort enthält den erstellten Mandanten und eine Standard-M2M-Anwendung. Die M2M-Anwendung wird im neuen Mandanten erstellt und hat Zugriff auf die Management API des Mandanten. + +Beispielantwort: + +```json +{ + "id": "new-tenant-id", + "name": "Mein automatisierter Mandant", + "tag": "development", + "indicator": "https://new-tenant-id.logto.app", + "regionName": "EU", + "defaultApplication": { + "id": "default-m2m-app-id", + "secret": "default-m2m-app-secret" + } +} +``` + +Speichere die Werte, die du für den nächsten Schritt benötigst: + +```bash +export TENANT_ID="" +export TENANT_ENDPOINT="" +export DEFAULT_M2M_APP_ID="" +export DEFAULT_M2M_APP_SECRET="" +``` + +## Ein Management API Zugangstoken für den neuen Mandanten erhalten \{#get-a-management-api-access-token-for-the-new-tenant} + +Verwende die Standard-M2M-Anwendungsdaten, um ein Zugangstoken vom neuen Mandanten anzufordern: + +```bash +curl "$TENANT_ENDPOINT/oidc/token" \ + -X POST \ + -u "$DEFAULT_M2M_APP_ID:$DEFAULT_M2M_APP_SECRET" \ + -H "Content-Type: application/x-www-form-urlencoded" \ + -d "grant_type=client_credentials" \ + -d "resource=$TENANT_ENDPOINT/api" \ + -d "scope=all" +``` + +Beispielantwort: + +```json +{ + "access_token": "eyJ...", + "expires_in": 3600, + "token_type": "Bearer", + "scope": "all" +} +``` + +Speichere das Zugangstoken: + +```bash +export MANAGEMENT_API_ACCESS_TOKEN="" +``` + +## Die Bereitstellung des neuen Mandanten fortsetzen \{#continue-provisioning-the-new-tenant} + +Verwende das Management API Zugangstoken, um die Management API des neuen Mandanten aufzurufen. + +Zum Beispiel, um Anwendungen aufzulisten: + +```bash +curl "$TENANT_ENDPOINT/api/applications" \ + -H "Authorization: Bearer $MANAGEMENT_API_ACCESS_TOKEN" +``` + +Oder eine Anwendung erstellen: + +```bash +curl "$TENANT_ENDPOINT/api/applications" \ + -X POST \ + -H "Authorization: Bearer $MANAGEMENT_API_ACCESS_TOKEN" \ + -H "Content-Type: application/json" \ + -d '{ + "name": "Meine Web-App", + "type": "SPA", + "oidcClientMetadata": { + "redirectUris": ["https://example.com/callback"], + "postLogoutRedirectUris": ["https://example.com"] + } + }' +``` + +An diesem Punkt kann deine Automatisierung mit jeder Management API-Operation fortfahren, wie z. B. dem Erstellen von Benutzern, Anwendungen, API-Ressourcen, Rollen, Organisationen, Connectors oder Einstellungen für die Anmeldeerfahrung. + +## Vollständiges Automatisierungsbeispiel \{#full-automation-example} + +Das folgende Node.js-Beispiel erstellt einen Mandanten, tauscht die zurückgegebenen Standard-M2M-Zugangsdaten gegen ein Management API Zugangstoken aus und listet Anwendungen im neuen Mandanten auf: + +```js +const cloudApiEndpoint = 'https://cloud.logto.io'; +const logtoCloudPat = process.env.LOGTO_CLOUD_PAT; + +const createTenantResponse = await fetch(`${cloudApiEndpoint}/api/tenants`, { + method: 'POST', + headers: { + authorization: `Bearer ${logtoCloudPat}`, + 'content-type': 'application/json', + }, + body: JSON.stringify({ + name: 'Mein automatisierter Mandant', + tag: 'development', + regionName: 'EU', + }), +}); + +if (!createTenantResponse.ok) { + throw new Error(`Fehler beim Erstellen des Mandanten: ${await createTenantResponse.text()}`); +} + +const tenant = await createTenantResponse.json(); +const tenantEndpoint = tenant.indicator; +const { id: appId, secret: appSecret } = tenant.defaultApplication; + +const tokenResponse = await fetch(`${tenantEndpoint}/oidc/token`, { + method: 'POST', + headers: { + authorization: `Basic ${Buffer.from(`${appId}:${appSecret}`).toString('base64')}`, + 'content-type': 'application/x-www-form-urlencoded', + }, + body: new URLSearchParams({ + grant_type: 'client_credentials', + resource: `${tenantEndpoint}/api`, + scope: 'all', + }), +}); + +if (!tokenResponse.ok) { + throw new Error(`Fehler beim Abrufen des Management API Tokens: ${await tokenResponse.text()}`); +} + +const { access_token: managementApiAccessToken } = await tokenResponse.json(); + +const applicationsResponse = await fetch(`${tenantEndpoint}/api/applications`, { + headers: { + authorization: `Bearer ${managementApiAccessToken}`, + }, +}); + +if (!applicationsResponse.ok) { + throw new Error(`Fehler beim Auflisten der Anwendungen: ${await applicationsResponse.text()}`); +} + +const applications = await applicationsResponse.json(); + +console.log({ tenantId: tenant.id, applications }); +``` + +## Verwandte Ressourcen \{#related-resources} + +- [Personal access token](/user-management/personal-access-token) +- [Mit Management API interagieren](/integrate-logto/interact-with-management-api) +- [Maschine-zu-Maschine Schnellstart](/quick-starts/m2m) diff --git a/i18n/es/docusaurus-plugin-content-docs/current/integrate-logto/protected-app.mdx b/i18n/es/docusaurus-plugin-content-docs/current/integrate-logto/protected-app.mdx index 0c524ce0126..7499438be09 100644 --- a/i18n/es/docusaurus-plugin-content-docs/current/integrate-logto/protected-app.mdx +++ b/i18n/es/docusaurus-plugin-content-docs/current/integrate-logto/protected-app.mdx @@ -1,25 +1,25 @@ --- -description: Añade fácilmente autenticación sin código a tus aplicaciones web con la innovadora Protected App de Logto, impulsada por Cloudflare. Soporta HTTP Basic Authentication y validación de JWT. +description: Añade fácilmente autenticación sin código a tus aplicaciones web con la innovadora Protected App de Logto, impulsada por Cloudflare. Soporta autenticación HTTP Basic y validación de JWT. sidebar_label: Protected App sidebar_position: 2 --- # Protected App — Integración de autenticación sin SDK -La Protected App está diseñada para eliminar la complejidad de las [integraciones de SDK](/quick-starts) separando la [autenticación](https://auth.wiki/authentication) de tu aplicación. Nosotros manejamos la autenticación, permitiéndote enfocarte en tu funcionalidad principal. Una vez que un usuario está autenticado, la Protected App sirve el contenido desde tu servidor. +La Protected App está diseñada para eliminar la complejidad de las [integraciones de SDK](/quick-starts) separando la capa de [autenticación (Authentication)](https://auth.wiki/authentication) de tu aplicación. Nosotros gestionamos la autenticación, permitiéndote centrarte en tu funcionalidad principal. Una vez que un usuario está autenticado, la Protected App sirve el contenido desde tu servidor. ## Cómo funciona Protected App \{#how-protected-app-works} -La Protected App, impulsada por Cloudflare, opera globalmente en redes de borde, asegurando baja latencia y alta disponibilidad para tu aplicación. +La Protected App, impulsada por Cloudflare, opera globalmente en redes edge, asegurando baja latencia y alta disponibilidad para tu aplicación. -La Protected App mantiene el estado de la sesión y la información del usuario. Si un usuario no está autenticado, la Protected App lo redirige a la página de inicio de sesión. Una vez autenticado, la Protected App envuelve la solicitud del usuario con autenticación e información del usuario, y luego la reenvía al servidor de origen. +La Protected App mantiene el estado de la sesión y la información del usuario. Si un usuario no está autenticado, la Protected App lo redirige a la página de inicio de sesión. Una vez autenticado, la Protected App envuelve la solicitud del usuario con la autenticación e información del usuario, y luego la reenvía al servidor de origen. Este proceso se visualiza en el siguiente diagrama de flujo: ```mermaid graph LR A("Cliente
(Navegador)") -->|Solicitud| B(Logto
Protected App) - B --> Condition{{¿Coincide la ruta?}} + B --> Condition{{¿Ruta
coincide?}} Condition -->|Sí| Matched{{¿Está autenticado?}} Matched -->|Sí| C(Servidor de origen) Matched -->|No| D(Inicio de sesión de Logto) @@ -28,45 +28,45 @@ graph LR ## Protege tu servidor de origen \{#protect-your-origin-server} -El servidor de origen, que podría ser un dispositivo físico o virtual no propiedad de la Protected App de Logto, es donde reside el contenido de tu aplicación. Similar a un servidor de Content Delivery Network (CDN), la Protected App gestiona los procesos de autenticación y recupera contenido de tu servidor de origen. Por lo tanto, si los usuarios obtienen acceso directo a tu servidor de origen, pueden eludir la autenticación y tu aplicación ya no está protegida. +El servidor de origen, que puede ser un dispositivo físico o virtual que no pertenece a la Protected App de Logto, es donde reside el contenido de tu aplicación. Similar a un servidor de Content Delivery Network (CDN), la Protected App gestiona los procesos de autenticación y recupera el contenido de tu servidor de origen. Por lo tanto, si los usuarios obtienen acceso directo a tu servidor de origen, pueden eludir la autenticación y tu aplicación deja de estar protegida. -Por lo tanto, es importante asegurar las conexiones de origen, ya que previene que los atacantes descubran y accedan a tu servidor de origen sin autenticación. Hay varias maneras de hacer esto: +Por eso es importante asegurar las conexiones de origen, ya que previene que los atacantes descubran y accedan a tu servidor de origen sin autenticación. Hay varias formas de hacerlo: -1. Validación de cabeceras HTTP +1. Validación de cabecera HTTP 2. Validación de JSON Web Tokens (JWT) -### Validación de cabeceras HTTP \{#http-header-validation} +### Validación de cabecera HTTP \{#http-header-validation} -Asegurar tu servidor de origen se puede lograr usando [HTTP Basic Authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication#basic_authentication_scheme) para asegurar tu servidor de origen. +Proteger tu servidor de origen se puede lograr usando [HTTP Basic Authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication#basic_authentication_scheme) para asegurar tu servidor de origen. -Cada solicitud de la Protected App incluye la siguiente cabecera: +Cada solicitud desde la Protected App incluye la siguiente cabecera: ``` Authorization: Basic base64(appId:appSecret) ``` -Al validar esta cabecera, puedes confirmar que la solicitud proviene de la Protected App y negar cualquier solicitud que no incluya esta cabecera. +Al validar esta cabecera, puedes confirmar que la solicitud proviene de la Protected App y denegar cualquier solicitud que no incluya esta cabecera. -Si estás usando Nginx o Apache, puedes consultar las siguientes guías para implementar HTTP Basic Authentication en tu servidor de origen: +Si usas Nginx o Apache, puedes consultar las siguientes guías para implementar HTTP Basic Authentication en tu servidor de origen: 1. Nginx: [Configuring HTTP Basic Authentication](https://docs.nginx.com/nginx/admin-guide/security-controls/configuring-http-basic-authentication/) 2. Apache: [Authentication and Authorization](https://httpd.apache.org/docs/2.4/howto/auth.html) -Para verificar las cabeceras dentro de tu aplicación, consulta el [ejemplo de HTTP Basic Authentication](https://developers.cloudflare.com/workers/examples/basic-auth/) proporcionado por Cloudflare para aprender cómo restringir el acceso usando el esquema HTTP Basic. +Para comprobar las cabeceras dentro de tu aplicación, consulta el [ejemplo de HTTP Basic Authentication](https://developers.cloudflare.com/workers/examples/basic-auth/) proporcionado por Cloudflare para aprender cómo restringir el acceso usando el esquema HTTP Basic. ### Validación de JSON Web Tokens (JWT) \{#json-web-tokens-jwt-validation} -Otra forma de asegurar tu servidor de origen es usando JSON Web Tokens (JWT). +Otra forma de proteger tu servidor de origen es usando JSON Web Tokens (JWT). -Cada solicitud autenticada de la Protected App incluye la siguiente cabecera: +Cada solicitud autenticada desde la Protected App incluye la siguiente cabecera: ``` Logto-ID-Token: ``` -El JWT se llama [Token de ID](https://auth.wiki/id-token) que está firmado por Logto y contiene información del usuario. Al validar este JWT, puedes confirmar que la solicitud proviene de la Protected App y negar cualquier solicitud que no incluya esta cabecera. +El JWT se llama [Token de ID (ID Token)](https://auth.wiki/id-token), el cual está firmado por Logto y contiene información del usuario. Al validar este JWT, puedes confirmar que la solicitud proviene de la Protected App y denegar cualquier solicitud que no incluya esta cabecera. -El token está encriptado y firmado como un token [JWS](https://auth.wiki/jws). +El token está cifrado y firmado como un token [JWS](https://auth.wiki/jws). Los pasos de validación: @@ -127,7 +127,7 @@ app.listen(3000); Si necesitas obtener la autenticación y la información del usuario para tu aplicación, también puedes usar la cabecera `Logto-ID-Token`. -Si solo deseas decodificar el token, puedes usar el siguiente código: +Si solo quieres decodificar el token, puedes usar el siguiente código: ```js const express = require('express'); @@ -166,31 +166,48 @@ app.get('/', (req, res) => { app.listen(3000); ``` +## Personalizar los reclamos del token de ID \{#customize-id-token-claims} + +Por defecto, la cabecera `Logto-ID-Token` incluye reclamos estándar de OIDC (por ejemplo, `sub`, `name` y `email`). Para incluir [reclamos extendidos](/developers/custom-id-token#extended-claims) como roles o datos de organización, ambos de los siguientes deben estar configurados: + +1. **Conmutador del tenant**: Habilita el reclamo en Consola > Custom JWT > Token de ID. +2. **Alcances de Protected App**: En la configuración de tu Protected App, selecciona el alcance correspondiente en **Reclamos del token de ID** > **Alcances adicionales**. + +Los reclamos extendidos se incluyen en el token de ID reenviado solo cuando el reclamo está habilitado en Custom JWT y el alcance correspondiente está seleccionado para la Protected App. Consulta [Token de ID personalizado](/developers/custom-id-token) para la lista completa de alcances y reclamos extendidos. + +| Alcance | Reclamos | +| ------------------------------------ | ------------------------------------ | +| `custom_data` | `custom_data` | +| `identities` | `identities`, `sso_identities` | +| `roles` | `roles` | +| `urn:logto:scope:organizations` | `organizations`, `organization_data` | +| `urn:logto:scope:organization_roles` | `organization_roles` | + ## Obtener el host original \{#get-the-original-host} Si necesitas obtener el host original solicitado por el cliente, puedes usar la cabecera `Logto-Host` o `x-forwarded-host`. -## Personalizar reglas de autenticación \{#customize-authentication-rules} +## Personalizar las reglas de autenticación \{#customize-authentication-rules} Por defecto, la Protected App protegerá todas las rutas. Si necesitas personalizar las reglas de autenticación, puedes establecer el campo "Reglas de autenticación personalizadas" en la Consola. -Soporta expresiones regulares, aquí hay dos escenarios de caso: +Soporta expresiones regulares, aquí tienes dos escenarios de ejemplo: 1. Para proteger solo las rutas `/admin` y `/privacy` con autenticación: `^/(admin|privacy)/.*` 2. Para excluir imágenes JPG de la autenticación: `^(?!.*\.jpg$).*$` ## Desarrollo local \{#local-development} -La Protected App está diseñada para trabajar con tu servidor de origen. Sin embargo, si tu servidor de origen no es accesible públicamente, puedes usar una herramienta como [ngrok](https://ngrok.com/) o [Cloudflare Tunnels](https://developers.cloudflare.com/pages/how-to/preview-with-cloudflare-tunnel/) para exponer tu servidor local a internet. +La Protected App está diseñada para funcionar con tu servidor de origen. Sin embargo, si tu servidor de origen no es accesible públicamente, puedes usar una herramienta como [ngrok](https://ngrok.com/) o [Cloudflare Tunnels](https://developers.cloudflare.com/pages/how-to/preview-with-cloudflare-tunnel/) para exponer tu servidor local a internet. -## Transición a la integración con SDK \{#transition-to-sdk-integration} +## Transición a integración con SDK \{#transition-to-sdk-integration} -La Protected App está diseñada para simplificar el proceso de autenticación. Sin embargo, si decides hacer la transición a la integración con SDK para un mejor control y personalización, puedes [crear una nueva aplicación](/integrate-logto/integrate-logto-into-your-application) en Logto y configurar la [integración con SDK](/quick-starts). Y para una transición sin problemas, puedes reutilizar las configuraciones de la aplicación de la Protected App. La Protected App es en realidad una "Aplicación Web Tradicional" en Logto, puedes encontrar el "[AppId](/integrate-logto/application-data-structure#application-id)" y el "[AppSecret](/integrate-logto/application-data-structure#application-secret)" en la configuración de la aplicación. Una vez que la transición esté completa, puedes eliminar la Protected App de tu aplicación. +La Protected App está diseñada para simplificar el proceso de autenticación. Sin embargo, si decides pasar a la integración con SDK para un mayor control y personalización, puedes [crear una nueva aplicación](/integrate-logto/integrate-logto-into-your-application) en Logto y configurar la [integración con SDK](/quick-starts). Y para una transición fluida, puedes reutilizar la configuración de la aplicación de la Protected App. La Protected App es en realidad una "Traditional Web App" en Logto, puedes encontrar el "[AppId](/integrate-logto/application-data-structure#application-id)" y el "[AppSecret](/integrate-logto/application-data-structure#application-secret)" en la configuración de la aplicación. Una vez completada la transición, puedes eliminar la Protected App de tu aplicación. ## Recursos relacionados \{#related-resources} - Protected App: Construye la autenticación de tu aplicación en clics. No se requiere código. + Protected App: Construye la autenticación de tu app en pocos clics. Sin código. La motivación detrás de Protected App diff --git a/i18n/es/docusaurus-plugin-content-docs/current/logto-cloud/README.mdx b/i18n/es/docusaurus-plugin-content-docs/current/logto-cloud/README.mdx index 7b743b7a9b6..24e47cf4756 100644 --- a/i18n/es/docusaurus-plugin-content-docs/current/logto-cloud/README.mdx +++ b/i18n/es/docusaurus-plugin-content-docs/current/logto-cloud/README.mdx @@ -3,6 +3,7 @@ import Developer from '@site/src/assets/developer.svg'; import TenantMemberManagement from '@site/src/assets/gear.svg'; import PricingAndBilling from '@site/src/assets/key.svg'; import McpIcon from '@site/src/assets/mcp.svg'; +import TenantAutomation from '@site/src/assets/robot.svg'; import CustomDomains from '@site/src/assets/search.svg'; import SystemLimit from '@site/src/assets/security.svg'; @@ -51,7 +52,7 @@ Si tienes alguna pregunta sobre los servicios en la nube y necesitas soporte adi label: 'Dominios personalizados', href: '/logto-cloud/custom-domain', description: - 'Utiliza tu propio dominio para tu tenant de Logto y mantén la coherencia de marca en la experiencia de usuario final.', + 'Utiliza tu propio dominio para tu tenant de Logto y mantén la coherencia de marca en la experiencia de tus usuarios finales.', customProps: { icon: , }, @@ -75,12 +76,22 @@ Si tienes alguna pregunta sobre los servicios en la nube y necesitas soporte adi icon: , }, }, + { + type: 'link', + label: 'Automatiza la gestión de tenants', + href: '/logto-cloud/automate-tenant-creation', + description: + 'Crea y gestiona tenants de forma programática con Logto Cloud API y Management API.', + customProps: { + icon: , + }, + }, { type: 'link', label: 'Logto MCP Server', href: '/logto-cloud/logto-mcp-server', description: - 'Conecta herramientas de IA e IDEs a Logto Cloud mediante MCP para gestionar recursos e integrar autenticación.', + 'Conecta herramientas de IA e IDEs a Logto Cloud vía MCP para gestionar recursos e integrar autenticación.', customProps: { icon: , }, diff --git a/i18n/es/docusaurus-plugin-content-docs/current/logto-cloud/automate-tenant-creation.mdx b/i18n/es/docusaurus-plugin-content-docs/current/logto-cloud/automate-tenant-creation.mdx new file mode 100644 index 00000000000..223e88862e3 --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/logto-cloud/automate-tenant-creation.mdx @@ -0,0 +1,244 @@ +--- +id: automate-tenant-creation +title: Automatiza la gestión de tenants +sidebar_position: 8 +--- + +# Automatiza la gestión de tenants + +Puedes gestionar los tenants de Logto Cloud de forma programática, incluyendo la creación de tenants y la continuación de la configuración sin cambiar a la Consola. + +Esto es útil cuando necesitas aprovisionar tenants desde tu propio flujo de incorporación, plataforma interna, agente de IA o automatización de integraciones. + +El flujo de automatización es: + +1. Usa un **Logto Cloud Personal Access Token (PAT)** para llamar a la API de Logto Cloud. +2. Crea un tenant con `POST /api/tenants`. +3. Lee las credenciales predeterminadas de la aplicación máquina a máquina (M2M) de la respuesta de creación. +4. Usa la aplicación M2M predeterminada para obtener un token de acceso de la Management API para el nuevo tenant. +5. Llama a la Management API del nuevo tenant para continuar aprovisionando aplicaciones, usuarios, roles, recursos, organizaciones y otros ajustes. + +## Antes de empezar \{#before-you-start} + +Prepara los siguientes valores: + +| Variable | Descripción | +| -------------------- | ------------------------------------------------------------------------------------- | +| `CLOUD_API_ENDPOINT` | El endpoint de la API de Logto Cloud. Para Logto Cloud, usa `https://cloud.logto.io`. | +| `LOGTO_CLOUD_PAT` | Un PAT para tu cuenta de Logto Cloud. | +| `TENANT_NAME` | El nombre visible del tenant a crear. | +| `TENANT_TAG` | El tipo de tenant. Usa `development` o `production`. | +| `REGION_NAME` | El identificador de región para el tenant. | + +Establécelos como variables de entorno: + +```bash +export CLOUD_API_ENDPOINT="https://cloud.logto.io" +export LOGTO_CLOUD_PAT="" +export TENANT_NAME="Mi tenant automatizado" +export TENANT_TAG="development" +export REGION_NAME="" +``` + +## Obtener regiones disponibles \{#get-available-regions} + +Antes de crear un tenant, obtén las regiones disponibles para tu cuenta de Logto Cloud: + +```bash +curl "$CLOUD_API_ENDPOINT/api/me/regions" \ + -H "Authorization: Bearer $LOGTO_CLOUD_PAT" +``` + +La respuesta contiene las regiones disponibles. Usa el valor `name` como `REGION_NAME` al crear el tenant. + +Ejemplo de respuesta: + +```json +{ + "regions": [ + { + "name": "EU", + "displayName": "Europe" + }, + { + "name": "US", + "displayName": "United States" + } + ] +} +``` + +## Crear un tenant \{#create-a-tenant} + +Llama a `POST /api/tenants` con el Logto Cloud PAT: + +```bash +curl "$CLOUD_API_ENDPOINT/api/tenants" \ + -X POST \ + -H "Authorization: Bearer $LOGTO_CLOUD_PAT" \ + -H "Content-Type: application/json" \ + -d '{ + "name": "'"$TENANT_NAME"'", + "tag": "'"$TENANT_TAG"'", + "regionName": "'"$REGION_NAME"'" + }' +``` + +La respuesta incluye el tenant creado y una aplicación M2M predeterminada. La aplicación M2M se crea en el nuevo tenant y tiene acceso a la Management API del tenant. + +Ejemplo de respuesta: + +```json +{ + "id": "new-tenant-id", + "name": "Mi tenant automatizado", + "tag": "development", + "indicator": "https://new-tenant-id.logto.app", + "regionName": "EU", + "defaultApplication": { + "id": "default-m2m-app-id", + "secret": "default-m2m-app-secret" + } +} +``` + +Guarda los valores que necesitas para el siguiente paso: + +```bash +export TENANT_ID="" +export TENANT_ENDPOINT="" +export DEFAULT_M2M_APP_ID="" +export DEFAULT_M2M_APP_SECRET="" +``` + +## Obtener un token de acceso de la Management API para el nuevo tenant \{#get-a-management-api-access-token-for-the-new-tenant} + +Usa las credenciales de la aplicación M2M predeterminada para solicitar un token de acceso del nuevo tenant: + +```bash +curl "$TENANT_ENDPOINT/oidc/token" \ + -X POST \ + -u "$DEFAULT_M2M_APP_ID:$DEFAULT_M2M_APP_SECRET" \ + -H "Content-Type: application/x-www-form-urlencoded" \ + -d "grant_type=client_credentials" \ + -d "resource=$TENANT_ENDPOINT/api" \ + -d "scope=all" +``` + +Ejemplo de respuesta: + +```json +{ + "access_token": "eyJ...", + "expires_in": 3600, + "token_type": "Bearer", + "scope": "all" +} +``` + +Guarda el token de acceso: + +```bash +export MANAGEMENT_API_ACCESS_TOKEN="" +``` + +## Continúa aprovisionando el nuevo tenant \{#continue-provisioning-the-new-tenant} + +Usa el token de acceso de la Management API para llamar a la Management API del nuevo tenant. + +Por ejemplo, listar aplicaciones: + +```bash +curl "$TENANT_ENDPOINT/api/applications" \ + -H "Authorization: Bearer $MANAGEMENT_API_ACCESS_TOKEN" +``` + +O crear una aplicación: + +```bash +curl "$TENANT_ENDPOINT/api/applications" \ + -X POST \ + -H "Authorization: Bearer $MANAGEMENT_API_ACCESS_TOKEN" \ + -H "Content-Type: application/json" \ + -d '{ + "name": "Mi aplicación web", + "type": "SPA", + "oidcClientMetadata": { + "redirectUris": ["https://example.com/callback"], + "postLogoutRedirectUris": ["https://example.com"] + } + }' +``` + +En este punto, tu automatización puede continuar con cualquier operación de la Management API, como crear usuarios, aplicaciones, recursos de API, roles, organizaciones, conectores o ajustes de la experiencia de inicio de sesión. + +## Ejemplo de automatización completa \{#full-automation-example} + +El siguiente ejemplo en Node.js crea un tenant, intercambia las credenciales M2M predeterminadas devueltas por un token de acceso de la Management API y lista las aplicaciones en el nuevo tenant: + +```js +const cloudApiEndpoint = 'https://cloud.logto.io'; +const logtoCloudPat = process.env.LOGTO_CLOUD_PAT; + +const createTenantResponse = await fetch(`${cloudApiEndpoint}/api/tenants`, { + method: 'POST', + headers: { + authorization: `Bearer ${logtoCloudPat}`, + 'content-type': 'application/json', + }, + body: JSON.stringify({ + name: 'Mi tenant automatizado', + tag: 'development', + regionName: 'EU', + }), +}); + +if (!createTenantResponse.ok) { + throw new Error(`No se pudo crear el tenant: ${await createTenantResponse.text()}`); +} + +const tenant = await createTenantResponse.json(); +const tenantEndpoint = tenant.indicator; +const { id: appId, secret: appSecret } = tenant.defaultApplication; + +const tokenResponse = await fetch(`${tenantEndpoint}/oidc/token`, { + method: 'POST', + headers: { + authorization: `Basic ${Buffer.from(`${appId}:${appSecret}`).toString('base64')}`, + 'content-type': 'application/x-www-form-urlencoded', + }, + body: new URLSearchParams({ + grant_type: 'client_credentials', + resource: `${tenantEndpoint}/api`, + scope: 'all', + }), +}); + +if (!tokenResponse.ok) { + throw new Error( + `No se pudo obtener el token de la Management API: ${await tokenResponse.text()}` + ); +} + +const { access_token: managementApiAccessToken } = await tokenResponse.json(); + +const applicationsResponse = await fetch(`${tenantEndpoint}/api/applications`, { + headers: { + authorization: `Bearer ${managementApiAccessToken}`, + }, +}); + +if (!applicationsResponse.ok) { + throw new Error(`No se pudo listar las aplicaciones: ${await applicationsResponse.text()}`); +} + +const applications = await applicationsResponse.json(); + +console.log({ tenantId: tenant.id, applications }); +``` + +## Recursos relacionados \{#related-resources} + +- [Personal access token](/user-management/personal-access-token) +- [Interactuar con la Management API](/integrate-logto/interact-with-management-api) +- [Inicio rápido máquina a máquina](/quick-starts/m2m) diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/integrate-logto/protected-app.mdx b/i18n/fr/docusaurus-plugin-content-docs/current/integrate-logto/protected-app.mdx index a93f605c7f4..fd244ca8ba3 100644 --- a/i18n/fr/docusaurus-plugin-content-docs/current/integrate-logto/protected-app.mdx +++ b/i18n/fr/docusaurus-plugin-content-docs/current/integrate-logto/protected-app.mdx @@ -1,78 +1,78 @@ --- -description: Ajoutez facilement une authentification sans code à vos applications web avec l'application protégée innovante de Logto, propulsée par Cloudflare. Prend en charge l'authentification HTTP Basic et la validation des JWT. -sidebar_label: Application protégée +description: Ajoutez facilement une authentification sans code à vos applications web grâce à l’innovant Protected App de Logto, propulsé par Cloudflare. Prend en charge l’authentification HTTP Basic et la validation JWT. +sidebar_label: Protected App sidebar_position: 2 --- -# Application protégée — Intégration d'authentification sans SDK +# Protected App — Intégration d’authentification sans SDK -L'application protégée est conçue pour éliminer la complexité des [intégrations SDK](/quick-starts) en séparant la couche d'[authentification](https://auth.wiki/authentication) de votre application. Nous gérons l'authentification, vous permettant de vous concentrer sur votre fonctionnalité principale. Une fois qu'un utilisateur est authentifié, l'application protégée sert le contenu de votre serveur. +Le Protected App est conçu pour éliminer la complexité des [intégrations SDK](/quick-starts) en séparant la couche d’[authentification](https://auth.wiki/authentication) de votre application. Nous gérons l’authentification, vous permettant de vous concentrer sur votre fonctionnalité principale. Une fois l’utilisateur authentifié, le Protected App sert le contenu depuis votre serveur. -## Comment fonctionne l'application protégée \{#how-protected-app-works} +## Fonctionnement du Protected App \{#how-protected-app-works} -L'application protégée, propulsée par Cloudflare, fonctionne globalement sur des réseaux de périphérie, garantissant une faible latence et une haute disponibilité pour votre application. +Le Protected App, propulsé par Cloudflare, fonctionne globalement sur des réseaux edge, garantissant une faible latence et une haute disponibilité pour votre application. -L'application protégée maintient l'état de la session et les informations utilisateur. Si un utilisateur n'est pas authentifié, l'application protégée le redirige vers la page de connexion. Une fois authentifié, l'application protégée enveloppe la requête de l'utilisateur avec des informations d'authentification et d'utilisateur, puis la transmet au serveur d'origine. +Le Protected App maintient l’état de session et les informations utilisateur. Si un utilisateur n’est pas authentifié, le Protected App le redirige vers la page de connexion. Une fois authentifié, le Protected App encapsule la requête de l’utilisateur avec les informations d’authentification et d’utilisateur, puis la transmet au serveur d’origine. Ce processus est visualisé dans le diagramme de flux suivant : ```mermaid graph LR - A("Client
(Navigateur)") -->|Requête| B(Logto
Application protégée) - B --> Condition{{Route
correspondante ?}} + A("Client
(Navigateur)") -->|Requête| B(Logto
Protected App) + B --> Condition{{La route
correspond ?}} Condition -->|Oui| Matched{{Est authentifié ?}} - Matched -->|Oui| C(Serveur d'origine) + Matched -->|Oui| C(Serveur d’origine) Matched -->|Non| D(Connexion Logto) Condition -->|Non| C ``` -## Protégez votre serveur d'origine \{#protect-your-origin-server} +## Protéger votre serveur d’origine \{#protect-your-origin-server} -Le serveur d'origine, qui peut être un appareil physique ou virtuel non détenu par l'application protégée de Logto, est l'endroit où réside le contenu de votre application. Semblable à un serveur de réseau de distribution de contenu (CDN), l'application protégée gère les processus d'authentification et récupère le contenu de votre serveur d'origine. Par conséquent, si les utilisateurs accèdent directement à votre serveur d'origine, ils peuvent contourner l'authentification et votre application n'est plus protégée. +Le serveur d’origine, qui peut être un appareil physique ou virtuel non détenu par le Protected App de Logto, est l’endroit où réside le contenu de votre application. À l’instar d’un serveur de Content Delivery Network (CDN), le Protected App gère les processus d’authentification et récupère le contenu depuis votre serveur d’origine. Par conséquent, si des utilisateurs accèdent directement à votre serveur d’origine, ils peuvent contourner l’authentification et votre application n’est plus protégée. -Il est donc important de sécuriser les connexions d'origine, cela empêche les attaquants de découvrir et d'accéder à votre serveur d'origine sans authentification. Il existe plusieurs façons de le faire : +Il est donc important de sécuriser les connexions à l’origine, cela empêche les attaquants de découvrir et d’accéder à votre serveur d’origine sans authentification. Il existe plusieurs façons de le faire : -1. Validation des en-têtes HTTP -2. Validation des JSON Web Tokens (JWT) +1. Validation d’en-tête HTTP +2. Validation de JSON Web Tokens (JWT) -### Validation des en-têtes HTTP \{#http-header-validation} +### Validation d’en-tête HTTP \{#http-header-validation} -Sécuriser votre serveur d'origine peut être réalisé en utilisant [l'authentification HTTP Basic](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication#basic_authentication_scheme) pour sécuriser votre serveur d'origine. +Sécuriser votre serveur d’origine peut se faire en utilisant [l’authentification HTTP Basic](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication#basic_authentication_scheme). -Chaque requête de l'application protégée inclut l'en-tête suivant : +Chaque requête provenant du Protected App inclut l’en-tête suivant : ``` Authorization: Basic base64(appId:appSecret) ``` -En validant cet en-tête, vous pouvez confirmer que la requête provient de l'application protégée et refuser toute requête qui n'inclut pas cet en-tête. +En validant cet en-tête, vous pouvez confirmer que la requête provient du Protected App et refuser toute requête ne comportant pas cet en-tête. -Si vous utilisez Nginx ou Apache, vous pouvez vous référer aux guides suivants pour implémenter l'authentification HTTP Basic sur votre serveur d'origine : +Si vous utilisez Nginx ou Apache, vous pouvez consulter les guides suivants pour mettre en place l’authentification HTTP Basic sur votre serveur d’origine : -1. Nginx : [Configurer l'authentification HTTP Basic](https://docs.nginx.com/nginx/admin-guide/security-controls/configuring-http-basic-authentication/) -2. Apache : [Authentification et autorisation](https://httpd.apache.org/docs/2.4/howto/auth.html) +1. Nginx : [Configurer l’authentification HTTP Basic](https://docs.nginx.com/nginx/admin-guide/security-controls/configuring-http-basic-authentication/) +2. Apache : [Authentification et Autorisation](https://httpd.apache.org/docs/2.4/howto/auth.html) -Pour vérifier les en-têtes au sein de votre application, consultez l'[exemple d'authentification HTTP Basic](https://developers.cloudflare.com/workers/examples/basic-auth/) fourni par Cloudflare pour apprendre à restreindre l'accès en utilisant le schéma HTTP Basic. +Pour vérifier les en-têtes dans votre application, consultez l’[exemple d’authentification HTTP Basic](https://developers.cloudflare.com/workers/examples/basic-auth/) fourni par Cloudflare pour apprendre à restreindre l’accès à l’aide du schéma HTTP Basic. -### Validation des JSON Web Tokens (JWT) \{#json-web-tokens-jwt-validation} +### Validation de JSON Web Tokens (JWT) \{#json-web-tokens-jwt-validation} -Une autre façon de sécuriser votre serveur d'origine est d'utiliser les JSON Web Tokens (JWT). +Une autre façon de sécuriser votre serveur d’origine est d’utiliser des JSON Web Tokens (JWT). -Chaque requête authentifiée de l'application protégée inclut l'en-tête suivant : +Chaque requête authentifiée provenant du Protected App inclut l’en-tête suivant : ``` Logto-ID-Token: ``` -Le JWT est appelé [Jeton d’identifiant (ID Token)](https://auth.wiki/id-token) qui est signé par Logto et contient des informations utilisateur. En validant ce JWT, vous pouvez confirmer que la requête provient de l'application protégée et refuser toute requête qui n'inclut pas cet en-tête. +Le JWT est appelé [Jeton d’identifiant (ID Token)](https://auth.wiki/id-token) qui est signé par Logto et contient des informations utilisateur. En validant ce JWT, vous pouvez confirmer que la requête provient du Protected App et refuser toute requête ne comportant pas cet en-tête. -Le jeton est crypté et signé en tant que jeton [JWS](https://auth.wiki/jws). +Le jeton est chiffré et signé en tant que jeton [JWS](https://auth.wiki/jws). Les étapes de validation : -1. [Validation d'un JWT](https://datatracker.ietf.org/doc/html/rfc7519#section-7.2) -2. [Validation de la signature JWS](https://datatracker.ietf.org/doc/html/rfc7515#section-5.2) -3. L'émetteur du jeton est `https:///oidc` (émis par votre serveur d'authentification Logto) +1. [Valider un JWT](https://datatracker.ietf.org/doc/html/rfc7519#section-7.2) +2. [Valider la signature JWS](https://datatracker.ietf.org/doc/html/rfc7515#section-5.2) +3. L’émetteur du jeton est `https:///oidc` (émis par votre serveur d’auth Logto) ```js const express = require('express'); @@ -95,7 +95,7 @@ const getKey = (header, callback) => { const verifyToken = (req, res, next) => { const token = req.headers['Logto-ID-Token']; - // Assurez-vous que la requête entrante a notre en-tête de jeton + // Assurez-vous que la requête entrante contient notre en-tête de jeton if (!token) { return res .status(403) @@ -104,7 +104,7 @@ const verifyToken = (req, res, next) => { jwt.verify(token, getKey, { issuer: ISSUER }, (err, decoded) => { if (err) { - return res.status(403).send({ status: false, message: 'jeton d’identifiant invalide' }); + return res.status(403).send({ status: false, message: 'jeton id invalide' }); } req.user = decoded; @@ -123,11 +123,11 @@ app.get('/', (req, res) => { app.listen(3000); ``` -## Obtenez l'état d'authentification et les informations utilisateur \{#get-authentication-state-and-user-information} +## Obtenir l’état d’authentification et les informations utilisateur \{#get-authentication-state-and-user-information} -Si vous avez besoin d'obtenir des informations d'authentification et d'utilisateur pour votre application, vous pouvez également utiliser l'en-tête `Logto-ID-Token`. +Si vous avez besoin d’obtenir l’état d’authentification et les informations utilisateur pour votre application, vous pouvez également utiliser l’en-tête `Logto-ID-Token`. -Si vous souhaitez uniquement décoder le jeton, vous pouvez utiliser le code suivant : +Si vous souhaitez simplement décoder le jeton, vous pouvez utiliser le code suivant : ```js const express = require('express'); @@ -166,36 +166,53 @@ app.get('/', (req, res) => { app.listen(3000); ``` -## Obtenez l'hôte d'origine \{#get-the-original-host} +## Personnaliser les revendications du jeton d’identifiant \{#customize-id-token-claims} -Si vous avez besoin d'obtenir l'hôte d'origine demandé par le client, vous pouvez utiliser l'en-tête `Logto-Host` ou `x-forwarded-host`. +Par défaut, l’en-tête `Logto-ID-Token` inclut les revendications OIDC standard (par exemple `sub`, `name` et `email`). Pour inclure des [revendications étendues](/developers/custom-id-token#extended-claims) telles que les rôles ou les données d’organisation, les deux éléments suivants doivent être configurés : -## Personnalisez les règles d'authentification \{#customize-authentication-rules} +1. **Bascule du locataire** : Activez la revendication dans Console > Custom JWT > Jeton d’identifiant. +2. **Scopes du Protected App** : Dans les paramètres de votre Protected App, sélectionnez la portée correspondante sous **Revendications du jeton d’identifiant** > **Scopes supplémentaires**. -Par défaut, l'application protégée protégera toutes les routes. Si vous avez besoin de personnaliser les règles d'authentification, vous pouvez définir le champ "Règles d'authentification personnalisées" dans la Console. +Les revendications étendues sont incluses dans le jeton d’identifiant transmis uniquement lorsque la revendication est activée dans Custom JWT et que la portée correspondante est sélectionnée pour le Protected App. Voir [Jeton d’identifiant personnalisé](/developers/custom-id-token) pour la liste complète des scopes et revendications étendus. -Il prend en charge les expressions régulières, voici deux scénarios : +| Portée | Revendications | +| ------------------------------------ | ------------------------------------ | +| `custom_data` | `custom_data` | +| `identities` | `identities`, `sso_identities` | +| `roles` | `roles` | +| `urn:logto:scope:organizations` | `organizations`, `organization_data` | +| `urn:logto:scope:organization_roles` | `organization_roles` | -1. Pour protéger uniquement les routes `/admin` et `/privacy` avec authentification : `^/(admin|privacy)/.*` -2. Pour exclure les images JPG de l'authentification : `^(?!.*\.jpg$).*$` +## Obtenir l’hôte d’origine \{#get-the-original-host} + +Si vous avez besoin d’obtenir l’hôte d’origine demandé par le client, vous pouvez utiliser l’en-tête `Logto-Host` ou `x-forwarded-host`. + +## Personnaliser les règles d’authentification \{#customize-authentication-rules} + +Par défaut, le Protected App protège toutes les routes. Si vous souhaitez personnaliser les règles d’authentification, vous pouvez définir le champ "Règles d’authentification personnalisées" dans la Console. + +Les expressions régulières sont prises en charge, voici deux scénarios d’exemple : + +1. Pour ne protéger que les routes `/admin` et `/privacy` avec authentification : `^/(admin|privacy)/.*` +2. Pour exclure les images JPG de l’authentification : `^(?!.*\.jpg$).*$` ## Développement local \{#local-development} -L'application protégée est conçue pour fonctionner avec votre serveur d'origine. Cependant, si votre serveur d'origine n'est pas accessible publiquement, vous pouvez utiliser un outil comme [ngrok](https://ngrok.com/) ou [Cloudflare Tunnels](https://developers.cloudflare.com/pages/how-to/preview-with-cloudflare-tunnel/) pour exposer votre serveur local à Internet. +Le Protected App est conçu pour fonctionner avec votre serveur d’origine. Cependant, si votre serveur d’origine n’est pas accessible publiquement, vous pouvez utiliser un outil comme [ngrok](https://ngrok.com/) ou [Cloudflare Tunnels](https://developers.cloudflare.com/pages/how-to/preview-with-cloudflare-tunnel/) pour exposer votre serveur local à Internet. -## Transition vers l'intégration SDK \{#transition-to-sdk-integration} +## Transition vers une intégration SDK \{#transition-to-sdk-integration} -L'application protégée est conçue pour simplifier le processus d'authentification. Cependant, si vous décidez de passer à l'intégration SDK pour un meilleur contrôle et une personnalisation accrue, vous pouvez [créer une nouvelle application](/integrate-logto/integrate-logto-into-your-application) dans Logto et configurer l'[intégration SDK](/quick-starts). Et pour une transition en douceur, vous pouvez réutiliser les configurations d'application de l'application protégée. L'application protégée est en fait une "Application Web Traditionnelle" dans Logto, vous pouvez trouver l'["AppId"](/integrate-logto/application-data-structure#application-id) et l'["AppSecret"](/integrate-logto/application-data-structure#application-secret) dans les paramètres de l'application. Une fois la transition terminée, vous pouvez supprimer l'application protégée de votre application. +Le Protected App est conçu pour simplifier le processus d’authentification. Cependant, si vous décidez de passer à une intégration SDK pour un meilleur contrôle et une personnalisation accrue, vous pouvez [créer une nouvelle application](/integrate-logto/integrate-logto-into-your-application) dans Logto et configurer l’[intégration SDK](/quick-starts). Pour une transition en douceur, vous pouvez réutiliser les configurations d’application du Protected App. Le Protected App est en réalité une "Application Web Traditionnelle" dans Logto, vous pouvez trouver l’"[AppId](/integrate-logto/application-data-structure#application-id)" et l’"[AppSecret](/integrate-logto/application-data-structure#application-secret)" dans les paramètres de l’application. Une fois la transition terminée, vous pouvez retirer le Protected App de votre application. ## Ressources associées \{#related-resources} - Application protégée : Construisez l'authentification de votre application en quelques clics. - Aucun code requis. + Protected App : Construisez l’authentification de votre application en quelques clics. Aucun code + requis. -La motivation derrière l'application protégée +La motivation derrière Protected App - La façon la plus rapide de construire un système d'authentification + La manière la plus rapide de construire un système d’authentification diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/logto-cloud/README.mdx b/i18n/fr/docusaurus-plugin-content-docs/current/logto-cloud/README.mdx index bafed92d808..3cea89be7c2 100644 --- a/i18n/fr/docusaurus-plugin-content-docs/current/logto-cloud/README.mdx +++ b/i18n/fr/docusaurus-plugin-content-docs/current/logto-cloud/README.mdx @@ -3,14 +3,15 @@ import Developer from '@site/src/assets/developer.svg'; import TenantMemberManagement from '@site/src/assets/gear.svg'; import PricingAndBilling from '@site/src/assets/key.svg'; import McpIcon from '@site/src/assets/mcp.svg'; +import TenantAutomation from '@site/src/assets/robot.svg'; import CustomDomains from '@site/src/assets/search.svg'; import SystemLimit from '@site/src/assets/security.svg'; # Logto Cloud -[Logto Cloud](https://cloud.logto.io) propose une gamme de services de gestion et d'exploitation pour vous aider à gérer les identités et les ressources de manière fluide et simple. Hébergé par Logto, il inclut des fonctionnalités telles que [prise en charge multi-régions](/logto-cloud/tenant-settings#tenant-region), gestion des locataires, [facturation et tarification](/logto-cloud/billing-and-pricing), [gestion des membres](/logto-cloud/tenant-member-management) et contrôle d’accès basé sur les rôles dans la console. +[Logto Cloud](https://cloud.logto.io) propose une gamme de services de gestion et d'exploitation pour vous aider à gérer les identités et les ressources de manière fluide et simple. Hébergé par Logto, il inclut des fonctionnalités telles que [prise en charge multi-régions](/logto-cloud/tenant-settings#tenant-region), gestion des tenants, [facturation et tarification](/logto-cloud/billing-and-pricing), [gestion des membres](/logto-cloud/tenant-member-management) et contrôle d’accès basé sur les rôles (RBAC) pour la console. -Si vous avez des questions concernant les services cloud et avez besoin d’un support supplémentaire, veuillez nous contacter. +Si vous avez des questions concernant les services cloud et avez besoin d'un support supplémentaire, veuillez nous contacter. ## Fonctionnalités du service cloud \{#features-for-cloud-service} @@ -18,30 +19,30 @@ Si vous avez des questions concernant les services cloud et avez besoin d’un s items={[ { type: 'link', - label: 'Paramètres du locataire', + label: 'Paramètres du tenant', href: '/logto-cloud/tenant-settings', description: - 'Mettez à jour ou modifiez le nom du locataire, vérifiez les régions et supprimez ou quittez le locataire.', + 'Mettez à jour ou modifiez le nom du tenant, vérifiez les régions et supprimez ou quittez le tenant.', customProps: { icon: , }, }, { type: 'link', - label: 'Politique de conservation des données du locataire de développement', + label: 'Politique de conservation des données du tenant de développement', href: '/logto-cloud/dev-tenant-data-retention', description: - 'Comprenez la politique de conservation des utilisateurs sur 90 jours pour les locataires de développement et comment utiliser efficacement un locataire de développement Logto.', + 'Comprenez la politique de conservation des utilisateurs sur 90 jours pour le tenant de développement et comment utiliser efficacement le tenant de développement Logto.', customProps: { icon: , }, }, { type: 'link', - label: 'Gestion des membres du locataire', + label: 'Gestion des membres du tenant', href: '/logto-cloud/tenant-member-management', description: - 'L’administrateur du locataire peut inviter et gérer les membres et mettre à jour leurs rôles.', + 'L’administrateur du tenant peut inviter et gérer les membres et mettre à jour leurs rôles.', customProps: { icon: , }, @@ -51,7 +52,7 @@ Si vous avez des questions concernant les services cloud et avez besoin d’un s label: 'Domaines personnalisés', href: '/logto-cloud/custom-domain', description: - 'Utilisez votre propre domaine pour votre locataire Logto afin de garantir la cohérence de la marque dans l’expérience utilisateur finale.', + 'Utilisez votre propre domaine pour votre tenant Logto afin de garder une expérience utilisateur cohérente avec votre marque.', customProps: { icon: , }, @@ -71,11 +72,21 @@ Si vous avez des questions concernant les services cloud et avez besoin d’un s label: 'Limite du système', href: '/logto-cloud/system-limit', description: - 'Comprenez les limites du système et la protection contre les dépassements pour les locataires Dev, Pro et Enterprise.', + 'Comprenez les limites du système et la protection contre les dépassements de quotas pour les tenants Dev, Pro et Enterprise.', customProps: { icon: , }, }, + { + type: 'link', + label: 'Automatiser la gestion des tenants', + href: '/logto-cloud/automate-tenant-creation', + description: + 'Créez et gérez des tenants de manière programmatique avec Logto Cloud API et Management API.', + customProps: { + icon: , + }, + }, { type: 'link', label: 'Logto MCP Server', diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/logto-cloud/automate-tenant-creation.mdx b/i18n/fr/docusaurus-plugin-content-docs/current/logto-cloud/automate-tenant-creation.mdx new file mode 100644 index 00000000000..414d90a018e --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/logto-cloud/automate-tenant-creation.mdx @@ -0,0 +1,245 @@ +--- +id: automate-tenant-creation +title: Automatiser la gestion des locataires +sidebar_position: 8 +--- + +# Automatiser la gestion des locataires + +Vous pouvez gérer les locataires Logto Cloud de manière programmatique, y compris créer des locataires et poursuivre la configuration sans passer par la Console. + +Ceci est utile lorsque vous devez approvisionner des locataires depuis votre propre parcours d'intégration, une plateforme interne, un agent IA ou une automatisation d'intégration. + +Le flux d'automatisation est le suivant : + +1. Utilisez un **Logto Cloud Personal Access Token (PAT)** pour appeler l'API Logto Cloud. +2. Créez un locataire avec `POST /api/tenants`. +3. Lisez les identifiants de l'application machine à machine (M2M) par défaut dans la réponse de création. +4. Utilisez l'application M2M par défaut pour obtenir un jeton d’accès Management API pour le nouveau locataire. +5. Appelez la Management API du nouveau locataire pour continuer l'approvisionnement des applications, utilisateurs, rôles, ressources, organisations et autres paramètres. + +## Avant de commencer \{#before-you-start} + +Préparez les valeurs suivantes : + +| Variable | Description | +| -------------------- | -------------------------------------------------------------------------------------------------- | +| `CLOUD_API_ENDPOINT` | Le point de terminaison de l'API Logto Cloud. Pour Logto Cloud, utilisez `https://cloud.logto.io`. | +| `LOGTO_CLOUD_PAT` | Un PAT pour votre compte Logto Cloud. | +| `TENANT_NAME` | Le nom d'affichage du locataire à créer. | +| `TENANT_TAG` | Le type de locataire. Utilisez `development` ou `production`. | +| `REGION_NAME` | L'identifiant de la région pour le locataire. | + +Définissez-les comme variables d'environnement : + +```bash +export CLOUD_API_ENDPOINT="https://cloud.logto.io" +export LOGTO_CLOUD_PAT="" +export TENANT_NAME="Mon locataire automatisé" +export TENANT_TAG="development" +export REGION_NAME="" +``` + +## Obtenir les régions disponibles \{#get-available-regions} + +Avant de créer un locataire, récupérez les régions disponibles pour votre compte Logto Cloud : + +```bash +curl "$CLOUD_API_ENDPOINT/api/me/regions" \ + -H "Authorization: Bearer $LOGTO_CLOUD_PAT" +``` + +La réponse contient les régions disponibles. Utilisez la valeur `name` comme `REGION_NAME` lors de la création du locataire. + +Exemple de réponse : + +```json +{ + "regions": [ + { + "name": "EU", + "displayName": "Europe" + }, + { + "name": "US", + "displayName": "United States" + } + ] +} +``` + +## Créer un locataire \{#create-a-tenant} + +Appelez `POST /api/tenants` avec le PAT Logto Cloud : + +```bash +curl "$CLOUD_API_ENDPOINT/api/tenants" \ + -X POST \ + -H "Authorization: Bearer $LOGTO_CLOUD_PAT" \ + -H "Content-Type: application/json" \ + -d '{ + "name": "'"$TENANT_NAME"'", + "tag": "'"$TENANT_TAG"'", + "regionName": "'"$REGION_NAME"'" + }' +``` + +La réponse inclut le locataire créé et une application M2M par défaut. L'application M2M est créée dans le nouveau locataire et a accès à la Management API du locataire. + +Exemple de réponse : + +```json +{ + "id": "new-tenant-id", + "name": "Mon locataire automatisé", + "tag": "development", + "indicator": "https://new-tenant-id.logto.app", + "regionName": "EU", + "defaultApplication": { + "id": "default-m2m-app-id", + "secret": "default-m2m-app-secret" + } +} +``` + +Enregistrez les valeurs nécessaires pour l'étape suivante : + +```bash +export TENANT_ID="" +export TENANT_ENDPOINT="" +export DEFAULT_M2M_APP_ID="" +export DEFAULT_M2M_APP_SECRET="" +``` + +## Obtenir un jeton d’accès Management API pour le nouveau locataire \{#get-a-management-api-access-token-for-the-new-tenant} + +Utilisez les identifiants de l'application M2M par défaut pour demander un jeton d’accès auprès du nouveau locataire : + +```bash +curl "$TENANT_ENDPOINT/oidc/token" \ + -X POST \ + -u "$DEFAULT_M2M_APP_ID:$DEFAULT_M2M_APP_SECRET" \ + -H "Content-Type: application/x-www-form-urlencoded" \ + -d "grant_type=client_credentials" \ + -d "resource=$TENANT_ENDPOINT/api" \ + -d "scope=all" +``` + +Exemple de réponse : + +```json +{ + "access_token": "eyJ...", + "expires_in": 3600, + "token_type": "Bearer", + "scope": "all" +} +``` + +Enregistrez le jeton d’accès : + +```bash +export MANAGEMENT_API_ACCESS_TOKEN="" +``` + +## Continuer l'approvisionnement du nouveau locataire \{#continue-provisioning-the-new-tenant} + +Utilisez le jeton d’accès Management API pour appeler la Management API du nouveau locataire. + +Par exemple, lister les applications : + +```bash +curl "$TENANT_ENDPOINT/api/applications" \ + -H "Authorization: Bearer $MANAGEMENT_API_ACCESS_TOKEN" +``` + +Ou créer une application : + +```bash +curl "$TENANT_ENDPOINT/api/applications" \ + -X POST \ + -H "Authorization: Bearer $MANAGEMENT_API_ACCESS_TOKEN" \ + -H "Content-Type: application/json" \ + -d '{ + "name": "Mon application web", + "type": "SPA", + "oidcClientMetadata": { + "redirectUris": ["https://example.com/callback"], + "postLogoutRedirectUris": ["https://example.com"] + } + }' +``` + +À ce stade, votre automatisation peut continuer avec n'importe quelle opération Management API, comme la création d'utilisateurs, d'applications, de ressources API, de rôles, d'organisations, de connecteurs ou de paramètres d'expérience de connexion. + +## Exemple d'automatisation complète \{#full-automation-example} + +L'exemple Node.js suivant crée un locataire, échange les identifiants M2M par défaut retournés contre un jeton d’accès Management API, et liste les applications du nouveau locataire : + +```js +const cloudApiEndpoint = 'https://cloud.logto.io'; +const logtoCloudPat = process.env.LOGTO_CLOUD_PAT; + +// Créer un locataire +const createTenantResponse = await fetch(`${cloudApiEndpoint}/api/tenants`, { + method: 'POST', + headers: { + authorization: `Bearer ${logtoCloudPat}`, + 'content-type': 'application/json', + }, + body: JSON.stringify({ + name: 'Mon locataire automatisé', + tag: 'development', + regionName: 'EU', + }), +}); + +if (!createTenantResponse.ok) { + throw new Error(`Échec de la création du locataire : ${await createTenantResponse.text()}`); +} + +const tenant = await createTenantResponse.json(); +const tenantEndpoint = tenant.indicator; +const { id: appId, secret: appSecret } = tenant.defaultApplication; + +// Obtenir un jeton d’accès Management API +const tokenResponse = await fetch(`${tenantEndpoint}/oidc/token`, { + method: 'POST', + headers: { + authorization: `Basic ${Buffer.from(`${appId}:${appSecret}`).toString('base64')}`, + 'content-type': 'application/x-www-form-urlencoded', + }, + body: new URLSearchParams({ + grant_type: 'client_credentials', + resource: `${tenantEndpoint}/api`, + scope: 'all', + }), +}); + +if (!tokenResponse.ok) { + throw new Error(`Échec de l'obtention du jeton Management API : ${await tokenResponse.text()}`); +} + +const { access_token: managementApiAccessToken } = await tokenResponse.json(); + +// Lister les applications +const applicationsResponse = await fetch(`${tenantEndpoint}/api/applications`, { + headers: { + authorization: `Bearer ${managementApiAccessToken}`, + }, +}); + +if (!applicationsResponse.ok) { + throw new Error(`Échec de la liste des applications : ${await applicationsResponse.text()}`); +} + +const applications = await applicationsResponse.json(); + +console.log({ tenantId: tenant.id, applications }); +``` + +## Ressources associées \{#related-resources} + +- [Jeton d’accès personnel](/user-management/personal-access-token) +- [Interagir avec Management API](/integrate-logto/interact-with-management-api) +- [Démarrage rapide machine à machine](/quick-starts/m2m) diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/integrate-logto/protected-app.mdx b/i18n/ja/docusaurus-plugin-content-docs/current/integrate-logto/protected-app.mdx index 5dec09d261f..7ca796e9395 100644 --- a/i18n/ja/docusaurus-plugin-content-docs/current/integrate-logto/protected-app.mdx +++ b/i18n/ja/docusaurus-plugin-content-docs/current/integrate-logto/protected-app.mdx @@ -1,78 +1,78 @@ --- -description: Logto の革新的な Protected App を使用して、Cloudflare によって強化されたノーコード認証 (Authentication) を Web アプリに簡単に追加します。HTTP Basic 認証 (Authentication) と JWT 検証をサポートします。 +description: Logto の革新的な Protected App(Cloudflare により提供)を使って、ノーコードで Web アプリに簡単に認証 (Authentication) を追加できます。HTTP Basic 認証 (Authentication) と JWT 検証に対応。 sidebar_label: Protected App sidebar_position: 2 --- -# Protected App — 非 SDK 認証 (Authentication) 統合 +# Protected App — SDK を使わない認証 (Authentication) 統合 -Protected App は、アプリケーションから [認証 (Authentication)](https://auth.wiki/authentication) レイヤーを分離することで、[SDK 統合](/quick-starts) の複雑さを排除するように設計されています。私たちは認証 (Authentication) を処理し、あなたはコア機能に集中できます。ユーザーが認証 (Authentication) されると、Protected App はサーバーからコンテンツを提供します。 +Protected App は、[SDK 統合](/quick-starts) の複雑さを排除し、[認証 (Authentication)](https://auth.wiki/authentication) レイヤーをアプリケーションから分離するために設計されています。認証 (Authentication) は当社が処理するため、コア機能に集中できます。ユーザーが認証 (Authentication) されると、Protected App がサーバーからコンテンツを配信します。 -## Protected App の動作 \{#how-protected-app-works} +## Protected App の仕組み \{#how-protected-app-works} -Cloudflare によって強化された Protected App は、エッジネットワーク上でグローバルに動作し、アプリケーションに低遅延と高可用性を保証します。 +Cloudflare により提供される Protected App は、グローバルなエッジネットワーク上で動作し、アプリケーションに低遅延かつ高可用性を実現します。 -Protected App はセッション状態とユーザー情報を保持します。ユーザーが認証 (Authentication) されていない場合、Protected App はサインインページにリダイレクトします。認証 (Authentication) されると、Protected App はユーザーのリクエストを認証 (Authentication) とユーザー情報でラップし、それをオリジンサーバーに転送します。 +Protected App はセッション状態とユーザー情報を管理します。ユーザーが認証 (Authentication) されていない場合、Protected App はサインインページへリダイレクトします。認証 (Authentication) 後、Protected App はユーザーのリクエストに認証 (Authentication) とユーザー情報を付与し、オリジンサーバーへ転送します。 -このプロセスは次のフローチャートで視覚化されています: +このプロセスは以下のフローチャートで視覚化されています: ```mermaid graph LR A("クライアント
(ブラウザ)") -->|リクエスト| B(Logto
Protected App) B --> Condition{{ルート
一致?}} - Condition -->|はい| Matched{{認証 (Authentication) 済み?}} + Condition -->|はい| Matched{{認証済み?}} Matched -->|はい| C(オリジンサーバー) Matched -->|いいえ| D(Logto サインイン) Condition -->|いいえ| C ``` -## オリジンサーバーを保護する \{#protect-your-origin-server} +## オリジンサーバーの保護 \{#protect-your-origin-server} -オリジンサーバーは、Logto の Protected App が所有していない物理または仮想デバイスであり、アプリケーションコンテンツが存在する場所です。コンテンツデリバリーネットワーク (CDN) サーバーと同様に、Protected App は認証 (Authentication) プロセスを管理し、オリジンサーバーからコンテンツを取得します。したがって、ユーザーがオリジンサーバーに直接アクセスできる場合、認証 (Authentication) をバイパスでき、アプリケーションはもはや保護されません。 +オリジンサーバーは、物理または仮想デバイスであり、Logto の Protected App が所有しない場合もあります。アプリケーションのコンテンツはここに存在します。CDN サーバーと同様に、Protected App は認証 (Authentication) 処理を管理し、オリジンサーバーからコンテンツを取得します。そのため、ユーザーがオリジンサーバーへ直接アクセスできる場合、認証 (Authentication) をバイパスでき、アプリケーションは保護されなくなります。 -したがって、オリジン接続を保護することが重要です。これにより、攻撃者が認証 (Authentication) なしでオリジンサーバーを発見しアクセスするのを防ぎます。これを行う方法はいくつかあります: +したがって、オリジン接続のセキュリティ確保は重要です。これにより、攻撃者が認証 (Authentication) なしでオリジンサーバーを発見・アクセスすることを防げます。主な方法は以下の通りです: 1. HTTP ヘッダー検証 2. JSON Web Token (JWT) 検証 ### HTTP ヘッダー検証 \{#http-header-validation} -オリジンサーバーを保護するために、[HTTP Basic 認証 (Authentication)](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication#basic_authentication_scheme) を使用してオリジンサーバーを保護できます。 +[HTTP Basic 認証 (Authentication)](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication#basic_authentication_scheme) を利用してオリジンサーバーを保護できます。 -Protected App からの各リクエストには次のヘッダーが含まれています: +Protected App からの各リクエストには、次のヘッダーが含まれます: ``` Authorization: Basic base64(appId:appSecret) ``` -このヘッダーを検証することで、リクエストが Protected App からのものであることを確認し、このヘッダーを含まないリクエストを拒否できます。 +このヘッダーを検証することで、リクエストが Protected App からのものであることを確認し、このヘッダーが含まれないリクエストを拒否できます。 -Nginx または Apache を使用している場合、オリジンサーバーで HTTP Basic 認証 (Authentication) を実装するための次のガイドを参照できます: +Nginx や Apache を利用している場合、オリジンサーバーで HTTP Basic 認証 (Authentication) を実装するには以下のガイドを参照してください: 1. Nginx: [HTTP Basic 認証 (Authentication) の設定](https://docs.nginx.com/nginx/admin-guide/security-controls/configuring-http-basic-authentication/) 2. Apache: [認証 (Authentication) と認可 (Authorization)](https://httpd.apache.org/docs/2.4/howto/auth.html) -アプリケーション内でヘッダーを確認するには、Cloudflare が提供する [HTTP Basic 認証 (Authentication) の例](https://developers.cloudflare.com/workers/examples/basic-auth/) を参照して、HTTP Basic スキーマを使用してアクセスを制限する方法を学んでください。 +アプリケーション内でヘッダーを確認するには、Cloudflare の [HTTP Basic 認証 (Authentication) の例](https://developers.cloudflare.com/workers/examples/basic-auth/) を参照し、HTTP Basic スキーマでアクセス制限する方法を学べます。 ### JSON Web Token (JWT) 検証 \{#json-web-tokens-jwt-validation} -オリジンサーバーを保護するもう一つの方法は、JSON Web Token (JWT) を使用することです。 +もう一つの方法は、JSON Web Token (JWT) を利用してオリジンサーバーを保護することです。 -Protected App からの各認証 (Authentication) 済みリクエストには次のヘッダーが含まれています: +Protected App からの認証済みリクエストには、次のヘッダーが含まれます: ``` Logto-ID-Token: ``` -JWT は [ID トークン](https://auth.wiki/id-token) と呼ばれ、Logto によって署名され、ユーザー情報を含んでいます。この JWT を検証することで、リクエストが Protected App からのものであることを確認し、このヘッダーを含まないリクエストを拒否できます。 +この JWT は [ID トークン (ID token)](https://auth.wiki/id-token) と呼ばれ、Logto により署名され、ユーザー情報が含まれています。この JWT を検証することで、リクエストが Protected App からのものであることを確認し、このヘッダーが含まれないリクエストを拒否できます。 -トークンは [JWS](https://auth.wiki/jws) トークンとして暗号化および署名されています。 +トークンは [JWS](https://auth.wiki/jws) トークンとして暗号化・署名されています。 検証手順: 1. [JWT の検証](https://datatracker.ietf.org/doc/html/rfc7519#section-7.2) 2. [JWS 署名の検証](https://datatracker.ietf.org/doc/html/rfc7515#section-5.2) -3. トークンの発行者は `https:///oidc`(あなたの Logto 認証 (Authentication) サーバーによって発行) +3. トークンの発行者 (Issuer) は `https:///oidc`(Logto 認証 (Authentication) サーバーによる発行) ```js const express = require('express'); @@ -99,12 +99,12 @@ const verifyToken = (req, res, next) => { if (!token) { return res .status(403) - .send({ status: false, message: '必要な Logto-ID-Token ヘッダーがありません' }); + .send({ status: false, message: 'missing required Logto-ID-Token header' }); } jwt.verify(token, getKey, { issuer: ISSUER }, (err, decoded) => { if (err) { - return res.status(403).send({ status: false, message: '無効な ID トークン' }); + return res.status(403).send({ status: false, message: 'invalid id token' }); } req.user = decoded; @@ -123,11 +123,11 @@ app.get('/', (req, res) => { app.listen(3000); ``` -## 認証 (Authentication) 状態とユーザー情報を取得する \{#get-authentication-state-and-user-information} +## 認証 (Authentication) 状態とユーザー情報の取得 \{#get-authentication-state-and-user-information} -アプリケーションの認証 (Authentication) とユーザー情報を取得する必要がある場合、`Logto-ID-Token` ヘッダーを使用できます。 +アプリケーションで認証 (Authentication) 状態やユーザー情報を取得したい場合も、`Logto-ID-Token` ヘッダーを利用できます。 -トークンをデコードするだけの場合、次のコードを使用できます: +トークンをデコードするだけでよい場合は、次のコードを利用できます: ```js const express = require('express'); @@ -138,13 +138,13 @@ const decodeIdToken = (req, res, next) => { if (!token) { return res.status(403).send({ status: false, - message: '必要な Logto-ID-Token ヘッダーがありません', + message: 'missing required Logto-ID-Token header', }); } const parts = token.split('.'); if (parts.length !== 3) { - throw new Error('無効な ID トークン'); + throw new Error('Invalid ID token'); } const payload = parts[1]; @@ -166,35 +166,52 @@ app.get('/', (req, res) => { app.listen(3000); ``` -## 元のホストを取得する \{#get-the-original-host} +## ID トークン (ID token) のクレーム (Claims) をカスタマイズ \{#customize-id-token-claims} -クライアントによって要求された元のホストを取得する必要がある場合、`Logto-Host` または `x-forwarded-host` ヘッダーを使用できます。 +デフォルトでは、`Logto-ID-Token` ヘッダーには標準 OIDC クレーム (Claims)(例:`sub`、`name`、`email`)が含まれます。[拡張クレーム (Claims)](/developers/custom-id-token#extended-claims)(ロールや組織データなど)を含めるには、以下の両方の設定が必要です: -## 認証 (Authentication) ルールをカスタマイズする \{#customize-authentication-rules} +1. **テナントのトグル**:Console > Custom JWT > ID token でクレーム (Claims) を有効化。 +2. **Protected App のスコープ**:Protected App の設定で、**ID token claims** > **Additional scopes** から該当スコープを選択。 -デフォルトでは、Protected App はすべてのルートを保護します。認証 (Authentication) ルールをカスタマイズする必要がある場合、Console の「カスタム認証 (Authentication) ルール」フィールドを設定できます。 +拡張クレーム (Claims) は、Custom JWT で有効化され、かつ Protected App で該当スコープが選択されている場合のみ、転送される ID トークン (ID token) に含まれます。拡張スコープとクレーム (Claims) の一覧は [Custom ID token](/developers/custom-id-token) を参照してください。 -正規表現をサポートしており、次のようなケースシナリオがあります: +| Scope | Claims | +| ------------------------------------ | ------------------------------------ | +| `custom_data` | `custom_data` | +| `identities` | `identities`, `sso_identities` | +| `roles` | `roles` | +| `urn:logto:scope:organizations` | `organizations`, `organization_data` | +| `urn:logto:scope:organization_roles` | `organization_roles` | -1. 認証 (Authentication) で `/admin` と `/privacy` のルートのみを保護する:`^/(admin|privacy)/.*` -2. JPG 画像を認証 (Authentication) から除外する:`^(?!.*\.jpg$).*$` +## オリジナルのホストを取得 \{#get-the-original-host} + +クライアントがリクエストした元のホストを取得したい場合、`Logto-Host` または `x-forwarded-host` ヘッダーを利用できます。 + +## 認証 (Authentication) ルールのカスタマイズ \{#customize-authentication-rules} + +デフォルトでは、Protected App はすべてのルートを保護します。認証 (Authentication) ルールをカスタマイズしたい場合は、Console の「Custom authentication rules」フィールドで設定できます。 + +正規表現に対応しており、以下のようなケースがあります: + +1. `/admin` および `/privacy` のみ認証 (Authentication) で保護したい場合:`^/(admin|privacy)/.*` +2. JPG 画像を認証 (Authentication) から除外したい場合:`^(?!.*\.jpg$).*$` ## ローカル開発 \{#local-development} -Protected App はオリジンサーバーと連携するように設計されています。ただし、オリジンサーバーが公開アクセスできない場合、[ngrok](https://ngrok.com/) や [Cloudflare Tunnels](https://developers.cloudflare.com/pages/how-to/preview-with-cloudflare-tunnel/) などのツールを使用してローカルサーバーをインターネットに公開できます。 +Protected App はオリジンサーバーと連携するよう設計されています。ただし、オリジンサーバーが公開されていない場合は、[ngrok](https://ngrok.com/) や [Cloudflare Tunnels](https://developers.cloudflare.com/pages/how-to/preview-with-cloudflare-tunnel/) などのツールを使ってローカルサーバーをインターネットに公開できます。 ## SDK 統合への移行 \{#transition-to-sdk-integration} -Protected App は認証 (Authentication) プロセスを簡素化するように設計されています。ただし、より良いコントロールとカスタマイズのために SDK 統合に移行することを決定した場合、Logto で [新しいアプリケーションを作成](/integrate-logto/integrate-logto-into-your-application) し、[SDK 統合](/quick-starts) を設定できます。スムーズな移行のために、Protected App のアプリケーション設定を再利用できます。Protected App は実際には Logto の「従来の Web アプリ」であり、アプリケーション設定で「[AppId](/integrate-logto/application-data-structure#application-id)」と「[AppSecret](/integrate-logto/application-data-structure#application-secret)」を見つけることができます。移行が完了したら、アプリケーションから Protected App を削除できます。 +Protected App は認証 (Authentication) プロセスを簡素化するために設計されていますが、より細かな制御やカスタマイズのために SDK 統合へ移行したい場合は、Logto で [新しいアプリケーションを作成](/integrate-logto/integrate-logto-into-your-application) し、[SDK 統合](/quick-starts) を設定できます。スムーズな移行のため、Protected App のアプリケーション設定を再利用できます。Protected App は Logto で「Traditional Web App」として扱われており、アプリケーション設定で「[AppId](/integrate-logto/application-data-structure#application-id)」や「[AppSecret](/integrate-logto/application-data-structure#application-secret)」を確認できます。移行完了後は、アプリケーションから Protected App を削除できます。 ## 関連リソース \{#related-resources} - Protected App: クリックでアプリの認証 (Authentication) を構築。コード不要。 + Protected App: 数クリックでアプリの認証 (Authentication) を構築。ノーコードで実現。 -Protected App の背後にある動機 +Protected App の背景と動機 - 認証 (Authentication) システムを構築する最速の方法 + 最速で認証 (Authentication) システムを構築する方法 diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/logto-cloud/README.mdx b/i18n/ja/docusaurus-plugin-content-docs/current/logto-cloud/README.mdx index 13a60e51769..18960a06bb1 100644 --- a/i18n/ja/docusaurus-plugin-content-docs/current/logto-cloud/README.mdx +++ b/i18n/ja/docusaurus-plugin-content-docs/current/logto-cloud/README.mdx @@ -3,14 +3,15 @@ import Developer from '@site/src/assets/developer.svg'; import TenantMemberManagement from '@site/src/assets/gear.svg'; import PricingAndBilling from '@site/src/assets/key.svg'; import McpIcon from '@site/src/assets/mcp.svg'; +import TenantAutomation from '@site/src/assets/robot.svg'; import CustomDomains from '@site/src/assets/search.svg'; import SystemLimit from '@site/src/assets/security.svg'; # Logto Cloud -[Logto Cloud](https://cloud.logto.io) は、アイデンティティやリソースをスムーズかつ簡単に管理できるように、さまざまな管理・運用サービスを提供しています。Logto によってホストされており、[マルチリージョンサポート](/logto-cloud/tenant-settings#tenant-region)、テナント管理、[請求と料金](/logto-cloud/billing-and-pricing)、[メンバー管理](/logto-cloud/tenant-member-management)、およびコンソールのロールベースのアクセス制御などの機能が含まれています。 +[Logto Cloud](https://cloud.logto.io) は、アイデンティティやリソースの管理をスムーズかつ簡単に行うための、さまざまな管理・運用サービスを提供しています。Logto によってホストされており、[マルチリージョンサポート](/logto-cloud/tenant-settings#tenant-region)、テナント管理、[請求と価格](/logto-cloud/billing-and-pricing)、[メンバー管理](/logto-cloud/tenant-member-management)、およびコンソールのロールベースのアクセス制御などの機能が含まれています。 -クラウドサービスに関するご質問や追加サポートが必要な場合は、お問い合わせください。 +クラウドサービスに関してご質問や追加サポートが必要な場合は、お問い合わせください。 ## クラウドサービスの機能 \{#features-for-cloud-service} @@ -30,7 +31,7 @@ import SystemLimit from '@site/src/assets/security.svg'; label: '開発テナントのデータ保持ポリシー', href: '/logto-cloud/dev-tenant-data-retention', description: - '開発テナントの90日間ユーザー保持ポリシーと、Logto 開発テナントの効果的な利用方法について理解できます。', + '開発テナントの 90 日間ユーザー保持ポリシーと、Logto 開発テナントの効果的な利用方法について理解できます。', customProps: { icon: , }, @@ -56,7 +57,7 @@ import SystemLimit from '@site/src/assets/security.svg'; }, { type: 'link', - label: '請求と料金', + label: '請求と価格', href: '/logto-cloud/billing-and-pricing', description: '請求内容を簡単に把握し、自信を持ってサブスクリプションを管理できます。', customProps: { @@ -74,10 +75,20 @@ import SystemLimit from '@site/src/assets/security.svg'; }, { type: 'link', - label: 'Logto MCP サーバー', + label: 'テナント管理の自動化', + href: '/logto-cloud/automate-tenant-creation', + description: + 'Logto Cloud API および Management API を使って、テナントをプログラムで作成・管理できます。', + customProps: { + icon: , + }, + }, + { + type: 'link', + label: 'Logto MCP Server', href: '/logto-cloud/logto-mcp-server', description: - 'AI ツールや IDE を MCP 経由で Logto Cloud に接続し、リソース管理や認証 (Authentication) 連携を実現します。', + 'MCP を通じて AI ツールや IDE を Logto Cloud に接続し、リソース管理や認証 (Authentication) 連携が可能です。', customProps: { icon: , }, diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/logto-cloud/automate-tenant-creation.mdx b/i18n/ja/docusaurus-plugin-content-docs/current/logto-cloud/automate-tenant-creation.mdx new file mode 100644 index 00000000000..24da602d0f2 --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/logto-cloud/automate-tenant-creation.mdx @@ -0,0 +1,242 @@ +--- +id: automate-tenant-creation +title: テナント管理の自動化 +sidebar_position: 8 +--- + +# テナント管理の自動化 + +Logto Cloud テナントはプログラムで管理できます。これにはテナントの作成や、Console に切り替えることなく設定を継続することが含まれます。 + +この機能は、独自のオンボーディングフローや社内プラットフォーム、AI エージェント、統合自動化からテナントをプロビジョニングする必要がある場合に便利です。 + +自動化フローは次の通りです: + +1. **Logto Cloud パーソナルアクセストークン (PAT)** を使って Logto Cloud API を呼び出します。 +2. `POST /api/tenants` でテナントを作成します。 +3. 作成レスポンスからデフォルトのマシン間通信 (M2M) アプリケーションの認証情報を取得します。 +4. デフォルトの M2M アプリケーションを使って新しいテナントの Management API アクセストークンを取得します。 +5. 新しいテナントの Management API を呼び出し、アプリケーション、ユーザー、ロール、リソース、組織、その他の設定のプロビジョニングを継続します。 + +## 始める前に \{#before-you-start} + +以下の値を準備してください: + +| Variable | Description | +| -------------------- | -------------------------------------------------------------------------------------------- | +| `CLOUD_API_ENDPOINT` | Logto Cloud API エンドポイント。Logto Cloud の場合は `https://cloud.logto.io` を使用します。 | +| `LOGTO_CLOUD_PAT` | Logto Cloud アカウント用の PAT。 | +| `TENANT_NAME` | 作成するテナントの表示名。 | +| `TENANT_TAG` | テナントのタイプ。`development` または `production` を使用します。 | +| `REGION_NAME` | テナントのリージョン識別子。 | + +これらを環境変数として設定します: + +```bash +export CLOUD_API_ENDPOINT="https://cloud.logto.io" +export LOGTO_CLOUD_PAT="" +export TENANT_NAME="My automated tenant" +export TENANT_TAG="development" +export REGION_NAME="" +``` + +## 利用可能なリージョンの取得 \{#get-available-regions} + +テナントを作成する前に、Logto Cloud アカウントで利用可能なリージョンを取得します: + +```bash +curl "$CLOUD_API_ENDPOINT/api/me/regions" \ + -H "Authorization: Bearer $LOGTO_CLOUD_PAT" +``` + +レスポンスには利用可能なリージョンが含まれます。テナント作成時には `name` の値を `REGION_NAME` として使用します。 + +レスポンス例: + +```json +{ + "regions": [ + { + "name": "EU", + "displayName": "Europe" + }, + { + "name": "US", + "displayName": "United States" + } + ] +} +``` + +## テナントの作成 \{#create-a-tenant} + +Logto Cloud PAT を使って `POST /api/tenants` を呼び出します: + +```bash +curl "$CLOUD_API_ENDPOINT/api/tenants" \ + -X POST \ + -H "Authorization: Bearer $LOGTO_CLOUD_PAT" \ + -H "Content-Type: application/json" \ + -d '{ + "name": "'"$TENANT_NAME"'", + "tag": "'"$TENANT_TAG"'", + "regionName": "'"$REGION_NAME"'" + }' +``` + +レスポンスには作成されたテナントとデフォルトの M2M アプリケーションが含まれます。M2M アプリケーションは新しいテナント内に作成され、そのテナントの Management API へアクセスできます。 + +レスポンス例: + +```json +{ + "id": "new-tenant-id", + "name": "My automated tenant", + "tag": "development", + "indicator": "https://new-tenant-id.logto.app", + "regionName": "EU", + "defaultApplication": { + "id": "default-m2m-app-id", + "secret": "default-m2m-app-secret" + } +} +``` + +次のステップで必要な値を保存します: + +```bash +export TENANT_ID="" +export TENANT_ENDPOINT="" +export DEFAULT_M2M_APP_ID="" +export DEFAULT_M2M_APP_SECRET="" +``` + +## 新しいテナントの Management API アクセストークンの取得 \{#get-a-management-api-access-token-for-the-new-tenant} + +デフォルトの M2M アプリケーション認証情報を使って、新しいテナントからアクセストークンをリクエストします: + +```bash +curl "$TENANT_ENDPOINT/oidc/token" \ + -X POST \ + -u "$DEFAULT_M2M_APP_ID:$DEFAULT_M2M_APP_SECRET" \ + -H "Content-Type: application/x-www-form-urlencoded" \ + -d "grant_type=client_credentials" \ + -d "resource=$TENANT_ENDPOINT/api" \ + -d "scope=all" +``` + +レスポンス例: + +```json +{ + "access_token": "eyJ...", + "expires_in": 3600, + "token_type": "Bearer", + "scope": "all" +} +``` + +アクセストークンを保存します: + +```bash +export MANAGEMENT_API_ACCESS_TOKEN="" +``` + +## 新しいテナントのプロビジョニングを継続する \{#continue-provisioning-the-new-tenant} + +Management API アクセストークンを使って新しいテナントの Management API を呼び出します。 + +例えば、アプリケーション一覧を取得する場合: + +```bash +curl "$TENANT_ENDPOINT/api/applications" \ + -H "Authorization: Bearer $MANAGEMENT_API_ACCESS_TOKEN" +``` + +またはアプリケーションを作成する場合: + +```bash +curl "$TENANT_ENDPOINT/api/applications" \ + -X POST \ + -H "Authorization: Bearer $MANAGEMENT_API_ACCESS_TOKEN" \ + -H "Content-Type: application/json" \ + -d '{ + "name": "My web app", + "type": "SPA", + "oidcClientMetadata": { + "redirectUris": ["https://example.com/callback"], + "postLogoutRedirectUris": ["https://example.com"] + } + }' +``` + +この時点で、ユーザー、アプリケーション、API リソース、ロール、組織、コネクター、サインイン体験設定など、任意の Management API 操作による自動化を継続できます。 + +## フル自動化例 \{#full-automation-example} + +以下の Node.js 例では、テナントを作成し、返されたデフォルトの M2M 認証情報を Management API アクセストークンに交換し、新しいテナント内のアプリケーション一覧を取得します: + +```js +const cloudApiEndpoint = 'https://cloud.logto.io'; +const logtoCloudPat = process.env.LOGTO_CLOUD_PAT; + +const createTenantResponse = await fetch(`${cloudApiEndpoint}/api/tenants`, { + method: 'POST', + headers: { + authorization: `Bearer ${logtoCloudPat}`, + 'content-type': 'application/json', + }, + body: JSON.stringify({ + name: 'My automated tenant', + tag: 'development', + regionName: 'EU', + }), +}); + +if (!createTenantResponse.ok) { + throw new Error(`Failed to create tenant: ${await createTenantResponse.text()}`); +} + +const tenant = await createTenantResponse.json(); +const tenantEndpoint = tenant.indicator; +const { id: appId, secret: appSecret } = tenant.defaultApplication; + +const tokenResponse = await fetch(`${tenantEndpoint}/oidc/token`, { + method: 'POST', + headers: { + authorization: `Basic ${Buffer.from(`${appId}:${appSecret}`).toString('base64')}`, + 'content-type': 'application/x-www-form-urlencoded', + }, + body: new URLSearchParams({ + grant_type: 'client_credentials', + resource: `${tenantEndpoint}/api`, + scope: 'all', + }), +}); + +if (!tokenResponse.ok) { + throw new Error(`Failed to get Management API token: ${await tokenResponse.text()}`); +} + +const { access_token: managementApiAccessToken } = await tokenResponse.json(); + +const applicationsResponse = await fetch(`${tenantEndpoint}/api/applications`, { + headers: { + authorization: `Bearer ${managementApiAccessToken}`, + }, +}); + +if (!applicationsResponse.ok) { + throw new Error(`Failed to list applications: ${await applicationsResponse.text()}`); +} + +const applications = await applicationsResponse.json(); + +console.log({ tenantId: tenant.id, applications }); +``` + +## 関連リソース \{#related-resources} + +- [パーソナルアクセストークン](/user-management/personal-access-token) +- [Management API との連携](/integrate-logto/interact-with-management-api) +- [マシン間通信クイックスタート](/quick-starts/m2m) diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/integrate-logto/protected-app.mdx b/i18n/ko/docusaurus-plugin-content-docs/current/integrate-logto/protected-app.mdx index cf143485bf7..ca895f846ce 100644 --- a/i18n/ko/docusaurus-plugin-content-docs/current/integrate-logto/protected-app.mdx +++ b/i18n/ko/docusaurus-plugin-content-docs/current/integrate-logto/protected-app.mdx @@ -1,78 +1,78 @@ --- -description: Logto의 혁신적인 Protected App을 통해 Cloudflare로 구동되는 웹 앱에 코드 없는 인증을 쉽게 추가하세요. HTTP Basic Authentication 및 JWT 검증을 지원합니다. +description: Logto의 혁신적인 Protected App을 통해 웹 앱에 노코드 인증 (Authentication)을 손쉽게 추가하세요. Cloudflare 기반으로 HTTP Basic 인증 (Authentication) 및 JWT 검증을 지원합니다. sidebar_label: Protected App sidebar_position: 2 --- -# Protected App — Non-SDK 인증 (Authentication) 통합 +# Protected App — SDK 없는 인증 (Authentication) 통합 -Protected App은 [인증 (Authentication)](https://auth.wiki/authentication) 레이어를 애플리케이션에서 분리하여 [SDK 통합](/quick-starts)의 복잡성을 제거하도록 설계되었습니다. 우리는 인증을 처리하여 여러분이 핵심 기능에 집중할 수 있도록 합니다. 사용자가 인증되면, Protected App은 서버에서 콘텐츠를 제공합니다. +Protected App은 [SDK 통합](/quick-starts)의 복잡성을 제거하고, [인증 (Authentication)](https://auth.wiki/authentication) 계층을 애플리케이션과 분리하도록 설계되었습니다. 인증 (Authentication)은 저희가 처리하므로, 여러분은 핵심 기능에 집중할 수 있습니다. 사용자가 인증 (Authentication)되면 Protected App이 서버의 콘텐츠를 제공합니다. -## Protected App의 작동 방식 \{#how-protected-app-works} +## Protected App의 동작 방식 \{#how-protected-app-works} -Cloudflare로 구동되는 Protected App은 전 세계 엣지 네트워크에서 작동하여 애플리케이션에 낮은 대기 시간과 높은 가용성을 보장합니다. +Cloudflare 기반의 Protected App은 글로벌 엣지 네트워크에서 동작하여, 애플리케이션에 낮은 지연 시간과 높은 가용성을 보장합니다. -Protected App은 세션 상태와 사용자 정보를 유지합니다. 사용자가 인증되지 않은 경우, Protected App은 로그인 페이지로 리디렉션합니다. 인증이 완료되면, Protected App은 사용자의 요청을 인증 및 사용자 정보와 함께 래핑하여 원본 서버로 전달합니다. +Protected App은 세션 상태와 사용자 정보를 유지합니다. 사용자가 인증 (Authentication)되지 않은 경우, Protected App은 로그인 페이지로 리디렉션합니다. 인증 (Authentication) 후, Protected App은 사용자의 요청에 인증 (Authentication) 및 사용자 정보를 래핑하여 원본 서버로 전달합니다. -이 과정은 다음 흐름도에서 시각화됩니다: +이 과정은 다음 플로우차트로 시각화할 수 있습니다: ```mermaid graph LR A("클라이언트
(브라우저)") -->|요청| B(Logto
Protected App) B --> Condition{{경로
일치?}} - Condition -->|예| Matched{{인증됨?}} + Condition -->|예| Matched{{인증 (Authentication)됨?}} Matched -->|예| C(원본 서버) Matched -->|아니오| D(Logto 로그인) Condition -->|아니오| C ``` -## 원본 서버 보호 \{#protect-your-origin-server} +## 원본 서버 보호하기 \{#protect-your-origin-server} -원본 서버는 Logto의 Protected App이 소유하지 않은 물리적 또는 가상 장치일 수 있으며, 애플리케이션 콘텐츠가 위치하는 곳입니다. 콘텐츠 전송 네트워크 (CDN) 서버와 유사하게, Protected App은 인증 프로세스를 관리하고 원본 서버에서 콘텐츠를 가져옵니다. 따라서 사용자가 원본 서버에 직접 접근할 수 있게 되면, 인증을 우회할 수 있으며 애플리케이션이 더 이상 보호되지 않습니다. +원본 서버는 Logto의 Protected App이 소유하지 않은 물리적 또는 가상 장치일 수 있으며, 애플리케이션 콘텐츠가 위치합니다. CDN 서버와 유사하게, Protected App은 인증 (Authentication) 과정을 관리하고 원본 서버에서 콘텐츠를 가져옵니다. 따라서 사용자가 원본 서버에 직접 접근할 수 있다면 인증 (Authentication)을 우회할 수 있으므로, 애플리케이션이 더 이상 보호되지 않습니다. -따라서 원본 연결을 보호하는 것이 중요하며, 이는 공격자가 인증 없이 원본 서버를 발견하고 접근하는 것을 방지합니다. 이를 수행하는 방법은 여러 가지가 있습니다: +따라서 원본 연결을 안전하게 보호하는 것이 중요합니다. 이는 공격자가 인증 (Authentication) 없이 원본 서버를 발견하고 접근하는 것을 방지합니다. 이를 위한 방법은 다음과 같습니다: 1. HTTP 헤더 검증 -2. JSON Web Tokens (JWT) 검증 +2. JSON Web Token (JWT) 검증 ### HTTP 헤더 검증 \{#http-header-validation} -원본 서버를 보호하는 방법 중 하나는 [HTTP Basic Authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication#basic_authentication_scheme)을 사용하는 것입니다. +원본 서버를 보호하는 한 가지 방법은 [HTTP Basic 인증 (Authentication)](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication#basic_authentication_scheme)을 사용하는 것입니다. -Protected App에서의 각 요청에는 다음 헤더가 포함됩니다: +Protected App에서 오는 각 요청에는 다음과 같은 헤더가 포함됩니다: ``` Authorization: Basic base64(appId:appSecret) ``` -이 헤더를 검증함으로써 요청이 Protected App에서 온 것임을 확인하고 이 헤더가 포함되지 않은 요청을 거부할 수 있습니다. +이 헤더를 검증함으로써 요청이 Protected App에서 왔음을 확인하고, 이 헤더가 없는 요청은 거부할 수 있습니다. -Nginx 또는 Apache를 사용하는 경우, 원본 서버에서 HTTP Basic Authentication을 구현하는 방법에 대한 다음 가이드를 참조할 수 있습니다: +Nginx 또는 Apache를 사용하는 경우, 원본 서버에서 HTTP Basic 인증 (Authentication)을 구현하는 방법은 다음 가이드를 참고하세요: -1. Nginx: [HTTP Basic Authentication 구성](https://docs.nginx.com/nginx/admin-guide/security-controls/configuring-http-basic-authentication/) -2. Apache: [인증 및 인가](https://httpd.apache.org/docs/2.4/howto/auth.html) +1. Nginx: [HTTP Basic 인증 (Authentication) 구성하기](https://docs.nginx.com/nginx/admin-guide/security-controls/configuring-http-basic-authentication/) +2. Apache: [인증 (Authentication) 및 인가 (Authorization)](https://httpd.apache.org/docs/2.4/howto/auth.html) -애플리케이션 내에서 헤더를 확인하려면, Cloudflare에서 제공하는 [HTTP Basic Authentication 예제](https://developers.cloudflare.com/workers/examples/basic-auth/)를 참조하여 HTTP Basic 스키마를 사용하여 접근을 제한하는 방법을 배우세요. +애플리케이션 내에서 헤더를 확인하려면, Cloudflare에서 제공하는 [HTTP Basic 인증 (Authentication) 예제](https://developers.cloudflare.com/workers/examples/basic-auth/)를 참고하여 HTTP Basic 스키마로 접근을 제한하는 방법을 배울 수 있습니다. -### JSON Web Tokens (JWT) 검증 \{#json-web-tokens-jwt-validation} +### JSON Web Token (JWT) 검증 \{#json-web-tokens-jwt-validation} -원본 서버를 보호하는 또 다른 방법은 JSON Web Tokens (JWT)를 사용하는 것입니다. +원본 서버를 보호하는 또 다른 방법은 JSON Web Token (JWT)을 사용하는 것입니다. -Protected App에서의 각 인증된 요청에는 다음 헤더가 포함됩니다: +Protected App에서 인증 (Authentication)된 각 요청에는 다음과 같은 헤더가 포함됩니다: ``` Logto-ID-Token: ``` -JWT는 Logto에 의해 서명된 [ID 토큰](https://auth.wiki/id-token)으로 사용자 정보를 포함합니다. 이 JWT를 검증함으로써 요청이 Protected App에서 온 것임을 확인하고 이 헤더가 포함되지 않은 요청을 거부할 수 있습니다. +이 JWT는 [ID 토큰 (ID token)](https://auth.wiki/id-token)으로, Logto에서 서명되며 사용자 정보를 포함합니다. 이 JWT를 검증함으로써 요청이 Protected App에서 왔음을 확인하고, 이 헤더가 없는 요청은 거부할 수 있습니다. -토큰은 [JWS](https://auth.wiki/jws) 토큰으로 암호화되고 서명됩니다. +토큰은 [JWS](https://auth.wiki/jws) 토큰으로 암호화 및 서명됩니다. 검증 단계: -1. [JWT 검증](https://datatracker.ietf.org/doc/html/rfc7519#section-7.2) -2. [JWS 서명 검증](https://datatracker.ietf.org/doc/html/rfc7515#section-5.2) -3. 토큰의 발급자는 `https:///oidc` (여러분의 Logto 인증 서버에 의해 발급됨) +1. [JWT 검증하기](https://datatracker.ietf.org/doc/html/rfc7519#section-7.2) +2. [JWS 서명 검증하기](https://datatracker.ietf.org/doc/html/rfc7515#section-5.2) +3. 토큰의 발급자 (Issuer)는 `https:///oidc` (여러분의 Logto 인증 (Authentication) 서버에서 발급) ```js const express = require('express'); @@ -97,14 +97,12 @@ const verifyToken = (req, res, next) => { // 들어오는 요청에 토큰 헤더가 있는지 확인 if (!token) { - return res - .status(403) - .send({ status: false, message: '필수 Logto-ID-Token 헤더가 누락되었습니다' }); + return res.status(403).send({ status: false, message: '필수 Logto-ID-Token 헤더가 없습니다.' }); } jwt.verify(token, getKey, { issuer: ISSUER }, (err, decoded) => { if (err) { - return res.status(403).send({ status: false, message: '유효하지 않은 ID 토큰' }); + return res.status(403).send({ status: false, message: '유효하지 않은 ID 토큰입니다.' }); } req.user = decoded; @@ -123,11 +121,11 @@ app.get('/', (req, res) => { app.listen(3000); ``` -## 인증 상태 및 사용자 정보 가져오기 \{#get-authentication-state-and-user-information} +## 인증 (Authentication) 상태 및 사용자 정보 가져오기 \{#get-authentication-state-and-user-information} -애플리케이션에 대한 인증 및 사용자 정보를 가져와야 하는 경우, `Logto-ID-Token` 헤더를 사용할 수 있습니다. +애플리케이션에서 인증 (Authentication) 및 사용자 정보를 가져와야 하는 경우, `Logto-ID-Token` 헤더를 사용할 수 있습니다. -토큰을 디코딩하기만 원한다면, 다음 코드를 사용할 수 있습니다: +토큰을 단순히 디코딩만 하고 싶다면, 다음 코드를 사용할 수 있습니다: ```js const express = require('express'); @@ -138,13 +136,13 @@ const decodeIdToken = (req, res, next) => { if (!token) { return res.status(403).send({ status: false, - message: '필수 Logto-ID-Token 헤더가 누락되었습니다', + message: '필수 Logto-ID-Token 헤더가 없습니다.', }); } const parts = token.split('.'); if (parts.length !== 3) { - throw new Error('유효하지 않은 ID 토큰'); + throw new Error('유효하지 않은 ID 토큰입니다.'); } const payload = parts[1]; @@ -166,35 +164,52 @@ app.get('/', (req, res) => { app.listen(3000); ``` +## ID 토큰 (ID token) 클레임 (Claim) 커스터마이즈하기 \{#customize-id-token-claims} + +기본적으로, `Logto-ID-Token` 헤더에는 표준 OIDC 클레임 (예: `sub`, `name`, `email`)이 포함됩니다. 역할이나 조직 데이터와 같은 [확장 클레임](/developers/custom-id-token#extended-claims)을 포함하려면, 다음 두 가지를 모두 설정해야 합니다: + +1. **테넌트 토글**: Console > Custom JWT > ID token에서 클레임을 활성화하세요. +2. **Protected App 스코프**: Protected App 설정에서 **ID 토큰 (ID token) 클레임** > **추가 스코프**에서 해당 스코프를 선택하세요. + +확장 클레임은 Custom JWT에서 클레임이 활성화되고, Protected App에 해당 스코프가 선택된 경우에만 전달된 ID 토큰 (ID token)에 포함됩니다. 전체 확장 스코프 및 클레임 목록은 [Custom ID token](/developers/custom-id-token)을 참고하세요. + +| Scope | Claims | +| ------------------------------------ | ------------------------------------ | +| `custom_data` | `custom_data` | +| `identities` | `identities`, `sso_identities` | +| `roles` | `roles` | +| `urn:logto:scope:organizations` | `organizations`, `organization_data` | +| `urn:logto:scope:organization_roles` | `organization_roles` | + ## 원본 호스트 가져오기 \{#get-the-original-host} -클라이언트가 요청한 원본 호스트를 가져와야 하는 경우, `Logto-Host` 또는 `x-forwarded-host` 헤더를 사용할 수 있습니다. +클라이언트가 요청한 원본 호스트가 필요하다면, `Logto-Host` 또는 `x-forwarded-host` 헤더를 사용할 수 있습니다. -## 인증 규칙 사용자 정의 \{#customize-authentication-rules} +## 인증 (Authentication) 규칙 커스터마이즈하기 \{#customize-authentication-rules} -기본적으로, Protected App은 모든 경로를 보호합니다. 인증 규칙을 사용자 정의해야 하는 경우, Console에서 "Custom authentication rules" 필드를 설정할 수 있습니다. +기본적으로 Protected App은 모든 경로를 보호합니다. 인증 (Authentication) 규칙을 커스터마이즈해야 한다면, Console에서 "Custom authentication rules" 필드를 설정할 수 있습니다. -정규 표현식을 지원하며, 다음은 두 가지 사례 시나리오입니다: +정규 표현식을 지원하며, 다음은 두 가지 예시입니다: -1. `/admin` 및 `/privacy` 경로만 인증으로 보호하려면: `^/(admin|privacy)/.*` -2. JPG 이미지를 인증에서 제외하려면: `^(?!.*\.jpg$).*$` +1. `/admin` 및 `/privacy` 경로만 인증 (Authentication)으로 보호하려면: `^/(admin|privacy)/.*` +2. JPG 이미지는 인증 (Authentication)에서 제외하려면: `^(?!.*\.jpg$).*$` ## 로컬 개발 \{#local-development} -Protected App은 원본 서버와 함께 작동하도록 설계되었습니다. 그러나 원본 서버가 공개적으로 접근할 수 없는 경우, [ngrok](https://ngrok.com/) 또는 [Cloudflare Tunnels](https://developers.cloudflare.com/pages/how-to/preview-with-cloudflare-tunnel/)과 같은 도구를 사용하여 로컬 서버를 인터넷에 노출할 수 있습니다. +Protected App은 원본 서버와 함께 동작하도록 설계되었습니다. 하지만 원본 서버가 공개적으로 접근할 수 없는 경우, [ngrok](https://ngrok.com/) 또는 [Cloudflare Tunnels](https://developers.cloudflare.com/pages/how-to/preview-with-cloudflare-tunnel/)과 같은 도구를 사용하여 로컬 서버를 인터넷에 노출할 수 있습니다. -## SDK 통합으로 전환 \{#transition-to-sdk-integration} +## SDK 통합으로 전환하기 \{#transition-to-sdk-integration} -Protected App은 인증 프로세스를 단순화하도록 설계되었습니다. 그러나 더 나은 제어 및 사용자 정의를 위해 SDK 통합으로 전환하기로 결정한 경우, Logto에서 [새 애플리케이션을 생성](/integrate-logto/integrate-logto-into-your-application)하고 [SDK 통합](/quick-starts)을 구성할 수 있습니다. 원활한 전환을 위해 Protected App의 애플리케이션 구성을 재사용할 수 있습니다. Protected App은 실제로 Logto에서 "전통적인 웹 앱"이며, 애플리케이션 설정에서 "[AppId](/integrate-logto/application-data-structure#application-id)" 및 "[AppSecret](/integrate-logto/application-data-structure#application-secret)"을 찾을 수 있습니다. 전환이 완료되면 애플리케이션에서 Protected App을 제거할 수 있습니다. +Protected App은 인증 (Authentication) 과정을 단순화하도록 설계되었습니다. 하지만 더 나은 제어와 커스터마이즈를 위해 SDK 통합으로 전환하려면, Logto에서 [새 애플리케이션 생성](/integrate-logto/integrate-logto-into-your-application) 후 [SDK 통합](/quick-starts)을 설정할 수 있습니다. 원활한 전환을 위해 Protected App의 애플리케이션 설정을 재사용할 수 있습니다. Protected App은 실제로 Logto에서 "Traditional Web App" 유형이며, 애플리케이션 설정에서 "[AppId](/integrate-logto/application-data-structure#application-id)"와 "[AppSecret](/integrate-logto/application-data-structure#application-secret)"을 찾을 수 있습니다. 전환이 완료되면 Protected App을 애플리케이션에서 제거할 수 있습니다. ## 관련 리소스 \{#related-resources} - Protected App: 클릭 몇 번으로 앱의 인증을 구축하세요. 코드가 필요하지 않습니다. + Protected App: 클릭 몇 번으로 앱의 인증 (Authentication) 구축하기. 코드 불필요. -Protected App의 동기 +Protected App의 개발 동기 - 인증 시스템을 구축하는 가장 빠른 방법 + 인증 (Authentication) 시스템을 가장 빠르게 구축하는 방법 diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/logto-cloud/README.mdx b/i18n/ko/docusaurus-plugin-content-docs/current/logto-cloud/README.mdx index afd6b792d0a..847a0eb8142 100644 --- a/i18n/ko/docusaurus-plugin-content-docs/current/logto-cloud/README.mdx +++ b/i18n/ko/docusaurus-plugin-content-docs/current/logto-cloud/README.mdx @@ -3,12 +3,13 @@ import Developer from '@site/src/assets/developer.svg'; import TenantMemberManagement from '@site/src/assets/gear.svg'; import PricingAndBilling from '@site/src/assets/key.svg'; import McpIcon from '@site/src/assets/mcp.svg'; +import TenantAutomation from '@site/src/assets/robot.svg'; import CustomDomains from '@site/src/assets/search.svg'; import SystemLimit from '@site/src/assets/security.svg'; # Logto Cloud -[Logto Cloud](https://cloud.logto.io) 는 아이덴티티와 리소스를 원활하고 쉽게 관리할 수 있도록 다양한 관리 및 운영 서비스를 제공합니다. Logto에서 호스팅하며, [다중 리전 지원](/logto-cloud/tenant-settings#tenant-region), 테넌트 관리, [청구 및 가격 정책](/logto-cloud/billing-and-pricing), [멤버 관리](/logto-cloud/tenant-member-management), 콘솔 역할 기반 접근 제어 등 다양한 기능을 포함합니다. +[Logto Cloud](https://cloud.logto.io)는 아이덴티티와 리소스를 원활하고 쉽게 관리할 수 있도록 다양한 관리 및 운영 서비스를 제공합니다. Logto에서 호스팅하며, [다중 리전 지원](/logto-cloud/tenant-settings#tenant-region), 테넌트 관리, [청구 및 가격](/logto-cloud/billing-and-pricing), [멤버 관리](/logto-cloud/tenant-member-management), 콘솔 역할 기반 접근 제어 등 다양한 기능을 포함하고 있습니다. 클라우드 서비스에 대해 궁금한 점이 있거나 추가 지원이 필요하시면 언제든지 문의해 주세요. @@ -31,7 +32,7 @@ import SystemLimit from '@site/src/assets/security.svg'; label: '개발 테넌트 데이터 보존 정책', href: '/logto-cloud/dev-tenant-data-retention', description: - '개발 테넌트의 90일 사용자 보존 정책과 Logto 개발 테넌트의 효과적인 사용 방법을 알아보세요.', + '개발 테넌트의 90일 사용자 보존 정책을 이해하고 Logto 개발 테넌트를 효과적으로 사용하는 방법을 알아보세요.', customProps: { icon: , }, @@ -57,9 +58,9 @@ import SystemLimit from '@site/src/assets/security.svg'; }, { type: 'link', - label: '청구 및 가격 정책', + label: '청구 및 가격', href: '/logto-cloud/billing-and-pricing', - description: '청구서를 쉽게 이해하고 구독을 안심하고 관리할 수 있습니다.', + description: '청구서를 쉽게 이해하고 구독을 자신 있게 관리하세요.', customProps: { icon: , }, @@ -75,10 +76,20 @@ import SystemLimit from '@site/src/assets/security.svg'; }, { type: 'link', - label: 'Logto MCP Server', + label: '테넌트 관리 자동화', + href: '/logto-cloud/automate-tenant-creation', + description: + 'Logto Cloud API 및 Management API를 사용하여 테넌트를 프로그래밍 방식으로 생성 및 관리하세요.', + customProps: { + icon: , + }, + }, + { + type: 'link', + label: 'Logto MCP 서버', href: '/logto-cloud/logto-mcp-server', description: - 'AI 도구 및 IDE를 MCP를 통해 Logto Cloud에 연결하여 리소스를 관리하고 인증 (Authentication)을 통합하세요.', + 'AI 도구와 IDE를 MCP를 통해 Logto Cloud에 연결하여 리소스를 관리하고 인증 (Authentication)을 통합하세요.', customProps: { icon: , }, diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/logto-cloud/automate-tenant-creation.mdx b/i18n/ko/docusaurus-plugin-content-docs/current/logto-cloud/automate-tenant-creation.mdx new file mode 100644 index 00000000000..0d73fadbcd0 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/logto-cloud/automate-tenant-creation.mdx @@ -0,0 +1,242 @@ +--- +id: automate-tenant-creation +title: 테넌트 관리 자동화 +sidebar_position: 8 +--- + +# 테넌트 관리 자동화 + +Logto Cloud 테넌트는 프로그래밍 방식으로 관리할 수 있습니다. 테넌트 생성 및 추가 설정을 Console로 전환하지 않고도 계속 진행할 수 있습니다. + +이는 자체 온보딩 플로우, 내부 플랫폼, AI 에이전트, 또는 통합 자동화에서 테넌트를 프로비저닝해야 할 때 유용합니다. + +자동화 흐름은 다음과 같습니다: + +1. **Logto Cloud 개인 액세스 토큰 (PAT)**을 사용하여 Logto Cloud API를 호출합니다. +2. `POST /api/tenants`로 테넌트를 생성합니다. +3. 생성 응답에서 기본 기계 간 (M2M) 애플리케이션 자격 증명을 읽어옵니다. +4. 기본 M2M 애플리케이션을 사용하여 새 테넌트의 Management API 액세스 토큰을 얻습니다. +5. 새 테넌트의 Management API를 호출하여 애플리케이션, 사용자, 역할, 리소스, 조직, 기타 설정을 계속 프로비저닝합니다. + +## 시작하기 전에 \{#before-you-start} + +다음 값을 준비하세요: + +| Variable | Description | +| -------------------- | ------------------------------------------------------------------------------------- | +| `CLOUD_API_ENDPOINT` | Logto Cloud API 엔드포인트. Logto Cloud의 경우 `https://cloud.logto.io`를 사용하세요. | +| `LOGTO_CLOUD_PAT` | Logto Cloud 계정의 PAT. | +| `TENANT_NAME` | 생성할 테넌트의 표시 이름. | +| `TENANT_TAG` | 테넌트 유형. `development` 또는 `production`을 사용하세요. | +| `REGION_NAME` | 테넌트의 리전 식별자. | + +환경 변수로 설정하세요: + +```bash +export CLOUD_API_ENDPOINT="https://cloud.logto.io" +export LOGTO_CLOUD_PAT="" +export TENANT_NAME="My automated tenant" +export TENANT_TAG="development" +export REGION_NAME="" +``` + +## 사용 가능한 리전 조회 \{#get-available-regions} + +테넌트를 생성하기 전에, Logto Cloud 계정에서 사용 가능한 리전을 조회하세요: + +```bash +curl "$CLOUD_API_ENDPOINT/api/me/regions" \ + -H "Authorization: Bearer $LOGTO_CLOUD_PAT" +``` + +응답에는 사용 가능한 리전이 포함되어 있습니다. 테넌트 생성 시 `REGION_NAME`으로 `name` 값을 사용하세요. + +예시 응답: + +```json +{ + "regions": [ + { + "name": "EU", + "displayName": "Europe" + }, + { + "name": "US", + "displayName": "United States" + } + ] +} +``` + +## 테넌트 생성 \{#create-a-tenant} + +Logto Cloud PAT으로 `POST /api/tenants`를 호출하세요: + +```bash +curl "$CLOUD_API_ENDPOINT/api/tenants" \ + -X POST \ + -H "Authorization: Bearer $LOGTO_CLOUD_PAT" \ + -H "Content-Type: application/json" \ + -d '{ + "name": "'"$TENANT_NAME"'", + "tag": "'"$TENANT_TAG"'", + "regionName": "'"$REGION_NAME"'" + }' +``` + +응답에는 생성된 테넌트와 기본 M2M 애플리케이션이 포함되어 있습니다. 이 M2M 애플리케이션은 새 테넌트에 생성되며, 테넌트의 Management API에 접근할 수 있습니다. + +예시 응답: + +```json +{ + "id": "new-tenant-id", + "name": "My automated tenant", + "tag": "development", + "indicator": "https://new-tenant-id.logto.app", + "regionName": "EU", + "defaultApplication": { + "id": "default-m2m-app-id", + "secret": "default-m2m-app-secret" + } +} +``` + +다음 단계에 필요한 값을 저장하세요: + +```bash +export TENANT_ID="" +export TENANT_ENDPOINT="" +export DEFAULT_M2M_APP_ID="" +export DEFAULT_M2M_APP_SECRET="" +``` + +## 새 테넌트의 Management API 액세스 토큰 받기 \{#get-a-management-api-access-token-for-the-new-tenant} + +기본 M2M 애플리케이션 자격 증명을 사용하여 새 테넌트에서 액세스 토큰을 요청하세요: + +```bash +curl "$TENANT_ENDPOINT/oidc/token" \ + -X POST \ + -u "$DEFAULT_M2M_APP_ID:$DEFAULT_M2M_APP_SECRET" \ + -H "Content-Type: application/x-www-form-urlencoded" \ + -d "grant_type=client_credentials" \ + -d "resource=$TENANT_ENDPOINT/api" \ + -d "scope=all" +``` + +예시 응답: + +```json +{ + "access_token": "eyJ...", + "expires_in": 3600, + "token_type": "Bearer", + "scope": "all" +} +``` + +액세스 토큰을 저장하세요: + +```bash +export MANAGEMENT_API_ACCESS_TOKEN="" +``` + +## 새 테넌트 프로비저닝 계속하기 \{#continue-provisioning-the-new-tenant} + +Management API 액세스 토큰을 사용하여 새 테넌트의 Management API를 호출하세요. + +예를 들어, 애플리케이션 목록 조회: + +```bash +curl "$TENANT_ENDPOINT/api/applications" \ + -H "Authorization: Bearer $MANAGEMENT_API_ACCESS_TOKEN" +``` + +또는 애플리케이션 생성: + +```bash +curl "$TENANT_ENDPOINT/api/applications" \ + -X POST \ + -H "Authorization: Bearer $MANAGEMENT_API_ACCESS_TOKEN" \ + -H "Content-Type: application/json" \ + -d '{ + "name": "My web app", + "type": "SPA", + "oidcClientMetadata": { + "redirectUris": ["https://example.com/callback"], + "postLogoutRedirectUris": ["https://example.com"] + } + }' +``` + +이 시점에서, 자동화는 사용자, 애플리케이션, API 리소스, 역할, 조직, 커넥터, 로그인 경험 설정 등 모든 Management API 작업을 계속 진행할 수 있습니다. + +## 전체 자동화 예시 \{#full-automation-example} + +다음 Node.js 예시는 테넌트를 생성하고, 반환된 기본 M2M 자격 증명으로 Management API 액세스 토큰을 교환한 뒤, 새 테넌트의 애플리케이션 목록을 조회합니다: + +```js +const cloudApiEndpoint = 'https://cloud.logto.io'; +const logtoCloudPat = process.env.LOGTO_CLOUD_PAT; + +const createTenantResponse = await fetch(`${cloudApiEndpoint}/api/tenants`, { + method: 'POST', + headers: { + authorization: `Bearer ${logtoCloudPat}`, + 'content-type': 'application/json', + }, + body: JSON.stringify({ + name: 'My automated tenant', + tag: 'development', + regionName: 'EU', + }), +}); + +if (!createTenantResponse.ok) { + throw new Error(`Failed to create tenant: ${await createTenantResponse.text()}`); +} + +const tenant = await createTenantResponse.json(); +const tenantEndpoint = tenant.indicator; +const { id: appId, secret: appSecret } = tenant.defaultApplication; + +const tokenResponse = await fetch(`${tenantEndpoint}/oidc/token`, { + method: 'POST', + headers: { + authorization: `Basic ${Buffer.from(`${appId}:${appSecret}`).toString('base64')}`, + 'content-type': 'application/x-www-form-urlencoded', + }, + body: new URLSearchParams({ + grant_type: 'client_credentials', + resource: `${tenantEndpoint}/api`, + scope: 'all', + }), +}); + +if (!tokenResponse.ok) { + throw new Error(`Failed to get Management API token: ${await tokenResponse.text()}`); +} + +const { access_token: managementApiAccessToken } = await tokenResponse.json(); + +const applicationsResponse = await fetch(`${tenantEndpoint}/api/applications`, { + headers: { + authorization: `Bearer ${managementApiAccessToken}`, + }, +}); + +if (!applicationsResponse.ok) { + throw new Error(`Failed to list applications: ${await applicationsResponse.text()}`); +} + +const applications = await applicationsResponse.json(); + +console.log({ tenantId: tenant.id, applications }); +``` + +## 관련 리소스 \{#related-resources} + +- [개인 액세스 토큰](/user-management/personal-access-token) +- [Management API와 상호작용하기](/integrate-logto/interact-with-management-api) +- [기계 간 (M2M) 빠른 시작](/quick-starts/m2m) diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/integrate-logto/protected-app.mdx b/i18n/pt-BR/docusaurus-plugin-content-docs/current/integrate-logto/protected-app.mdx index b458b5512fd..f80ff0f1fcf 100644 --- a/i18n/pt-BR/docusaurus-plugin-content-docs/current/integrate-logto/protected-app.mdx +++ b/i18n/pt-BR/docusaurus-plugin-content-docs/current/integrate-logto/protected-app.mdx @@ -1,70 +1,70 @@ --- -description: Adicione facilmente autenticação sem código aos seus aplicativos web com o inovador Protected App do Logto, alimentado pelo Cloudflare. Suporta HTTP Basic Authentication e validação de JWT. +description: Adicione facilmente autenticação sem código aos seus aplicativos web com o inovador Protected App do Logto, alimentado pela Cloudflare. Suporta autenticação HTTP Basic e validação de JWT. sidebar_label: Protected App sidebar_position: 2 --- # Protected App — Integração de autenticação sem SDK -O Protected App foi projetado para eliminar a complexidade das [integrações de SDK](/quick-starts) separando a [autenticação](https://auth.wiki/authentication) do seu aplicativo. Nós cuidamos da autenticação, permitindo que você se concentre na sua funcionalidade principal. Uma vez que um usuário é autenticado, o Protected App serve o conteúdo do seu servidor. +O Protected App foi projetado para eliminar a complexidade das [integrações de SDK](/quick-starts) ao separar a camada de [autenticação](https://auth.wiki/authentication) da sua aplicação. Nós cuidamos da autenticação, permitindo que você foque na sua funcionalidade principal. Uma vez que um usuário é autenticado, o Protected App serve o conteúdo do seu servidor. ## Como o Protected App funciona \{#how-protected-app-works} -O Protected App, alimentado pelo Cloudflare, opera globalmente em redes de borda, garantindo baixa latência e alta disponibilidade para o seu aplicativo. +O Protected App, alimentado pela Cloudflare, opera globalmente em redes de borda, garantindo baixa latência e alta disponibilidade para sua aplicação. -O Protected App mantém o estado da sessão e as informações do usuário. Se um usuário não estiver autenticado, o Protected App os redireciona para a página de login. Uma vez autenticado, o Protected App envolve a solicitação do usuário com autenticação e informações do usuário, e então a encaminha para o servidor de origem. +O Protected App mantém o estado da sessão e as informações do usuário. Se um usuário não estiver autenticado, o Protected App o redireciona para a página de login. Uma vez autenticado, o Protected App encapsula a solicitação do usuário com autenticação e informações do usuário, e então a encaminha para o servidor de origem. -Este processo é visualizado no seguinte fluxograma: +Esse processo é visualizado no fluxograma a seguir: ```mermaid graph LR - A("Cliente
(Navegador)") -->|Solicitação| B(Logto
Protected App) + A("Cliente
(Navegador)") -->|Requisição| B(Logto
Protected App) B --> Condition{{Rota
corresponde?}} Condition -->|Sim| Matched{{Está autenticado?}} Matched -->|Sim| C(Servidor de origem) - Matched -->|Não| D(Logto login) + Matched -->|Não| D(Login Logto) Condition -->|Não| C ``` ## Proteja seu servidor de origem \{#protect-your-origin-server} -O servidor de origem, que pode ser um dispositivo físico ou virtual não pertencente ao Protected App do Logto, é onde reside o conteúdo do seu aplicativo. Semelhante a um servidor de Rede de Distribuição de Conteúdo (CDN), o Protected App gerencia processos de autenticação e recupera conteúdo do seu servidor de origem. Portanto, se os usuários obtiverem acesso direto ao seu servidor de origem, eles podem contornar a autenticação e seu aplicativo não estará mais protegido. +O servidor de origem, que pode ser um dispositivo físico ou virtual não pertencente ao Protected App do Logto, é onde o conteúdo da sua aplicação reside. Semelhante a um servidor de Content Delivery Network (CDN), o Protected App gerencia os processos de autenticação e recupera o conteúdo do seu servidor de origem. Portanto, se os usuários obtiverem acesso direto ao seu servidor de origem, eles podem contornar a autenticação e sua aplicação não estará mais protegida. -Portanto, é importante proteger as conexões de origem, isso impede que invasores descubram e acessem seu servidor de origem sem autenticação. Existem várias maneiras de fazer isso: +Por isso, é importante proteger as conexões de origem, pois isso impede que invasores descubram e acessem seu servidor de origem sem autenticação. Existem várias maneiras de fazer isso: -1. Validação de Cabeçalho HTTP +1. Validação de cabeçalho HTTP 2. Validação de JSON Web Tokens (JWT) -### Validação de Cabeçalho HTTP \{#http-header-validation} +### Validação de cabeçalho HTTP \{#http-header-validation} -Proteger seu servidor de origem pode ser alcançado usando [HTTP Basic Authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication#basic_authentication_scheme) para proteger seu servidor de origem. +Proteger seu servidor de origem pode ser feito usando [HTTP Basic Authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication#basic_authentication_scheme). -Cada solicitação do Protected App inclui o seguinte cabeçalho: +Cada requisição do Protected App inclui o seguinte cabeçalho: ``` Authorization: Basic base64(appId:appSecret) ``` -Ao validar este cabeçalho, você pode confirmar que a solicitação vem do Protected App e negar quaisquer solicitações que não incluam este cabeçalho. +Ao validar esse cabeçalho, você pode confirmar que a requisição vem do Protected App e negar qualquer requisição que não inclua esse cabeçalho. -Se você estiver usando Nginx ou Apache, pode consultar os seguintes guias para implementar HTTP Basic Authentication no seu servidor de origem: +Se você estiver usando Nginx ou Apache, pode consultar os seguintes guias para implementar HTTP Basic Authentication em seu servidor de origem: -1. Nginx: [Configuring HTTP Basic Authentication](https://docs.nginx.com/nginx/admin-guide/security-controls/configuring-http-basic-authentication/) +1. Nginx: [Configurando HTTP Basic Authentication](https://docs.nginx.com/nginx/admin-guide/security-controls/configuring-http-basic-authentication/) 2. Apache: [Authentication and Authorization](https://httpd.apache.org/docs/2.4/howto/auth.html) -Para verificar os cabeçalhos dentro do seu aplicativo, consulte o [exemplo de HTTP Basic Authentication](https://developers.cloudflare.com/workers/examples/basic-auth/) fornecido pela Cloudflare para aprender como restringir o acesso usando o esquema HTTP Basic. +Para verificar os cabeçalhos dentro da sua aplicação, consulte o [exemplo de HTTP Basic Authentication](https://developers.cloudflare.com/workers/examples/basic-auth/) fornecido pela Cloudflare para aprender como restringir o acesso usando o esquema HTTP Basic. ### Validação de JSON Web Tokens (JWT) \{#json-web-tokens-jwt-validation} -Outra maneira de proteger seu servidor de origem é usando JSON Web Tokens (JWT). +Outra forma de proteger seu servidor de origem é usando JSON Web Tokens (JWT). -Cada solicitação autenticada do Protected App inclui o seguinte cabeçalho: +Cada requisição autenticada do Protected App inclui o seguinte cabeçalho: ``` Logto-ID-Token: ``` -O JWT é chamado de [Token de ID](https://auth.wiki/id-token), que é assinado pelo Logto e contém informações do usuário. Ao validar este JWT, você pode confirmar que a solicitação vem do Protected App e negar quaisquer solicitações que não incluam este cabeçalho. +O JWT é chamado de [Token de ID (ID token)](https://auth.wiki/id-token), assinado pelo Logto e contém informações do usuário. Ao validar esse JWT, você pode confirmar que a requisição vem do Protected App e negar qualquer requisição que não inclua esse cabeçalho. O token é criptografado e assinado como um token [JWS](https://auth.wiki/jws). @@ -95,16 +95,16 @@ const getKey = (header, callback) => { const verifyToken = (req, res, next) => { const token = req.headers['Logto-ID-Token']; - // Certifique-se de que a solicitação recebida tenha nosso cabeçalho de token + // Certifique-se de que a requisição recebida possui nosso cabeçalho de token if (!token) { return res .status(403) - .send({ status: false, message: 'missing required Logto-ID-Token header' }); + .send({ status: false, message: 'cabeçalho Logto-ID-Token obrigatório ausente' }); } jwt.verify(token, getKey, { issuer: ISSUER }, (err, decoded) => { if (err) { - return res.status(403).send({ status: false, message: 'invalid id token' }); + return res.status(403).send({ status: false, message: 'token de ID inválido' }); } req.user = decoded; @@ -117,17 +117,17 @@ const app = express(); app.use(verifyToken); app.get('/', (req, res) => { - res.send('Hello World!'); + res.send('Olá Mundo!'); }); app.listen(3000); ``` -## Obter estado de autenticação e informações do usuário \{#get-authentication-state-and-user-information} +## Obtenha o estado de autenticação e informações do usuário \{#get-authentication-state-and-user-information} -Se você precisar obter autenticação e informações do usuário para seu aplicativo, também pode usar o cabeçalho `Logto-ID-Token`. +Se você precisar obter informações de autenticação e do usuário para sua aplicação, também pode usar o cabeçalho `Logto-ID-Token`. -Se você apenas quiser decodificar o token, pode usar o seguinte código: +Se você quiser apenas decodificar o token, pode usar o seguinte código: ```js const express = require('express'); @@ -138,13 +138,13 @@ const decodeIdToken = (req, res, next) => { if (!token) { return res.status(403).send({ status: false, - message: 'missing required Logto-ID-Token header', + message: 'cabeçalho Logto-ID-Token obrigatório ausente', }); } const parts = token.split('.'); if (parts.length !== 3) { - throw new Error('Invalid ID token'); + throw new Error('Token de ID inválido'); } const payload = parts[1]; @@ -166,15 +166,32 @@ app.get('/', (req, res) => { app.listen(3000); ``` -## Obter o host original \{#get-the-original-host} +## Personalize as reivindicações do token de ID \{#customize-id-token-claims} + +Por padrão, o cabeçalho `Logto-ID-Token` inclui reivindicações padrão do OIDC (por exemplo, `sub`, `name` e `email`). Para incluir [reivindicações estendidas](/developers/custom-id-token#extended-claims) como papéis ou dados da organização, ambos os itens a seguir devem ser configurados: + +1. **Alternância do tenant**: Ative a reivindicação em Console > Custom JWT > ID token. +2. **Escopos do Protected App**: Nas configurações do seu Protected App, selecione o escopo correspondente em **ID token claims** > **Additional scopes**. + +As reivindicações estendidas são incluídas no token de ID encaminhado somente quando a reivindicação está ativada no Custom JWT e o escopo correspondente está selecionado para o Protected App. Veja [Custom ID token](/developers/custom-id-token) para a lista completa de escopos e reivindicações estendidas. + +| Escopo | Reivindicações | +| ------------------------------------ | ------------------------------------ | +| `custom_data` | `custom_data` | +| `identities` | `identities`, `sso_identities` | +| `roles` | `roles` | +| `urn:logto:scope:organizations` | `organizations`, `organization_data` | +| `urn:logto:scope:organization_roles` | `organization_roles` | + +## Obtenha o host original \{#get-the-original-host} Se você precisar obter o host original solicitado pelo cliente, pode usar o cabeçalho `Logto-Host` ou `x-forwarded-host`. -## Personalizar regras de autenticação \{#customize-authentication-rules} +## Personalize as regras de autenticação \{#customize-authentication-rules} -Por padrão, o Protected App protegerá todas as rotas. Se você precisar personalizar as regras de autenticação, pode definir o campo "Regras de autenticação personalizadas" no Console. +Por padrão, o Protected App protegerá todas as rotas. Se você precisar personalizar as regras de autenticação, pode definir o campo "Custom authentication rules" no Console. -Ele suporta expressões regulares, aqui estão dois cenários de caso: +Ele suporta expressões regulares, aqui estão dois cenários de uso: 1. Para proteger apenas as rotas `/admin` e `/privacy` com autenticação: `^/(admin|privacy)/.*` 2. Para excluir imagens JPG da autenticação: `^(?!.*\.jpg$).*$` @@ -185,12 +202,12 @@ O Protected App foi projetado para funcionar com seu servidor de origem. No enta ## Transição para integração com SDK \{#transition-to-sdk-integration} -O Protected App foi projetado para simplificar o processo de autenticação. No entanto, se você decidir fazer a transição para a integração com SDK para melhor controle e personalização, pode [criar um novo aplicativo](/integrate-logto/integrate-logto-into-your-application) no Logto e configurar a [integração com SDK](/quick-starts). E para uma transição suave, você pode reutilizar as configurações do aplicativo do Protected App. O Protected App é, na verdade, um "Aplicativo Web Tradicional" no Logto, você pode encontrar o "[AppId](/integrate-logto/application-data-structure#application-id)" e o "[AppSecret](/integrate-logto/application-data-structure#application-secret)" nas configurações do aplicativo. Após a conclusão da transição, você pode remover o Protected App do seu aplicativo. +O Protected App foi projetado para simplificar o processo de autenticação. No entanto, se você decidir migrar para a integração com SDK para obter mais controle e personalização, pode [criar um novo aplicativo](/integrate-logto/integrate-logto-into-your-application) no Logto e configurar a [integração com SDK](/quick-starts). E para uma transição suave, você pode reutilizar as configurações do aplicativo do Protected App. O Protected App é, na verdade, um "Traditional Web App" no Logto, você pode encontrar o "[AppId](/integrate-logto/application-data-structure#application-id)" e o "[AppSecret](/integrate-logto/application-data-structure#application-secret)" nas configurações do aplicativo. Após a conclusão da transição, você pode remover o Protected App da sua aplicação. ## Recursos relacionados \{#related-resources} - Protected App: Construa a autenticação do seu aplicativo em cliques. Nenhum código necessário. + Protected App: construa a autenticação do seu app em poucos cliques. Sem código. A motivação por trás do Protected App diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/logto-cloud/README.mdx b/i18n/pt-BR/docusaurus-plugin-content-docs/current/logto-cloud/README.mdx index 69d958e43a3..a5a03c3d98d 100644 --- a/i18n/pt-BR/docusaurus-plugin-content-docs/current/logto-cloud/README.mdx +++ b/i18n/pt-BR/docusaurus-plugin-content-docs/current/logto-cloud/README.mdx @@ -3,12 +3,13 @@ import Developer from '@site/src/assets/developer.svg'; import TenantMemberManagement from '@site/src/assets/gear.svg'; import PricingAndBilling from '@site/src/assets/key.svg'; import McpIcon from '@site/src/assets/mcp.svg'; +import TenantAutomation from '@site/src/assets/robot.svg'; import CustomDomains from '@site/src/assets/search.svg'; import SystemLimit from '@site/src/assets/security.svg'; # Logto Cloud -[Logto Cloud](https://cloud.logto.io) oferece uma variedade de serviços de gerenciamento e operação para ajudar você a gerenciar identidades e recursos de forma simples e eficiente. Hospedado pelo Logto, inclui recursos como [suporte a múltiplas regiões](/logto-cloud/tenant-settings#tenant-region), gerenciamento de tenant, [faturamento e preços](/logto-cloud/billing-and-pricing), [gerenciamento de membros](/logto-cloud/tenant-member-management) e controle de acesso baseado em papel no console. +[Logto Cloud](https://cloud.logto.io) oferece uma variedade de serviços de gerenciamento e operação para ajudar você a gerenciar identidades e recursos de forma simples e eficiente. Hospedado pelo Logto, inclui recursos como [suporte a múltiplas regiões](/logto-cloud/tenant-settings#tenant-region), gerenciamento de tenants, [faturamento e preços](/logto-cloud/billing-and-pricing), [gerenciamento de membros](/logto-cloud/tenant-member-management) e controle de acesso baseado em papel no console. Se você tiver dúvidas sobre os serviços em nuvem e precisar de suporte adicional, entre em contato conosco. @@ -31,7 +32,7 @@ Se você tiver dúvidas sobre os serviços em nuvem e precisar de suporte adicio label: 'Política de retenção de dados do tenant de desenvolvimento', href: '/logto-cloud/dev-tenant-data-retention', description: - 'Entenda a política de retenção de usuários por 90 dias do tenant de desenvolvimento e como usar o tenant de desenvolvimento do Logto de forma eficaz.', + 'Entenda a política de retenção de usuários de 90 dias do tenant de desenvolvimento e como usar o tenant de desenvolvimento do Logto de forma eficaz.', customProps: { icon: , }, @@ -75,6 +76,16 @@ Se você tiver dúvidas sobre os serviços em nuvem e precisar de suporte adicio icon: , }, }, + { + type: 'link', + label: 'Automatizar o gerenciamento de tenants', + href: '/logto-cloud/automate-tenant-creation', + description: + 'Crie e gerencie tenants programaticamente com Logto Cloud API e Management API.', + customProps: { + icon: , + }, + }, { type: 'link', label: 'Logto MCP Server', diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/logto-cloud/automate-tenant-creation.mdx b/i18n/pt-BR/docusaurus-plugin-content-docs/current/logto-cloud/automate-tenant-creation.mdx new file mode 100644 index 00000000000..3ce0fe4d691 --- /dev/null +++ b/i18n/pt-BR/docusaurus-plugin-content-docs/current/logto-cloud/automate-tenant-creation.mdx @@ -0,0 +1,245 @@ +--- +id: automate-tenant-creation +title: Automatizar o gerenciamento de tenants +sidebar_position: 8 +--- + +# Automatizar o gerenciamento de tenants + +Você pode gerenciar tenants do Logto Cloud programaticamente, incluindo criar tenants e continuar a configuração sem precisar alternar para o Console. + +Isso é útil quando você precisa provisionar tenants a partir do seu próprio fluxo de onboarding, plataforma interna, agente de IA ou automação de integração. + +O fluxo de automação é: + +1. Use um **Logto Cloud Personal Access Token (PAT)** para chamar a API do Logto Cloud. +2. Crie um tenant com `POST /api/tenants`. +3. Leia as credenciais padrão do aplicativo máquina para máquina (M2M) da resposta de criação. +4. Use o aplicativo M2M padrão para obter um token de acesso da Management API para o novo tenant. +5. Chame a Management API do novo tenant para continuar o provisionamento de aplicativos, usuários, papéis, recursos, organizações e outras configurações. + +## Antes de começar \{#before-you-start} + +Prepare os seguintes valores: + +| Variable | Description | +| -------------------- | --------------------------------------------------------------------------------- | +| `CLOUD_API_ENDPOINT` | O endpoint da API do Logto Cloud. Para Logto Cloud, use `https://cloud.logto.io`. | +| `LOGTO_CLOUD_PAT` | Um PAT para sua conta Logto Cloud. | +| `TENANT_NAME` | O nome de exibição do tenant a ser criado. | +| `TENANT_TAG` | O tipo do tenant. Use `development` ou `production`. | +| `REGION_NAME` | O identificador da região para o tenant. | + +Defina-os como variáveis de ambiente: + +```bash +export CLOUD_API_ENDPOINT="https://cloud.logto.io" +export LOGTO_CLOUD_PAT="" +export TENANT_NAME="Meu tenant automatizado" +export TENANT_TAG="development" +export REGION_NAME="" +``` + +## Obter regiões disponíveis \{#get-available-regions} + +Antes de criar um tenant, busque as regiões disponíveis para sua conta Logto Cloud: + +```bash +curl "$CLOUD_API_ENDPOINT/api/me/regions" \ + -H "Authorization: Bearer $LOGTO_CLOUD_PAT" +``` + +A resposta contém as regiões disponíveis. Use o valor `name` como `REGION_NAME` ao criar o tenant. + +Exemplo de resposta: + +```json +{ + "regions": [ + { + "name": "EU", + "displayName": "Europe" + }, + { + "name": "US", + "displayName": "United States" + } + ] +} +``` + +## Criar um tenant \{#create-a-tenant} + +Chame `POST /api/tenants` com o Logto Cloud PAT: + +```bash +curl "$CLOUD_API_ENDPOINT/api/tenants" \ + -X POST \ + -H "Authorization: Bearer $LOGTO_CLOUD_PAT" \ + -H "Content-Type: application/json" \ + -d '{ + "name": "'"$TENANT_NAME"'", + "tag": "'"$TENANT_TAG"'", + "regionName": "'"$REGION_NAME"'" + }' +``` + +A resposta inclui o tenant criado e um aplicativo M2M padrão. O aplicativo M2M é criado no novo tenant e tem acesso à Management API do tenant. + +Exemplo de resposta: + +```json +{ + "id": "new-tenant-id", + "name": "Meu tenant automatizado", + "tag": "development", + "indicator": "https://new-tenant-id.logto.app", + "regionName": "EU", + "defaultApplication": { + "id": "default-m2m-app-id", + "secret": "default-m2m-app-secret" + } +} +``` + +Salve os valores necessários para o próximo passo: + +```bash +export TENANT_ID="" +export TENANT_ENDPOINT="" +export DEFAULT_M2M_APP_ID="" +export DEFAULT_M2M_APP_SECRET="" +``` + +## Obter um token de acesso da Management API para o novo tenant \{#get-a-management-api-access-token-for-the-new-tenant} + +Use as credenciais do aplicativo M2M padrão para solicitar um token de acesso do novo tenant: + +```bash +curl "$TENANT_ENDPOINT/oidc/token" \ + -X POST \ + -u "$DEFAULT_M2M_APP_ID:$DEFAULT_M2M_APP_SECRET" \ + -H "Content-Type: application/x-www-form-urlencoded" \ + -d "grant_type=client_credentials" \ + -d "resource=$TENANT_ENDPOINT/api" \ + -d "scope=all" +``` + +Exemplo de resposta: + +```json +{ + "access_token": "eyJ...", + "expires_in": 3600, + "token_type": "Bearer", + "scope": "all" +} +``` + +Salve o token de acesso: + +```bash +export MANAGEMENT_API_ACCESS_TOKEN="" +``` + +## Continue o provisionamento do novo tenant \{#continue-provisioning-the-new-tenant} + +Use o token de acesso da Management API para chamar a Management API do novo tenant. + +Por exemplo, listar aplicativos: + +```bash +curl "$TENANT_ENDPOINT/api/applications" \ + -H "Authorization: Bearer $MANAGEMENT_API_ACCESS_TOKEN" +``` + +Ou criar um aplicativo: + +```bash +curl "$TENANT_ENDPOINT/api/applications" \ + -X POST \ + -H "Authorization: Bearer $MANAGEMENT_API_ACCESS_TOKEN" \ + -H "Content-Type: application/json" \ + -d '{ + "name": "Meu aplicativo web", + "type": "SPA", + "oidcClientMetadata": { + "redirectUris": ["https://example.com/callback"], + "postLogoutRedirectUris": ["https://example.com"] + } + }' +``` + +Neste ponto, sua automação pode continuar com qualquer operação da Management API, como criar usuários, aplicativos, recursos de API, papéis, organizações, conectores ou configurações da experiência de login. + +## Exemplo de automação completa \{#full-automation-example} + +O exemplo a seguir em Node.js cria um tenant, troca as credenciais M2M padrão retornadas por um token de acesso da Management API e lista os aplicativos no novo tenant: + +```js +const cloudApiEndpoint = 'https://cloud.logto.io'; +const logtoCloudPat = process.env.LOGTO_CLOUD_PAT; + +// Cria o tenant +const createTenantResponse = await fetch(`${cloudApiEndpoint}/api/tenants`, { + method: 'POST', + headers: { + authorization: `Bearer ${logtoCloudPat}`, + 'content-type': 'application/json', + }, + body: JSON.stringify({ + name: 'Meu tenant automatizado', + tag: 'development', + regionName: 'EU', + }), +}); + +if (!createTenantResponse.ok) { + throw new Error(`Falha ao criar tenant: ${await createTenantResponse.text()}`); +} + +const tenant = await createTenantResponse.json(); +const tenantEndpoint = tenant.indicator; +const { id: appId, secret: appSecret } = tenant.defaultApplication; + +// Solicita o token de acesso da Management API +const tokenResponse = await fetch(`${tenantEndpoint}/oidc/token`, { + method: 'POST', + headers: { + authorization: `Basic ${Buffer.from(`${appId}:${appSecret}`).toString('base64')}`, + 'content-type': 'application/x-www-form-urlencoded', + }, + body: new URLSearchParams({ + grant_type: 'client_credentials', + resource: `${tenantEndpoint}/api`, + scope: 'all', + }), +}); + +if (!tokenResponse.ok) { + throw new Error(`Falha ao obter token da Management API: ${await tokenResponse.text()}`); +} + +const { access_token: managementApiAccessToken } = await tokenResponse.json(); + +// Lista os aplicativos do novo tenant +const applicationsResponse = await fetch(`${tenantEndpoint}/api/applications`, { + headers: { + authorization: `Bearer ${managementApiAccessToken}`, + }, +}); + +if (!applicationsResponse.ok) { + throw new Error(`Falha ao listar aplicativos: ${await applicationsResponse.text()}`); +} + +const applications = await applicationsResponse.json(); + +console.log({ tenantId: tenant.id, applications }); +``` + +## Recursos relacionados \{#related-resources} + +- [Personal access token](/user-management/personal-access-token) +- [Interagir com a Management API](/integrate-logto/interact-with-management-api) +- [Guia rápido de máquina para máquina](/quick-starts/m2m) diff --git a/i18n/th/docusaurus-plugin-content-docs/current/integrate-logto/protected-app.mdx b/i18n/th/docusaurus-plugin-content-docs/current/integrate-logto/protected-app.mdx index 3bee9598464..8a5ab6cebe0 100644 --- a/i18n/th/docusaurus-plugin-content-docs/current/integrate-logto/protected-app.mdx +++ b/i18n/th/docusaurus-plugin-content-docs/current/integrate-logto/protected-app.mdx @@ -1,5 +1,5 @@ --- -description: เพิ่มการยืนยันตัวตนแบบไม่ต้องเขียนโค้ดให้กับเว็บแอปของคุณได้อย่างง่ายดายด้วย Protected App อันล้ำสมัยของ Logto ที่ขับเคลื่อนโดย Cloudflare รองรับ HTTP Basic Authentication และการตรวจสอบ JWT +description: เพิ่มการยืนยันตัวตนแบบไม่ต้องเขียนโค้ดให้กับเว็บแอปของคุณอย่างง่ายดายด้วย Protected App อันล้ำสมัยของ Logto ขับเคลื่อนโดย Cloudflare รองรับ HTTP Basic Authentication และการตรวจสอบ JWT sidebar_label: Protected App sidebar_position: 2 --- @@ -10,34 +10,34 @@ Protected App ถูกออกแบบมาเพื่อลดความ ## Protected App ทำงานอย่างไร \{#how-protected-app-works} -Protected App ที่ขับเคลื่อนโดย Cloudflare ทำงานทั่วโลกบน edge networks เพื่อให้แน่ใจว่าแอปของคุณมี latency ต่ำและพร้อมใช้งานสูง +Protected App ขับเคลื่อนโดย Cloudflare ทำงานทั่วโลกบน edge networks เพื่อให้แอปของคุณมี latency ต่ำและความพร้อมใช้งานสูง -Protected App จะดูแลสถานะเซสชันและข้อมูลผู้ใช้ หากผู้ใช้ยังไม่ได้รับการยืนยันตัวตน Protected App จะเปลี่ยนเส้นทางไปยังหน้าลงชื่อเข้าใช้ เมื่อได้รับการยืนยันตัวตนแล้ว Protected App จะห่อหุ้มคำขอของผู้ใช้ด้วยข้อมูลการยืนยันตัวตนและข้อมูลผู้ใช้ จากนั้นจึงส่งต่อไปยัง origin server +Protected App จะดูแลสถานะเซสชันและข้อมูลผู้ใช้ หากผู้ใช้ยังไม่ได้รับการยืนยันตัวตน Protected App จะเปลี่ยนเส้นทางไปยังหน้าลงชื่อเข้าใช้ เมื่อได้รับการยืนยันตัวตนแล้ว Protected App จะแนบคำขอของผู้ใช้พร้อมข้อมูลการยืนยันตัวตนและข้อมูลผู้ใช้ แล้วส่งต่อไปยัง origin server -กระบวนการนี้แสดงในแผนผังลำดับขั้นต่อไปนี้: +กระบวนการนี้แสดงในแผนภาพ flowchart ด้านล่าง: ```mermaid graph LR - A("ไคลเอนต์
(เบราว์เซอร์)") -->|คำขอ| B(Logto
Protected App) + A("ไคลเอนต์
(เบราว์เซอร์)") -->|Request| B(Logto
Protected App) B --> Condition{{เส้นทาง
ตรงกันหรือไม่?}} - Condition -->|ใช่| Matched{{ได้รับการยืนยันตัวตนหรือไม่?}} - Matched -->|ใช่| C(Origin server) - Matched -->|ไม่ใช่| D(Logto sign-in) - Condition -->|ไม่ใช่| C + Condition -->|Yes| Matched{{ได้รับการยืนยันตัวตนหรือไม่?}} + Matched -->|Yes| C(Origin server) + Matched -->|No| D(Logto sign-in) + Condition -->|No| C ``` ## ปกป้อง origin server ของคุณ \{#protect-your-origin-server} -Origin server ซึ่งอาจเป็นอุปกรณ์จริงหรือเสมือนที่ไม่ได้เป็นเจ้าของโดย Protected App ของ Logto คือที่ที่เนื้อหาแอปของคุณอยู่ คล้ายกับเซิร์ฟเวอร์ Content Delivery Network (CDN) โดย Protected App จะจัดการกระบวนการยืนยันตัวตนและดึงเนื้อหาจาก origin server ของคุณ ดังนั้น หากผู้ใช้เข้าถึง origin server ได้โดยตรง พวกเขาจะสามารถข้ามการยืนยันตัวตนและแอปของคุณจะไม่ปลอดภัยอีกต่อไป +Origin server ซึ่งอาจเป็นอุปกรณ์จริงหรือเสมือนที่ไม่ได้เป็นเจ้าของโดย Protected App ของ Logto คือที่ที่เนื้อหาแอปของคุณอยู่ เช่นเดียวกับเซิร์ฟเวอร์ Content Delivery Network (CDN) Protected App จะจัดการกระบวนการยืนยันตัวตนและดึงเนื้อหาจาก origin server ของคุณ ดังนั้น หากผู้ใช้เข้าถึง origin server ได้โดยตรง พวกเขาจะข้ามการยืนยันตัวตนและแอปของคุณจะไม่ปลอดภัยอีกต่อไป -ดังนั้นจึงสำคัญมากที่จะต้องรักษาความปลอดภัยของการเชื่อมต่อกับ origin เพื่อป้องกันไม่ให้ผู้โจมตีค้นพบและเข้าถึง origin server ของคุณโดยไม่มีการยืนยันตัวตน มีหลายวิธีในการทำเช่นนี้: +ดังนั้นจึงสำคัญมากที่จะต้องรักษาความปลอดภัยของการเชื่อมต่อกับ origin เพื่อป้องกันไม่ให้ผู้โจมตีค้นพบและเข้าถึง origin server ของคุณโดยไม่ผ่านการยืนยันตัวตน มีวิธีการดังนี้: 1. การตรวจสอบ HTTP Header 2. การตรวจสอบ JSON Web Tokens (JWT) ### การตรวจสอบ HTTP Header \{#http-header-validation} -การรักษาความปลอดภัย origin server ของคุณสามารถทำได้โดยใช้ [HTTP Basic Authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication#basic_authentication_scheme) เพื่อปกป้อง origin server +การรักษาความปลอดภัย origin server ของคุณสามารถทำได้โดยใช้ [HTTP Basic Authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication#basic_authentication_scheme) ทุกคำขอจาก Protected App จะมี header ดังนี้: @@ -49,14 +49,14 @@ Authorization: Basic base64(appId:appSecret) หากคุณใช้ Nginx หรือ Apache สามารถดูคู่มือเหล่านี้เพื่อใช้งาน HTTP Basic Authentication บน origin server ของคุณ: -1. Nginx: [การตั้งค่า HTTP Basic Authentication](https://docs.nginx.com/nginx/admin-guide/security-controls/configuring-http-basic-authentication/) +1. Nginx: [Configuring HTTP Basic Authentication](https://docs.nginx.com/nginx/admin-guide/security-controls/configuring-http-basic-authentication/) 2. Apache: [Authentication and Authorization](https://httpd.apache.org/docs/2.4/howto/auth.html) -หากต้องการตรวจสอบ header ภายในแอปของคุณ ดูตัวอย่าง [HTTP Basic Authentication](https://developers.cloudflare.com/workers/examples/basic-auth/) ที่ Cloudflare ให้ไว้เพื่อเรียนรู้วิธีจำกัดการเข้าถึงด้วย HTTP Basic schema +หากต้องการตรวจสอบ header ในแอปของคุณ ดูตัวอย่าง [HTTP Basic Authentication](https://developers.cloudflare.com/workers/examples/basic-auth/) ที่ Cloudflare ให้ไว้เพื่อเรียนรู้วิธีจำกัดการเข้าถึงด้วย schema HTTP Basic ### การตรวจสอบ JSON Web Tokens (JWT) \{#json-web-tokens-jwt-validation} -อีกวิธีหนึ่งในการรักษาความปลอดภัย origin server ของคุณคือการใช้ JSON Web Tokens (JWT) +อีกวิธีในการรักษาความปลอดภัย origin server ของคุณคือการใช้ JSON Web Tokens (JWT) ทุกคำขอที่ได้รับการยืนยันตัวตนจาก Protected App จะมี header ดังนี้: @@ -64,15 +64,15 @@ Authorization: Basic base64(appId:appSecret) Logto-ID-Token: ``` -JWT นี้เรียกว่า [ID Token](https://auth.wiki/id-token) ซึ่งถูกลงนามโดย Logto และมีข้อมูลผู้ใช้อยู่ โดยการตรวจสอบ JWT นี้ คุณสามารถยืนยันได้ว่าคำขอมาจาก Protected App และปฏิเสธคำขอที่ไม่มี header นี้ +JWT นี้เรียกว่า [ID Token](https://auth.wiki/id-token) ซึ่งถูกลงนามโดย Logto และมีข้อมูลผู้ใช้ โดยการตรวจสอบ JWT นี้ คุณสามารถยืนยันได้ว่าคำขอมาจาก Protected App และปฏิเสธคำขอที่ไม่มี header นี้ โทเค็นนี้ถูกเข้ารหัสและลงนามเป็นโทเค็น [JWS](https://auth.wiki/jws) ขั้นตอนการตรวจสอบ: -1. [การตรวจสอบ JWT](https://datatracker.ietf.org/doc/html/rfc7519#section-7.2) -2. [การตรวจสอบลายเซ็น JWS](https://datatracker.ietf.org/doc/html/rfc7515#section-5.2) -3. ผู้ออกโทเค็นคือ `https:///oidc` (ออกโดย Logto auth server ของคุณ) +1. [Validating a JWT](https://datatracker.ietf.org/doc/html/rfc7519#section-7.2) +2. [Validating the JWS signature](https://datatracker.ietf.org/doc/html/rfc7515#section-5.2) +3. ผู้ออกโทเค็น (Issuer) คือ `https:///oidc` (ออกโดย Logto auth server ของคุณ) ```js const express = require('express'); @@ -95,7 +95,7 @@ const getKey = (header, callback) => { const verifyToken = (req, res, next) => { const token = req.headers['Logto-ID-Token']; - // ตรวจสอบว่าคำขอที่เข้ามามี header โทเค็นของเราหรือไม่ + // ตรวจสอบว่าคำขอที่เข้ามามี header token ของเราหรือไม่ if (!token) { return res .status(403) @@ -127,7 +127,7 @@ app.listen(3000); หากคุณต้องการรับข้อมูลการยืนยันตัวตนและข้อมูลผู้ใช้สำหรับแอปของคุณ คุณสามารถใช้ header `Logto-ID-Token` ได้เช่นกัน -หากคุณต้องการเพียงแค่ถอดรหัสโทเค็น สามารถใช้โค้ดต่อไปนี้: +หากคุณต้องการเพียงแค่ถอดรหัสโทเค็น สามารถใช้โค้ดตัวอย่างนี้: ```js const express = require('express'); @@ -166,18 +166,35 @@ app.get('/', (req, res) => { app.listen(3000); ``` +## ปรับแต่งการอ้างสิทธิ์ของ ID token \{#customize-id-token-claims} + +โดยปกติ header `Logto-ID-Token` จะมีการอ้างสิทธิ์ OIDC มาตรฐาน (เช่น `sub`, `name`, และ `email`) หากต้องการเพิ่ม [การอ้างสิทธิ์เพิ่มเติม](/developers/custom-id-token#extended-claims) เช่น บทบาท (roles) หรือข้อมูลองค์กร ต้องตั้งค่าทั้งสองส่วนนี้: + +1. **Tenant toggle**: เปิดใช้งานการอ้างสิทธิ์ใน Console > Custom JWT > ID token +2. **Protected App scopes**: ในการตั้งค่า Protected App ของคุณ ให้เลือก scope ที่ตรงกันใน **ID token claims** > **Additional scopes** + +การอ้างสิทธิ์เพิ่มเติมจะถูกรวมใน ID token ที่ส่งต่อก็ต่อเมื่อเปิดใช้งานใน Custom JWT และเลือก scope ที่เกี่ยวข้องสำหรับ Protected App ดู [Custom ID token](/developers/custom-id-token) สำหรับรายการ scope และการอ้างสิทธิ์เพิ่มเติมทั้งหมด + +| ขอบเขต (Scope) | การอ้างสิทธิ์ (Claims) | +| ------------------------------------ | ------------------------------------ | +| `custom_data` | `custom_data` | +| `identities` | `identities`, `sso_identities` | +| `roles` | `roles` | +| `urn:logto:scope:organizations` | `organizations`, `organization_data` | +| `urn:logto:scope:organization_roles` | `organization_roles` | + ## รับ host ต้นทางเดิม \{#get-the-original-host} หากคุณต้องการรับ host ต้นทางที่ไคลเอนต์ร้องขอ สามารถใช้ header `Logto-Host` หรือ `x-forwarded-host` ## ปรับแต่งกฎการยืนยันตัวตน \{#customize-authentication-rules} -โดยปกติ Protected App จะปกป้องทุกเส้นทาง หากคุณต้องการปรับแต่งกฎการยืนยันตัวตน สามารถตั้งค่าในฟิลด์ "Custom authentication rules" ใน Console +โดยปกติ Protected App จะปกป้องทุกเส้นทาง หากคุณต้องการปรับแต่งกฎการยืนยันตัวตน สามารถตั้งค่าในช่อง "Custom authentication rules" ใน Console รองรับ regular expressions ตัวอย่างกรณีการใช้งาน: 1. เพื่อปกป้องเฉพาะเส้นทาง `/admin` และ `/privacy` ด้วยการยืนยันตัวตน: `^/(admin|privacy)/.*` -2. เพื่อยกเว้นภาพ JPG จากการยืนยันตัวตน: `^(?!.*\.jpg$).*$` +2. เพื่อยกเว้นไฟล์ภาพ JPG จากการยืนยันตัวตน: `^(?!.*\.jpg$).*$` ## การพัฒนาแบบ local \{#local-development} @@ -185,7 +202,7 @@ Protected App ถูกออกแบบมาให้ทำงานร่ว ## การเปลี่ยนไปใช้การผสาน SDK \{#transition-to-sdk-integration} -Protected App ถูกออกแบบมาเพื่อให้ง่ายต่อการยืนยันตัวตน อย่างไรก็ตาม หากคุณต้องการเปลี่ยนไปใช้การผสาน SDK เพื่อการควบคุมและปรับแต่งที่มากขึ้น คุณสามารถ [สร้างแอปใหม่](/integrate-logto/integrate-logto-into-your-application) ใน Logto และตั้งค่า [การผสาน SDK](/quick-starts) และเพื่อให้เปลี่ยนผ่านได้อย่างราบรื่น คุณสามารถนำ config ของแอปจาก Protected App มาใช้ซ้ำได้ โดย Protected App จริง ๆ แล้วคือ "Traditional Web App" ใน Logto คุณสามารถดู "[AppId](/integrate-logto/application-data-structure#application-id)" และ "[AppSecret](/integrate-logto/application-data-structure#application-secret)" ได้ในหน้าตั้งค่าแอป หลังจากเปลี่ยนผ่านเสร็จแล้ว คุณสามารถลบ Protected App ออกจากแอปของคุณได้ +Protected App ถูกออกแบบมาเพื่อให้ง่ายต่อการยืนยันตัวตน อย่างไรก็ตาม หากคุณต้องการเปลี่ยนไปใช้การผสาน SDK เพื่อการควบคุมและปรับแต่งที่มากขึ้น คุณสามารถ [สร้างแอปใหม่](/integrate-logto/integrate-logto-into-your-application) ใน Logto และตั้งค่า [การผสาน SDK](/quick-starts) และเพื่อให้เปลี่ยนผ่านได้อย่างราบรื่น คุณสามารถนำ config ของแอปจาก Protected App ไปใช้ซ้ำได้ โดย Protected App จริง ๆ แล้วคือ "Traditional Web App" ใน Logto คุณสามารถดู "[AppId](/integrate-logto/application-data-structure#application-id)" และ "[AppSecret](/integrate-logto/application-data-structure#application-secret)" ได้ในหน้าตั้งค่าแอป หลังจากเปลี่ยนผ่านเสร็จแล้ว คุณสามารถลบ Protected App ออกจากแอปของคุณได้ ## แหล่งข้อมูลที่เกี่ยวข้อง \{#related-resources} diff --git a/i18n/th/docusaurus-plugin-content-docs/current/logto-cloud/README.mdx b/i18n/th/docusaurus-plugin-content-docs/current/logto-cloud/README.mdx index 7342d309c90..2ec1a0faefa 100644 --- a/i18n/th/docusaurus-plugin-content-docs/current/logto-cloud/README.mdx +++ b/i18n/th/docusaurus-plugin-content-docs/current/logto-cloud/README.mdx @@ -3,12 +3,13 @@ import Developer from '@site/src/assets/developer.svg'; import TenantMemberManagement from '@site/src/assets/gear.svg'; import PricingAndBilling from '@site/src/assets/key.svg'; import McpIcon from '@site/src/assets/mcp.svg'; +import TenantAutomation from '@site/src/assets/robot.svg'; import CustomDomains from '@site/src/assets/search.svg'; import SystemLimit from '@site/src/assets/security.svg'; # Logto Cloud -[Logto Cloud](https://cloud.logto.io) ให้บริการด้านการจัดการและการดำเนินงานที่หลากหลาย เพื่อช่วยให้คุณบริหารจัดการเอกลักษณ์และทรัพยากรได้อย่างราบรื่นและง่ายดาย โดยโฮสต์โดย Logto ซึ่งประกอบด้วยฟีเจอร์ต่าง ๆ เช่น [รองรับหลายภูมิภาค](/logto-cloud/tenant-settings#tenant-region), การจัดการผู้เช่า (tenant management), [การเรียกเก็บเงินและราคา](/logto-cloud/billing-and-pricing), [การจัดการสมาชิกผู้เช่า](/logto-cloud/tenant-member-management), และการควบคุมการเข้าถึงตามบทบาท (RBAC) สำหรับคอนโซล +[Logto Cloud](https://cloud.logto.io) ให้บริการด้านการจัดการและการดำเนินงานที่หลากหลาย เพื่อช่วยให้คุณจัดการเอกลักษณ์และทรัพยากรได้อย่างราบรื่นและง่ายดาย โดยโฮสต์โดย Logto ซึ่งประกอบด้วยฟีเจอร์ต่าง ๆ เช่น [รองรับหลายภูมิภาค](/logto-cloud/tenant-settings#tenant-region), การจัดการ tenant, [การเรียกเก็บเงินและราคา](/logto-cloud/billing-and-pricing), [การจัดการสมาชิก tenant](/logto-cloud/tenant-member-management), และการควบคุมการเข้าถึงคอนโซลตามบทบาท (RBAC) หากคุณมีคำถามเกี่ยวกับบริการคลาวด์และต้องการความช่วยเหลือเพิ่มเติม กรุณาติดต่อเรา @@ -18,28 +19,28 @@ import SystemLimit from '@site/src/assets/security.svg'; items={[ { type: 'link', - label: 'การตั้งค่าผู้เช่า', + label: 'การตั้งค่า tenant', href: '/logto-cloud/tenant-settings', - description: 'อัปเดตหรือเปลี่ยนชื่อผู้เช่า ตรวจสอบภูมิภาค และลบหรือออกจากผู้เช่า', + description: 'อัปเดตหรือเปลี่ยนชื่อ tenant, ตรวจสอบภูมิภาค และลบหรือออกจาก tenant', customProps: { icon: , }, }, { type: 'link', - label: 'นโยบายการเก็บข้อมูลผู้เช่า Dev', + label: 'นโยบายการเก็บข้อมูล tenant สำหรับนักพัฒนา', href: '/logto-cloud/dev-tenant-data-retention', description: - 'ทำความเข้าใจนโยบายการเก็บข้อมูลผู้ใช้ 90 วันสำหรับผู้เช่า Dev และวิธีใช้ Logto dev tenant อย่างมีประสิทธิภาพ', + 'ทำความเข้าใจนโยบายการเก็บข้อมูลผู้ใช้ 90 วันสำหรับ dev tenant และวิธีใช้ Logto dev tenant อย่างมีประสิทธิภาพ', customProps: { icon: , }, }, { type: 'link', - label: 'การจัดการสมาชิกผู้เช่า', + label: 'การจัดการสมาชิก tenant', href: '/logto-cloud/tenant-member-management', - description: 'ผู้ดูแลผู้เช่าสามารถเชิญและจัดการสมาชิก รวมถึงอัปเดตบทบาทของพวกเขาได้', + description: 'ผู้ดูแล tenant สามารถเชิญและจัดการสมาชิก รวมถึงอัปเดตบทบาทของพวกเขาได้', customProps: { icon: , }, @@ -49,7 +50,7 @@ import SystemLimit from '@site/src/assets/security.svg'; label: 'โดเมนแบบกำหนดเอง', href: '/logto-cloud/custom-domain', description: - 'ใช้โดเมนของคุณเองสำหรับผู้เช่า Logto เพื่อให้ประสบการณ์ผู้ใช้ปลายทางสอดคล้องกับแบรนด์ของคุณ', + 'ใช้โดเมนของคุณเองสำหรับ Logto tenant เพื่อให้ประสบการณ์ผู้ใช้ปลายทางของคุณสอดคล้องกับแบรนด์', customProps: { icon: , }, @@ -68,17 +69,26 @@ import SystemLimit from '@site/src/assets/security.svg'; label: 'ขีดจำกัดของระบบ', href: '/logto-cloud/system-limit', description: - 'ทำความเข้าใจขีดจำกัดของระบบและการป้องกันอัตราสำหรับผู้เช่า Dev, Pro และ Enterprise', + 'ทำความเข้าใจขีดจำกัดของระบบและการป้องกันอัตราสำหรับ Dev, Pro และ Enterprise tenant', customProps: { icon: , }, }, + { + type: 'link', + label: 'การจัดการ tenant อัตโนมัติ', + href: '/logto-cloud/automate-tenant-creation', + description: 'สร้างและจัดการ tenant แบบโปรแกรมด้วย Logto Cloud API และ Management API', + customProps: { + icon: , + }, + }, { type: 'link', label: 'Logto MCP Server', href: '/logto-cloud/logto-mcp-server', description: - 'เชื่อมต่อเครื่องมือ AI และ IDEs กับ Logto Cloud ผ่าน MCP เพื่อจัดการทรัพยากรและผสานรวมการยืนยันตัวตน (Authentication)', + 'เชื่อมต่อเครื่องมือ AI และ IDE กับ Logto Cloud ผ่าน MCP เพื่อจัดการทรัพยากรและผสานการยืนยันตัวตน', customProps: { icon: , }, diff --git a/i18n/th/docusaurus-plugin-content-docs/current/logto-cloud/automate-tenant-creation.mdx b/i18n/th/docusaurus-plugin-content-docs/current/logto-cloud/automate-tenant-creation.mdx new file mode 100644 index 00000000000..07102da6da1 --- /dev/null +++ b/i18n/th/docusaurus-plugin-content-docs/current/logto-cloud/automate-tenant-creation.mdx @@ -0,0 +1,242 @@ +--- +id: automate-tenant-creation +title: จัดการผู้เช่าแบบอัตโนมัติ +sidebar_position: 8 +--- + +# จัดการผู้เช่าแบบอัตโนมัติ + +คุณสามารถจัดการผู้เช่า Logto Cloud แบบโปรแกรมมิ่งได้ รวมถึงการสร้างผู้เช่าและดำเนินการตั้งค่าต่อโดยไม่ต้องสลับไปที่ Console + +สิ่งนี้มีประโยชน์เมื่อคุณต้องการจัดเตรียมผู้เช่าจากกระบวนการ onboarding ของคุณเอง แพลตฟอร์มภายใน ตัวแทน AI หรือระบบอัตโนมัติแบบบูรณาการ + +ขั้นตอนการอัตโนมัติคือ: + +1. ใช้ **Logto Cloud Personal Access Token (PAT)** เพื่อเรียก Logto Cloud API +2. สร้างผู้เช่าด้วย `POST /api/tenants` +3. อ่านข้อมูลรับรองแอป Machine-to-machine (M2M) เริ่มต้นจากผลลัพธ์การสร้าง +4. ใช้แอป M2M เริ่มต้นเพื่อขอรับโทเค็นการเข้าถึง Management API สำหรับผู้เช่าใหม่ +5. เรียก Management API ของผู้เช่าใหม่เพื่อดำเนินการจัดเตรียมแอปพลิเคชัน ผู้ใช้ บทบาท ทรัพยากร องค์กร และการตั้งค่าอื่น ๆ ต่อไป + +## ก่อนเริ่มต้น \{#before-you-start} + +เตรียมค่าต่อไปนี้: + +| Variable | Description | +| -------------------- | -------------------------------------------------------------------------- | +| `CLOUD_API_ENDPOINT` | จุดปลายทาง Logto Cloud API สำหรับ Logto Cloud ใช้ `https://cloud.logto.io` | +| `LOGTO_CLOUD_PAT` | PAT สำหรับบัญชี Logto Cloud ของคุณ | +| `TENANT_NAME` | ชื่อที่แสดงของผู้เช่าที่จะสร้าง | +| `TENANT_TAG` | ประเภทของผู้เช่า ใช้ `development` หรือ `production` | +| `REGION_NAME` | ตัวระบุภูมิภาคสำหรับผู้เช่า | + +ตั้งค่าเป็น environment variables: + +```bash +export CLOUD_API_ENDPOINT="https://cloud.logto.io" +export LOGTO_CLOUD_PAT="" +export TENANT_NAME="My automated tenant" +export TENANT_TAG="development" +export REGION_NAME="" +``` + +## รับภูมิภาคที่มีให้เลือก \{#get-available-regions} + +ก่อนสร้างผู้เช่า ให้ดึงข้อมูลภูมิภาคที่บัญชี Logto Cloud ของคุณสามารถใช้ได้: + +```bash +curl "$CLOUD_API_ENDPOINT/api/me/regions" \ + -H "Authorization: Bearer $LOGTO_CLOUD_PAT" +``` + +ผลลัพธ์จะมีภูมิภาคที่ใช้ได้ ใช้ค่า `name` เป็น `REGION_NAME` เมื่อสร้างผู้เช่า + +ตัวอย่างผลลัพธ์: + +```json +{ + "regions": [ + { + "name": "EU", + "displayName": "Europe" + }, + { + "name": "US", + "displayName": "United States" + } + ] +} +``` + +## สร้างผู้เช่า \{#create-a-tenant} + +เรียก `POST /api/tenants` พร้อม Logto Cloud PAT: + +```bash +curl "$CLOUD_API_ENDPOINT/api/tenants" \ + -X POST \ + -H "Authorization: Bearer $LOGTO_CLOUD_PAT" \ + -H "Content-Type: application/json" \ + -d '{ + "name": "'"$TENANT_NAME"'", + "tag": "'"$TENANT_TAG"'", + "regionName": "'"$REGION_NAME"'" + }' +``` + +ผลลัพธ์จะมีข้อมูลผู้เช่าที่สร้างและแอป M2M เริ่มต้น แอป M2M นี้ถูกสร้างในผู้เช่าใหม่และมีสิทธิ์เข้าถึง Management API ของผู้เช่านั้น + +ตัวอย่างผลลัพธ์: + +```json +{ + "id": "new-tenant-id", + "name": "My automated tenant", + "tag": "development", + "indicator": "https://new-tenant-id.logto.app", + "regionName": "EU", + "defaultApplication": { + "id": "default-m2m-app-id", + "secret": "default-m2m-app-secret" + } +} +``` + +บันทึกค่าที่ต้องใช้ในขั้นตอนถัดไป: + +```bash +export TENANT_ID="" +export TENANT_ENDPOINT="" +export DEFAULT_M2M_APP_ID="" +export DEFAULT_M2M_APP_SECRET="" +``` + +## ขอรับโทเค็นการเข้าถึง Management API สำหรับผู้เช่าใหม่ \{#get-a-management-api-access-token-for-the-new-tenant} + +ใช้ข้อมูลรับรองแอป M2M เริ่มต้นเพื่อขอโทเค็นการเข้าถึงจากผู้เช่าใหม่: + +```bash +curl "$TENANT_ENDPOINT/oidc/token" \ + -X POST \ + -u "$DEFAULT_M2M_APP_ID:$DEFAULT_M2M_APP_SECRET" \ + -H "Content-Type: application/x-www-form-urlencoded" \ + -d "grant_type=client_credentials" \ + -d "resource=$TENANT_ENDPOINT/api" \ + -d "scope=all" +``` + +ตัวอย่างผลลัพธ์: + +```json +{ + "access_token": "eyJ...", + "expires_in": 3600, + "token_type": "Bearer", + "scope": "all" +} +``` + +บันทึก access token: + +```bash +export MANAGEMENT_API_ACCESS_TOKEN="" +``` + +## ดำเนินการจัดเตรียมผู้เช่าใหม่ต่อ \{#continue-provisioning-the-new-tenant} + +ใช้ Management API access token เพื่อเรียก Management API ของผู้เช่าใหม่ + +ตัวอย่างเช่น แสดงรายการแอปพลิเคชัน: + +```bash +curl "$TENANT_ENDPOINT/api/applications" \ + -H "Authorization: Bearer $MANAGEMENT_API_ACCESS_TOKEN" +``` + +หรือสร้างแอปพลิเคชัน: + +```bash +curl "$TENANT_ENDPOINT/api/applications" \ + -X POST \ + -H "Authorization: Bearer $MANAGEMENT_API_ACCESS_TOKEN" \ + -H "Content-Type: application/json" \ + -d '{ + "name": "My web app", + "type": "SPA", + "oidcClientMetadata": { + "redirectUris": ["https://example.com/callback"], + "postLogoutRedirectUris": ["https://example.com"] + } + }' +``` + +ณ จุดนี้ ระบบอัตโนมัติของคุณสามารถดำเนินการกับ Management API ใด ๆ ต่อได้ เช่น การสร้างผู้ใช้ แอปพลิเคชัน ทรัพยากร API บทบาท องค์กร ตัวเชื่อมต่อ หรือการตั้งค่าประสบการณ์การลงชื่อเข้าใช้ + +## ตัวอย่างอัตโนมัติเต็มรูปแบบ \{#full-automation-example} + +ตัวอย่าง Node.js ต่อไปนี้จะสร้างผู้เช่า แลกเปลี่ยนข้อมูลรับรอง M2M เริ่มต้นที่ได้มาเป็นโทเค็นการเข้าถึง Management API และแสดงรายการแอปพลิเคชันในผู้เช่าใหม่: + +```js +const cloudApiEndpoint = 'https://cloud.logto.io'; +const logtoCloudPat = process.env.LOGTO_CLOUD_PAT; + +const createTenantResponse = await fetch(`${cloudApiEndpoint}/api/tenants`, { + method: 'POST', + headers: { + authorization: `Bearer ${logtoCloudPat}`, + 'content-type': 'application/json', + }, + body: JSON.stringify({ + name: 'My automated tenant', + tag: 'development', + regionName: 'EU', + }), +}); + +if (!createTenantResponse.ok) { + throw new Error(`Failed to create tenant: ${await createTenantResponse.text()}`); +} + +const tenant = await createTenantResponse.json(); +const tenantEndpoint = tenant.indicator; +const { id: appId, secret: appSecret } = tenant.defaultApplication; + +const tokenResponse = await fetch(`${tenantEndpoint}/oidc/token`, { + method: 'POST', + headers: { + authorization: `Basic ${Buffer.from(`${appId}:${appSecret}`).toString('base64')}`, + 'content-type': 'application/x-www-form-urlencoded', + }, + body: new URLSearchParams({ + grant_type: 'client_credentials', + resource: `${tenantEndpoint}/api`, + scope: 'all', + }), +}); + +if (!tokenResponse.ok) { + throw new Error(`Failed to get Management API token: ${await tokenResponse.text()}`); +} + +const { access_token: managementApiAccessToken } = await tokenResponse.json(); + +const applicationsResponse = await fetch(`${tenantEndpoint}/api/applications`, { + headers: { + authorization: `Bearer ${managementApiAccessToken}`, + }, +}); + +if (!applicationsResponse.ok) { + throw new Error(`Failed to list applications: ${await applicationsResponse.text()}`); +} + +const applications = await applicationsResponse.json(); + +console.log({ tenantId: tenant.id, applications }); +``` + +## แหล่งข้อมูลที่เกี่ยวข้อง \{#related-resources} + +- [Personal access token](/user-management/personal-access-token) +- [โต้ตอบกับ Management API](/integrate-logto/interact-with-management-api) +- [เริ่มต้น Machine-to-machine อย่างรวดเร็ว](/quick-starts/m2m) diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/integrate-logto/protected-app.mdx b/i18n/zh-CN/docusaurus-plugin-content-docs/current/integrate-logto/protected-app.mdx index 0203fc4fd34..7c53ea99d46 100644 --- a/i18n/zh-CN/docusaurus-plugin-content-docs/current/integrate-logto/protected-app.mdx +++ b/i18n/zh-CN/docusaurus-plugin-content-docs/current/integrate-logto/protected-app.mdx @@ -1,26 +1,26 @@ --- -description: 使用 Logto 创新的 Protected App,轻松为你的 Web 应用添加无代码认证 (Authentication),由 Cloudflare 提供支持。支持 HTTP 基本认证 (Authentication) 和 JWT 验证。 +description: 通过 Logto 创新的 Protected App(由 Cloudflare 提供支持),轻松为你的 Web 应用添加无代码认证 (Authentication)。支持 HTTP 基本认证 (Authentication) 和 JWT 验证。 sidebar_label: Protected App sidebar_position: 2 --- # Protected App — 非 SDK 认证 (Authentication) 集成 -Protected App 旨在通过将[认证 (Authentication)](https://auth.wiki/authentication)层与应用程序分离,消除 [SDK 集成](/quick-starts) 的复杂性。我们负责认证 (Authentication),让你专注于核心功能。一旦用户通过认证 (Authentication),Protected App 将从你的服务器提供内容。 +Protected App 旨在通过将[认证 (Authentication)](https://auth.wiki/authentication)层与应用程序分离,消除[SDK 集成](/quick-starts)的复杂性。我们负责认证 (Authentication),让你专注于核心功能。一旦用户通过认证 (Authentication),Protected App 就会从你的服务器提供内容。 -## Protected App 如何工作 \{#how-protected-app-works} +## Protected App 的工作原理 \{#how-protected-app-works} -由 Cloudflare 提供支持的 Protected App 在全球边缘网络上运行,确保你的应用程序具有低延迟和高可用性。 +Protected App 由 Cloudflare 提供支持,在全球边缘网络上运行,确保你的应用低延迟和高可用性。 -Protected App 维护会话状态和用户信息。如果用户未通过认证 (Authentication),Protected App 会将他们重定向到登录页面。一旦认证 (Authentication) 成功,Protected App 会将用户的请求与认证 (Authentication) 和用户信息一起包装,然后转发到源服务器。 +Protected App 会维护会话状态和用户信息。如果用户未通过认证 (Authentication),Protected App 会将其重定向到登录页面。认证 (Authentication) 成功后,Protected App 会将用户的请求附带认证 (Authentication) 和用户信息后转发到源服务器。 -以下流程图展示了这一过程: +此过程可通过以下流程图进行可视化: ```mermaid graph LR A("客户端
(浏览器)") -->|请求| B(Logto
Protected App) - B --> Condition{{路由
匹配吗?}} - Condition -->|是| Matched{{已认证 (Authenticated) 吗?}} + B --> Condition{{路由
匹配?}} + Condition -->|是| Matched{{已认证 (Authentication)?}} Matched -->|是| C(源服务器) Matched -->|否| D(Logto 登录) Condition -->|否| C @@ -28,51 +28,51 @@ graph LR ## 保护你的源服务器 \{#protect-your-origin-server} -源服务器可以是 Logto 的 Protected App 不拥有的物理或虚拟设备,是你的应用程序内容所在的位置。类似于内容分发网络 (CDN) 服务器,Protected App 管理认证 (Authentication) 过程并从你的源服务器检索内容。因此,如果用户直接访问你的源服务器,他们可以绕过认证 (Authentication),你的应用程序将不再受保护。 +源服务器可以是物理或虚拟设备,不属于 Logto 的 Protected App,存放你的应用内容。类似于内容分发网络 (CDN) 服务器,Protected App 管理认证 (Authentication) 流程并从你的源服务器获取内容。因此,如果用户可以直接访问你的源服务器,就能绕过认证 (Authentication),你的应用将不再受保护。 -因此,保护源连接非常重要,它可以防止攻击者在未经认证 (Authentication) 的情况下发现和访问你的源服务器。有几种方法可以做到这一点: +因此,保护源服务器连接非常重要,这可以防止攻击者在未认证 (Authentication) 的情况下发现并访问你的源服务器。常见的做法有: 1. HTTP 头验证 -2. JSON Web Tokens (JWT) 验证 +2. JSON Web Token (JWT) 验证 ### HTTP 头验证 \{#http-header-validation} -可以使用 [HTTP 基本认证 (Authentication)](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication#basic_authentication_scheme) 来保护你的源服务器。 +你可以使用 [HTTP 基本认证 (Authentication)](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication#basic_authentication_scheme) 来保护你的源服务器。 -每个来自 Protected App 的请求都包含以下头: +每个来自 Protected App 的请求都会包含如下头部: ``` Authorization: Basic base64(appId:appSecret) ``` -通过验证此头,你可以确认请求来自 Protected App,并拒绝任何不包含此头的请求。 +通过验证此头部,你可以确认请求来自 Protected App,并拒绝所有未包含此头部的请求。 如果你使用 Nginx 或 Apache,可以参考以下指南在源服务器上实现 HTTP 基本认证 (Authentication): 1. Nginx: [配置 HTTP 基本认证 (Authentication)](https://docs.nginx.com/nginx/admin-guide/security-controls/configuring-http-basic-authentication/) -2. Apache: [认证 (Authentication) 和授权 (Authorization)](https://httpd.apache.org/docs/2.4/howto/auth.html) +2. Apache: [认证 (Authentication) 与授权 (Authorization)](https://httpd.apache.org/docs/2.4/howto/auth.html) -要在应用程序中检查头,请参考 Cloudflare 提供的 [HTTP 基本认证 (Authentication) 示例](https://developers.cloudflare.com/workers/examples/basic-auth/)以了解如何使用 HTTP 基本模式限制访问。 +如需在应用程序中检查头部,请参考 Cloudflare 提供的 [HTTP Basic Authentication 示例](https://developers.cloudflare.com/workers/examples/basic-auth/),了解如何使用 HTTP Basic 方案限制访问。 -### JSON Web Tokens (JWT) 验证 \{#json-web-tokens-jwt-validation} +### JSON Web Token (JWT) 验证 \{#json-web-tokens-jwt-validation} -另一种保护源服务器的方法是使用 JSON Web Tokens (JWT)。 +另一种保护源服务器的方法是使用 JSON Web Token (JWT)。 -每个来自 Protected App 的认证 (Authenticated) 请求都包含以下头: +每个通过认证 (Authentication) 的 Protected App 请求都会包含如下头部: ``` Logto-ID-Token: ``` -JWT 被称为 [ID 令牌 (ID Token)](https://auth.wiki/id-token),由 Logto 签名并包含用户信息。通过验证此 JWT,你可以确认请求来自 Protected App,并拒绝任何不包含此头的请求。 +该 JWT 被称为 [ID 令牌 (ID token)](https://auth.wiki/id-token),由 Logto 签名并包含用户信息。通过验证此 JWT,你可以确认请求来自 Protected App,并拒绝所有未包含此头部的请求。 -令牌被加密并签名为 [JWS](https://auth.wiki/jws) 令牌。 +该令牌采用 [JWS](https://auth.wiki/jws) 令牌格式进行加密和签名。 -验证步骤: +验证步骤如下: 1. [验证 JWT](https://datatracker.ietf.org/doc/html/rfc7519#section-7.2) 2. [验证 JWS 签名](https://datatracker.ietf.org/doc/html/rfc7515#section-5.2) -3. 令牌的发行者是 `https:///oidc`(由你的 Logto 认证 (Auth) 服务器发行) +3. 令牌的发行者 (Issuer) 是 `https:///oidc`(由你的 Logto 认证 (Authentication) 服务器签发) ```js const express = require('express'); @@ -95,9 +95,9 @@ const getKey = (header, callback) => { const verifyToken = (req, res, next) => { const token = req.headers['Logto-ID-Token']; - // 确保传入的请求包含我们的令牌头 + // 确保传入请求包含我们的令牌头部 if (!token) { - return res.status(403).send({ status: false, message: '缺少必需的 Logto-ID-Token 头' }); + return res.status(403).send({ status: false, message: '缺少必需的 Logto-ID-Token 头部' }); } jwt.verify(token, getKey, { issuer: ISSUER }, (err, decoded) => { @@ -123,9 +123,9 @@ app.listen(3000); ## 获取认证 (Authentication) 状态和用户信息 \{#get-authentication-state-and-user-information} -如果你需要为应用程序获取认证 (Authentication) 和用户信息,也可以使用 `Logto-ID-Token` 头。 +如果你需要为应用获取认证 (Authentication) 和用户信息,也可以使用 `Logto-ID-Token` 头部。 -如果你只想解码令牌,可以使用以下代码: +如果你只想解码令牌,可以使用如下代码: ```js const express = require('express'); @@ -136,7 +136,7 @@ const decodeIdToken = (req, res, next) => { if (!token) { return res.status(403).send({ status: false, - message: '缺少必需的 Logto-ID-Token 头', + message: '缺少必需的 Logto-ID-Token 头部', }); } @@ -164,31 +164,48 @@ app.get('/', (req, res) => { app.listen(3000); ``` +## 自定义 ID 令牌 (ID token) 声明 (Claims) \{#customize-id-token-claims} + +默认情况下,`Logto-ID-Token` 头部包含标准 OIDC 声明 (Claims)(如 `sub`、`name` 和 `email`)。如需包含[扩展声明 (Claims)](/developers/custom-id-token#extended-claims)(如角色或组织数据),需同时配置以下两项: + +1. **租户开关**:在 控制台 > 自定义 JWT > ID 令牌 (ID token) 中启用该声明 (Claim)。 +2. **Protected App 权限 (Scopes)**:在 Protected App 设置中,于 **ID 令牌 (ID token) 声明 (Claims)** > **附加权限 (Scopes)** 选择对应权限 (Scope)。 + +仅当在自定义 JWT 中启用声明 (Claim) 且为 Protected App 选择了对应权限 (Scope) 时,扩展声明 (Claims) 才会包含在转发的 ID 令牌 (ID token) 中。完整扩展权限 (Scopes) 和声明 (Claims) 列表见 [自定义 ID 令牌 (ID token)](/developers/custom-id-token)。 + +| 权限 (Scope) | 声明 (Claims) | +| ------------------------------------ | ------------------------------------ | +| `custom_data` | `custom_data` | +| `identities` | `identities`, `sso_identities` | +| `roles` | `roles` | +| `urn:logto:scope:organizations` | `organizations`, `organization_data` | +| `urn:logto:scope:organization_roles` | `organization_roles` | + ## 获取原始主机 \{#get-the-original-host} -如果你需要获取客户端请求的原始主机,可以使用 `Logto-Host` 或 `x-forwarded-host` 头。 +如果你需要获取客户端请求的原始主机,可以使用 `Logto-Host` 或 `x-forwarded-host` 头部。 ## 自定义认证 (Authentication) 规则 \{#customize-authentication-rules} -默认情况下,Protected App 将保护所有路由。如果你需要自定义认证 (Authentication) 规则,可以在控制台中设置“自定义认证 (Authentication) 规则”字段。 +默认情况下,Protected App 会保护所有路由。如果你需要自定义认证 (Authentication) 规则,可以在控制台设置“自定义认证 (Authentication) 规则”字段。 -它支持正则表达式,以下是两个案例场景: +支持正则表达式,以下是两种场景示例: 1. 仅保护 `/admin` 和 `/privacy` 路由:`^/(admin|privacy)/.*` -2. 排除 JPG 图像的认证 (Authentication):`^(?!.*\.jpg$).*$` +2. 排除 JPG 图片不进行认证 (Authentication):`^(?!.*\.jpg$).*$` ## 本地开发 \{#local-development} -Protected App 旨在与源服务器一起工作。然而,如果你的源服务器无法公开访问,可以使用 [ngrok](https://ngrok.com/) 或 [Cloudflare Tunnels](https://developers.cloudflare.com/pages/how-to/preview-with-cloudflare-tunnel/) 等工具将本地服务器暴露到互联网。 +Protected App 设计用于与你的源服务器配合使用。如果你的源服务器无法公开访问,可以使用 [ngrok](https://ngrok.com/) 或 [Cloudflare Tunnels](https://developers.cloudflare.com/pages/how-to/preview-with-cloudflare-tunnel/) 等工具将本地服务器暴露到互联网。 -## 过渡到 SDK 集成 \{#transition-to-sdk-integration} +## 迁移到 SDK 集成 \{#transition-to-sdk-integration} -Protected App 旨在简化认证 (Authentication) 过程。然而,如果你决定过渡到 SDK 集成以获得更好的控制和定制,可以在 Logto 中[创建一个新应用程序](/integrate-logto/integrate-logto-into-your-application)并配置 [SDK 集成](/quick-starts)。为了顺利过渡,你可以重用 Protected App 的应用程序配置。Protected App 实际上是 Logto 中的“传统 Web 应用”,你可以在应用程序设置中找到“[AppId](/integrate-logto/application-data-structure#application-id)”和“[AppSecret](/integrate-logto/application-data-structure#application-secret)”。过渡完成后,你可以从应用程序中移除 Protected App。 +Protected App 旨在简化认证 (Authentication) 流程。但如果你希望获得更好的控制和自定义,可以选择迁移到 SDK 集成。你可以在 Logto 中[创建新应用](/integrate-logto/integrate-logto-into-your-application)并配置[SDK 集成](/quick-starts)。为顺利迁移,你可以复用 Protected App 的应用配置。Protected App 实际上是 Logto 中的“传统 Web 应用”,你可以在应用设置中找到 “[AppId](/integrate-logto/application-data-structure#application-id)” 和 “[AppSecret](/integrate-logto/application-data-structure#application-secret)”。迁移完成后,可以将 Protected App 从你的应用中移除。 ## 相关资源 \{#related-resources} - Protected App: 通过点击构建应用的认证 (Authentication)。无需代码。 + Protected App:几步构建你的应用认证 (Authentication),无需代码。 Protected App 背后的动机 diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/logto-cloud/README.mdx b/i18n/zh-CN/docusaurus-plugin-content-docs/current/logto-cloud/README.mdx index 7b808d05896..abdc8693a3e 100644 --- a/i18n/zh-CN/docusaurus-plugin-content-docs/current/logto-cloud/README.mdx +++ b/i18n/zh-CN/docusaurus-plugin-content-docs/current/logto-cloud/README.mdx @@ -3,12 +3,13 @@ import Developer from '@site/src/assets/developer.svg'; import TenantMemberManagement from '@site/src/assets/gear.svg'; import PricingAndBilling from '@site/src/assets/key.svg'; import McpIcon from '@site/src/assets/mcp.svg'; +import TenantAutomation from '@site/src/assets/robot.svg'; import CustomDomains from '@site/src/assets/search.svg'; import SystemLimit from '@site/src/assets/security.svg'; # Logto Cloud -[Logto Cloud](https://cloud.logto.io) 提供了一系列管理和运营服务,帮助你顺利且轻松地管理身份和资源。由 Logto 托管,包含了如[多区域支持](/logto-cloud/tenant-settings#tenant-region)、租户管理、[计费与定价](/logto-cloud/billing-and-pricing)、[成员管理](/logto-cloud/tenant-member-management)以及控制台基于角色的访问控制等功能。 +[Logto Cloud](https://cloud.logto.io) 提供了一系列管理和运营服务,帮助你顺畅、轻松地管理身份和资源。由 Logto 托管,包含 [多区域支持](/logto-cloud/tenant-settings#tenant-region)、租户管理、[计费与定价](/logto-cloud/billing-and-pricing)、[成员管理](/logto-cloud/tenant-member-management) 以及控制台基于角色的访问控制 (RBAC) 等功能。 如果你对云服务有任何疑问或需要额外支持,请联系我们。 @@ -38,7 +39,7 @@ import SystemLimit from '@site/src/assets/security.svg'; type: 'link', label: '租户成员管理', href: '/logto-cloud/tenant-member-management', - description: '租户管理员可以邀请和管理成员,并更新他们的角色。', + description: '租户管理员可以邀请和管理成员,并更新其角色。', customProps: { icon: , }, @@ -56,7 +57,7 @@ import SystemLimit from '@site/src/assets/security.svg'; type: 'link', label: '计费与定价', href: '/logto-cloud/billing-and-pricing', - description: '轻松了解你的账单,自信地管理你的订阅。', + description: '轻松了解你的账单,并自信地管理你的订阅。', customProps: { icon: , }, @@ -70,12 +71,21 @@ import SystemLimit from '@site/src/assets/security.svg'; icon: , }, }, + { + type: 'link', + label: '自动化租户管理', + href: '/logto-cloud/automate-tenant-creation', + description: '通过 Logto Cloud API 和 Management API 以编程方式创建和管理租户。', + customProps: { + icon: , + }, + }, { type: 'link', label: 'Logto MCP Server', href: '/logto-cloud/logto-mcp-server', description: - '通过 MCP 将 AI 工具和 IDE 连接到 Logto Cloud,以管理资源并集成认证 (Authentication)。', + '通过 MCP 将 AI 工具和 IDE 连接到 Logto Cloud,管理资源并集成认证 (Authentication)。', customProps: { icon: , }, diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/logto-cloud/automate-tenant-creation.mdx b/i18n/zh-CN/docusaurus-plugin-content-docs/current/logto-cloud/automate-tenant-creation.mdx new file mode 100644 index 00000000000..3a550055142 --- /dev/null +++ b/i18n/zh-CN/docusaurus-plugin-content-docs/current/logto-cloud/automate-tenant-creation.mdx @@ -0,0 +1,242 @@ +--- +id: automate-tenant-creation +title: 自动化租户管理 +sidebar_position: 8 +--- + +# 自动化租户管理 + +你可以通过编程方式管理 Logto Cloud 租户,包括创建租户并持续配置,无需切换到控制台 (Console)。 + +当你需要从自己的注册流程、内部平台、AI agent 或集成自动化中自动创建租户时,这非常有用。 + +自动化流程如下: + +1. 使用 **Logto Cloud 个人访问令牌 (PAT)** 调用 Logto Cloud API。 +2. 通过 `POST /api/tenants` 创建租户。 +3. 从创建响应中读取默认机器对机器 (M2M) 应用程序凭据。 +4. 使用默认 M2M 应用程序为新租户获取 Management API 访问令牌。 +5. 调用新租户的 Management API,继续配置应用程序、用户、角色、API 资源、组织 (Organizations) 及其他设置。 + +## 开始前的准备 \{#before-you-start} + +准备以下变量: + +| Variable | Description | +| -------------------- | ----------------------------------------------------------------------- | +| `CLOUD_API_ENDPOINT` | Logto Cloud API 端点。对于 Logto Cloud,使用 `https://cloud.logto.io`。 | +| `LOGTO_CLOUD_PAT` | 你的 Logto Cloud 账户的 PAT。 | +| `TENANT_NAME` | 要创建的租户显示名称。 | +| `TENANT_TAG` | 租户类型。使用 `development` 或 `production`。 | +| `REGION_NAME` | 租户的区域标识符。 | + +将它们设置为环境变量: + +```bash +export CLOUD_API_ENDPOINT="https://cloud.logto.io" +export LOGTO_CLOUD_PAT="" +export TENANT_NAME="我的自动化租户" +export TENANT_TAG="development" +export REGION_NAME="" +``` + +## 获取可用区域 \{#get-available-regions} + +在创建租户前,获取你的 Logto Cloud 账户可用的区域: + +```bash +curl "$CLOUD_API_ENDPOINT/api/me/regions" \ + -H "Authorization: Bearer $LOGTO_CLOUD_PAT" +``` + +响应中包含可用区域。创建租户时,使用 `name` 作为 `REGION_NAME`。 + +示例响应: + +```json +{ + "regions": [ + { + "name": "EU", + "displayName": "Europe" + }, + { + "name": "US", + "displayName": "United States" + } + ] +} +``` + +## 创建租户 \{#create-a-tenant} + +使用 Logto Cloud PAT 调用 `POST /api/tenants`: + +```bash +curl "$CLOUD_API_ENDPOINT/api/tenants" \ + -X POST \ + -H "Authorization: Bearer $LOGTO_CLOUD_PAT" \ + -H "Content-Type: application/json" \ + -d '{ + "name": "'"$TENANT_NAME"'", + "tag": "'"$TENANT_TAG"'", + "regionName": "'"$REGION_NAME"'" + }' +``` + +响应中包含已创建的租户和一个默认的 M2M 应用程序。该 M2M 应用程序在新租户中创建,并拥有该租户的 Management API 访问权限。 + +示例响应: + +```json +{ + "id": "new-tenant-id", + "name": "我的自动化租户", + "tag": "development", + "indicator": "https://new-tenant-id.logto.app", + "regionName": "EU", + "defaultApplication": { + "id": "default-m2m-app-id", + "secret": "default-m2m-app-secret" + } +} +``` + +保存你在下一步需要的值: + +```bash +export TENANT_ID="" +export TENANT_ENDPOINT="" +export DEFAULT_M2M_APP_ID="" +export DEFAULT_M2M_APP_SECRET="" +``` + +## 获取新租户的 Management API 访问令牌 \{#get-a-management-api-access-token-for-the-new-tenant} + +使用默认 M2M 应用程序凭据,从新租户请求访问令牌: + +```bash +curl "$TENANT_ENDPOINT/oidc/token" \ + -X POST \ + -u "$DEFAULT_M2M_APP_ID:$DEFAULT_M2M_APP_SECRET" \ + -H "Content-Type: application/x-www-form-urlencoded" \ + -d "grant_type=client_credentials" \ + -d "resource=$TENANT_ENDPOINT/api" \ + -d "scope=all" +``` + +示例响应: + +```json +{ + "access_token": "eyJ...", + "expires_in": 3600, + "token_type": "Bearer", + "scope": "all" +} +``` + +保存访问令牌: + +```bash +export MANAGEMENT_API_ACCESS_TOKEN="" +``` + +## 继续配置新租户 \{#continue-provisioning-the-new-tenant} + +使用 Management API 访问令牌调用新租户的 Management API。 + +例如,列出应用程序: + +```bash +curl "$TENANT_ENDPOINT/api/applications" \ + -H "Authorization: Bearer $MANAGEMENT_API_ACCESS_TOKEN" +``` + +或创建一个应用程序: + +```bash +curl "$TENANT_ENDPOINT/api/applications" \ + -X POST \ + -H "Authorization: Bearer $MANAGEMENT_API_ACCESS_TOKEN" \ + -H "Content-Type: application/json" \ + -d '{ + "name": "我的 Web 应用", + "type": "SPA", + "oidcClientMetadata": { + "redirectUris": ["https://example.com/callback"], + "postLogoutRedirectUris": ["https://example.com"] + } + }' +``` + +此时,你的自动化可以继续进行任何 Management API 操作,例如创建用户、应用程序、API 资源、角色、组织 (Organizations)、连接器 (Connectors) 或登录体验设置等。 + +## 完整自动化示例 \{#full-automation-example} + +以下 Node.js 示例会创建一个租户,使用返回的默认 M2M 凭据换取 Management API 访问令牌,并列出新租户中的应用程序: + +```js +const cloudApiEndpoint = 'https://cloud.logto.io'; +const logtoCloudPat = process.env.LOGTO_CLOUD_PAT; + +const createTenantResponse = await fetch(`${cloudApiEndpoint}/api/tenants`, { + method: 'POST', + headers: { + authorization: `Bearer ${logtoCloudPat}`, + 'content-type': 'application/json', + }, + body: JSON.stringify({ + name: '我的自动化租户', + tag: 'development', + regionName: 'EU', + }), +}); + +if (!createTenantResponse.ok) { + throw new Error(`Failed to create tenant: ${await createTenantResponse.text()}`); +} + +const tenant = await createTenantResponse.json(); +const tenantEndpoint = tenant.indicator; +const { id: appId, secret: appSecret } = tenant.defaultApplication; + +const tokenResponse = await fetch(`${tenantEndpoint}/oidc/token`, { + method: 'POST', + headers: { + authorization: `Basic ${Buffer.from(`${appId}:${appSecret}`).toString('base64')}`, + 'content-type': 'application/x-www-form-urlencoded', + }, + body: new URLSearchParams({ + grant_type: 'client_credentials', + resource: `${tenantEndpoint}/api`, + scope: 'all', + }), +}); + +if (!tokenResponse.ok) { + throw new Error(`Failed to get Management API token: ${await tokenResponse.text()}`); +} + +const { access_token: managementApiAccessToken } = await tokenResponse.json(); + +const applicationsResponse = await fetch(`${tenantEndpoint}/api/applications`, { + headers: { + authorization: `Bearer ${managementApiAccessToken}`, + }, +}); + +if (!applicationsResponse.ok) { + throw new Error(`Failed to list applications: ${await applicationsResponse.text()}`); +} + +const applications = await applicationsResponse.json(); + +console.log({ tenantId: tenant.id, applications }); +``` + +## 相关资源 \{#related-resources} + +- [个人访问令牌](/user-management/personal-access-token) +- [与 Management API 交互](/integrate-logto/interact-with-management-api) +- [机器对机器快速开始](/quick-starts/m2m) diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/integrate-logto/protected-app.mdx b/i18n/zh-TW/docusaurus-plugin-content-docs/current/integrate-logto/protected-app.mdx index 4f85b7407d4..b0fb9d730bc 100644 --- a/i18n/zh-TW/docusaurus-plugin-content-docs/current/integrate-logto/protected-app.mdx +++ b/i18n/zh-TW/docusaurus-plugin-content-docs/current/integrate-logto/protected-app.mdx @@ -1,78 +1,78 @@ --- -description: 輕鬆使用 Logto 的創新 Protected App,透過 Cloudflare 為你的網頁應用程式新增無需編碼的驗證 (Authentication)。支援 HTTP Basic Authentication 和 JWT 驗證。 +description: 使用 Logto 創新的 Protected App,輕鬆為你的網頁應用程式新增無程式碼驗證 (Authentication),由 Cloudflare 提供支援。支援 HTTP 基本驗證 (HTTP Basic Authentication) 與 JWT 驗證。 sidebar_label: Protected App sidebar_position: 2 --- # Protected App — 非 SDK 驗證 (Authentication) 整合 -Protected App 的設計旨在透過將 [驗證 (Authentication)](https://auth.wiki/authentication) 層與應用程式分離,消除 [SDK 整合](/quick-starts) 的複雜性。我們負責處理驗證,讓你專注於核心功能。使用者驗證後,Protected App 會從你的伺服器提供內容。 +Protected App 的設計目的是將 [驗證 (Authentication)](https://auth.wiki/authentication) 層從你的應用程式中分離,消除 [SDK 整合](/quick-starts) 的複雜性。我們負責驗證 (Authentication),讓你專注於核心功能。使用者驗證後,Protected App 會從你的伺服器提供內容。 -## Protected App 的運作方式 \{#how-protected-app-works} +## Protected App 如何運作 \{#how-protected-app-works} -由 Cloudflare 提供支持的 Protected App 在全球邊緣網路上運行,確保你的應用程式具有低延遲和高可用性。 +Protected App 由 Cloudflare 提供支援,運行於全球邊緣網路,確保你的應用程式具有低延遲與高可用性。 -Protected App 維護會話狀態和使用者資訊。如果使用者未經驗證,Protected App 會將他們重定向到登入頁面。驗證後,Protected App 會將使用者的請求包裹上驗證和使用者資訊,然後轉發到原始伺服器。 +Protected App 維護會話狀態與使用者資訊。如果使用者尚未驗證,Protected App 會將其導向登入頁面。驗證後,Protected App 會將使用者的請求包裝上驗證與使用者資訊,然後轉發至來源伺服器。 -此過程在以下流程圖中可視化: +此流程可用下方流程圖表示: ```mermaid graph LR - A("客戶端
(瀏覽器)") -->|請求| B(Logto
Protected App) - B --> Condition{{路由
匹配嗎?}} - Condition -->|是| Matched{{已驗證嗎?}} - Matched -->|是| C(原始伺服器) + A("用戶端
(瀏覽器)") -->|請求| B(Logto
Protected App) + B --> Condition{{路由
符合?}} + Condition -->|是| Matched{{已驗證?}} + Matched -->|是| C(來源伺服器) Matched -->|否| D(Logto 登入) Condition -->|否| C ``` -## 保護你的原始伺服器 \{#protect-your-origin-server} +## 保護你的來源伺服器 \{#protect-your-origin-server} -原始伺服器可以是 Logto 的 Protected App 不擁有的實體或虛擬設備,是你的應用程式內容所在的位置。類似於內容傳遞網路 (CDN) 伺服器,Protected App 管理驗證過程並從你的原始伺服器檢索內容。因此,如果使用者直接訪問你的原始伺服器,他們可以繞過驗證,應用程式將不再受保護。 +來源伺服器可以是 Logto Protected App 不擁有的實體或虛擬設備,是你的應用程式內容所在。類似於內容傳遞網路(CDN)伺服器,Protected App 管理驗證流程並從來源伺服器取得內容。因此,若使用者能直接存取來源伺服器,將可繞過驗證,應用程式將不再受保護。 -因此,保護原始連接非常重要,這可以防止攻擊者在未經驗證的情況下發現和訪問你的原始伺服器。有幾種方法可以做到這一點: +因此,保護來源連線非常重要,可防止攻擊者在未經驗證下發現並存取你的來源伺服器。常見做法如下: -1. HTTP Header 驗證 -2. JSON Web Tokens (JWT) 驗證 +1. HTTP 標頭驗證 (HTTP Header Validation) +2. JSON Web Token (JWT) 驗證 -### HTTP Header 驗證 \{#http-header-validation} +### HTTP 標頭驗證 (HTTP Header Validation) \{#http-header-validation} -可以使用 [HTTP Basic Authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication#basic_authentication_scheme) 來保護你的原始伺服器。 +你可以使用 [HTTP 基本驗證 (HTTP Basic Authentication)](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication#basic_authentication_scheme) 來保護你的來源伺服器。 -每個來自 Protected App 的請求都包含以下標頭: +每個來自 Protected App 的請求都會包含以下標頭: ``` Authorization: Basic base64(appId:appSecret) ``` -通過驗證此標頭,你可以確認請求來自 Protected App,並拒絕任何不包含此標頭的請求。 +只要驗證此標頭,即可確認請求來自 Protected App,並拒絕未包含此標頭的請求。 -如果你使用 Nginx 或 Apache,可以參考以下指南在原始伺服器上實施 HTTP Basic Authentication: +若你使用 Nginx 或 Apache,可參考以下指南在來源伺服器實作 HTTP 基本驗證: -1. Nginx:[配置 HTTP Basic Authentication](https://docs.nginx.com/nginx/admin-guide/security-controls/configuring-http-basic-authentication/) -2. Apache:[驗證 (Authentication) 和授權 (Authorization)](https://httpd.apache.org/docs/2.4/howto/auth.html) +1. Nginx:[設定 HTTP 基本驗證](https://docs.nginx.com/nginx/admin-guide/security-controls/configuring-http-basic-authentication/) +2. Apache:[驗證 (Authentication) 與授權 (Authorization)](https://httpd.apache.org/docs/2.4/howto/auth.html) -要在應用程式中檢查標頭,請參考 Cloudflare 提供的 [HTTP Basic Authentication 範例](https://developers.cloudflare.com/workers/examples/basic-auth/) 以了解如何使用 HTTP Basic 模式限制訪問。 +若需在應用程式內檢查標頭,可參考 Cloudflare 提供的 [HTTP Basic Authentication 範例](https://developers.cloudflare.com/workers/examples/basic-auth/),學習如何使用 HTTP Basic 機制限制存取。 -### JSON Web Tokens (JWT) 驗證 \{#json-web-tokens-jwt-validation} +### JSON Web Token (JWT) 驗證 \{#json-web-tokens-jwt-validation} -另一種保護原始伺服器的方法是使用 JSON Web Tokens (JWT)。 +另一種保護來源伺服器的方法是使用 JSON Web Token (JWT)。 -每個來自 Protected App 的已驗證請求都包含以下標頭: +每個經驗證的 Protected App 請求都會包含以下標頭: ``` Logto-ID-Token: ``` -JWT 被稱為 [ID 權杖 (ID Token)](https://auth.wiki/id-token),由 Logto 簽署並包含使用者資訊。通過驗證此 JWT,你可以確認請求來自 Protected App,並拒絕任何不包含此標頭的請求。 +此 JWT 稱為 [ID 權杖 (ID Token)](https://auth.wiki/id-token),由 Logto 簽署並包含使用者資訊。驗證此 JWT 可確認請求來自 Protected App,並拒絕未包含此標頭的請求。 -權杖被加密並簽署為 [JWS](https://auth.wiki/jws) 權杖。 +權杖以 [JWS](https://auth.wiki/jws) 權杖格式加密並簽署。 -驗證步驟: +驗證步驟如下: 1. [驗證 JWT](https://datatracker.ietf.org/doc/html/rfc7519#section-7.2) -2. [驗證 JWS 簽名](https://datatracker.ietf.org/doc/html/rfc7515#section-5.2) -3. 權杖的簽發者是 `https:///oidc`(由你的 Logto 驗證伺服器簽發) +2. [驗證 JWS 簽章](https://datatracker.ietf.org/doc/html/rfc7515#section-5.2) +3. 權杖的簽發者 (Issuer) 為 `https:///oidc`(由你的 Logto 驗證伺服器簽發) ```js const express = require('express'); @@ -95,14 +95,16 @@ const getKey = (header, callback) => { const verifyToken = (req, res, next) => { const token = req.headers['Logto-ID-Token']; - // 確保傳入的請求具有我們的權杖標頭 + // 確認請求包含 Logto-ID-Token 標頭 if (!token) { - return res.status(403).send({ status: false, message: '缺少必要的 Logto-ID-Token 標頭' }); + return res + .status(403) + .send({ status: false, message: 'missing required Logto-ID-Token header' }); } jwt.verify(token, getKey, { issuer: ISSUER }, (err, decoded) => { if (err) { - return res.status(403).send({ status: false, message: '無效的 ID 權杖' }); + return res.status(403).send({ status: false, message: 'invalid id token' }); } req.user = decoded; @@ -121,11 +123,11 @@ app.get('/', (req, res) => { app.listen(3000); ``` -## 獲取驗證狀態和使用者資訊 \{#get-authentication-state-and-user-information} +## 取得驗證狀態與使用者資訊 \{#get-authentication-state-and-user-information} -如果你需要獲取應用程式的驗證和使用者資訊,也可以使用 `Logto-ID-Token` 標頭。 +若你需要取得應用程式的驗證狀態與使用者資訊,也可以使用 `Logto-ID-Token` 標頭。 -如果你只想解碼權杖,可以使用以下代碼: +若你只需解碼權杖,可參考以下程式碼: ```js const express = require('express'); @@ -136,13 +138,13 @@ const decodeIdToken = (req, res, next) => { if (!token) { return res.status(403).send({ status: false, - message: '缺少必要的 Logto-ID-Token 標頭', + message: 'missing required Logto-ID-Token header', }); } const parts = token.split('.'); if (parts.length !== 3) { - throw new Error('無效的 ID 權杖'); + throw new Error('Invalid ID token'); } const payload = parts[1]; @@ -164,33 +166,52 @@ app.get('/', (req, res) => { app.listen(3000); ``` -## 獲取原始主機 \{#get-the-original-host} +## 自訂 ID 權杖宣告 (Claims) \{#customize-id-token-claims} -如果你需要獲取客戶端請求的原始主機,可以使用 `Logto-Host` 或 `x-forwarded-host` 標頭。 +預設情況下,`Logto-ID-Token` 標頭包含標準 OIDC 宣告(如 `sub`、`name`、`email`)。若要包含 [擴充宣告](/developers/custom-id-token#extended-claims)(如角色或組織資料),需同時設定下列兩項: + +1. **租戶開關**:於 Console > Custom JWT > ID 權杖 (ID token) 啟用該宣告。 +2. **Protected App 權限範圍 (Scopes)**:於 Protected App 設定中,在 **ID 權杖宣告 (ID token claims)** > **Additional scopes** 選擇對應範圍。 + +只有在 Custom JWT 啟用宣告且 Protected App 選擇對應範圍時,擴充宣告才會包含於轉發的 ID 權杖中。完整擴充範圍與宣告請參閱 [自訂 ID 權杖](/developers/custom-id-token)。 + +| 權限範圍 (Scope) | 宣告 (Claims) | +| ------------------------------------ | ------------------------------------ | +| `custom_data` | `custom_data` | +| `identities` | `identities`, `sso_identities` | +| `roles` | `roles` | +| `urn:logto:scope:organizations` | `organizations`, `organization_data` | +| `urn:logto:scope:organization_roles` | `organization_roles` | + +## 取得原始主機 \{#get-the-original-host} + +若你需要取得用戶端請求的原始主機,可使用 `Logto-Host` 或 `x-forwarded-host` 標頭。 ## 自訂驗證規則 \{#customize-authentication-rules} -預設情況下,Protected App 會保護所有路由。如果你需要自訂驗證規則,可以在 Console 中設置「自訂驗證規則」欄位。 +預設情況下,Protected App 會保護所有路由。若需自訂驗證規則,可於 Console 設定「自訂驗證規則」欄位。 -它支援正則表達式,以下是兩個案例: +支援正則表達式,以下為兩種情境範例: -1. 僅保護路由 `/admin` 和 `/privacy`:`^/(admin|privacy)/.*` -2. 排除 JPG 圖片的驗證:`^(?!.*\.jpg$).*$` +1. 僅保護 `/admin` 與 `/privacy` 路由:`^/(admin|privacy)/.*` +2. 排除 JPG 圖片不進行驗證:`^(?!.*\.jpg$).*$` ## 本地開發 \{#local-development} -Protected App 設計用於與你的原始伺服器一起工作。然而,如果你的原始伺服器無法公開訪問,可以使用 [ngrok](https://ngrok.com/) 或 [Cloudflare Tunnels](https://developers.cloudflare.com/pages/how-to/preview-with-cloudflare-tunnel/) 等工具將本地伺服器暴露到互聯網。 +Protected App 設計用於搭配你的來源伺服器運作。若來源伺服器未公開存取,可使用 [ngrok](https://ngrok.com/) 或 [Cloudflare Tunnels](https://developers.cloudflare.com/pages/how-to/preview-with-cloudflare-tunnel/) 等工具將本地伺服器暴露至網際網路。 -## 過渡到 SDK 整合 \{#transition-to-sdk-integration} +## 過渡至 SDK 整合 \{#transition-to-sdk-integration} -Protected App 設計用於簡化驗證過程。然而,如果你決定過渡到 SDK 整合以獲得更好的控制和自訂,可以在 Logto 中 [創建一個新應用程式](/integrate-logto/integrate-logto-into-your-application) 並配置 [SDK 整合](/quick-starts)。為了順利過渡,你可以重用 Protected App 的應用程式配置。Protected App 實際上是 Logto 中的「傳統 Web 應用程式」,你可以在應用程式設置中找到「[AppId](/integrate-logto/application-data-structure#application-id)」和「[AppSecret](/integrate-logto/application-data-structure#application-secret)」。過渡完成後,可以從應用程式中移除 Protected App。 +Protected App 旨在簡化驗證流程。若你希望獲得更高控制與自訂性,決定轉換為 SDK 整合,可在 Logto [建立新應用程式](/integrate-logto/integrate-logto-into-your-application) 並設定 [SDK 整合](/quick-starts)。為順利過渡,你可重複使用 Protected App 的應用程式設定。Protected App 在 Logto 中實際上是一種「傳統網頁應用程式 (Traditional Web App)」,你可於應用程式設定中找到「[AppId](/integrate-logto/application-data-structure#application-id)」與「[AppSecret](/integrate-logto/application-data-structure#application-secret)」。過渡完成後,即可將 Protected App 從應用程式中移除。 ## 相關資源 \{#related-resources} - Protected App:點擊即可構建應用程式的驗證 (Authentication)。無需編碼。 + Protected App:幾個點擊即可建立應用程式驗證 (Authentication),無需寫程式碼。 -Protected App 背後的動機 +Protected App 的設計動機 -構建驗證系統的最快方法 + + 建立驗證 (Authentication) 系統的最快方式 + diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/logto-cloud/README.mdx b/i18n/zh-TW/docusaurus-plugin-content-docs/current/logto-cloud/README.mdx index 647ec36dd07..d30b379ed96 100644 --- a/i18n/zh-TW/docusaurus-plugin-content-docs/current/logto-cloud/README.mdx +++ b/i18n/zh-TW/docusaurus-plugin-content-docs/current/logto-cloud/README.mdx @@ -3,6 +3,7 @@ import Developer from '@site/src/assets/developer.svg'; import TenantMemberManagement from '@site/src/assets/gear.svg'; import PricingAndBilling from '@site/src/assets/key.svg'; import McpIcon from '@site/src/assets/mcp.svg'; +import TenantAutomation from '@site/src/assets/robot.svg'; import CustomDomains from '@site/src/assets/search.svg'; import SystemLimit from '@site/src/assets/security.svg'; @@ -10,7 +11,7 @@ import SystemLimit from '@site/src/assets/security.svg'; [Logto Cloud](https://cloud.logto.io) 提供一系列管理與營運服務,協助你順利且輕鬆地管理身分 (Identities) 與資源 (Resources)。由 Logto 託管,包含 [多區域支援](/logto-cloud/tenant-settings#tenant-region)、租戶管理、[計費與價格](/logto-cloud/billing-and-pricing)、[成員管理](/logto-cloud/tenant-member-management) 以及主控台角色型存取控制 (RBAC, Role-based Access Control) 等功能。 -若你對雲端服務有任何疑問或需要額外支援,歡迎聯繫我們。 +若你對雲端服務有任何疑問或需要額外協助,請隨時聯繫我們。 ## 雲端服務功能 \{#features-for-cloud-service} @@ -20,7 +21,7 @@ import SystemLimit from '@site/src/assets/security.svg'; type: 'link', label: '租戶設定 (Tenant settings)', href: '/logto-cloud/tenant-settings', - description: '更新或變更租戶名稱、檢查區域、刪除或退出租戶。', + description: '更新或變更租戶名稱、檢查區域,並刪除或退出租戶。', customProps: { icon: , }, @@ -56,7 +57,7 @@ import SystemLimit from '@site/src/assets/security.svg'; type: 'link', label: '計費與價格 (Billing and pricing)', href: '/logto-cloud/billing-and-pricing', - description: '輕鬆瞭解帳單並自信管理你的訂閱。', + description: '輕鬆瞭解你的帳單,並自信地管理訂閱。', customProps: { icon: , }, @@ -70,6 +71,15 @@ import SystemLimit from '@site/src/assets/security.svg'; icon: , }, }, + { + type: 'link', + label: '自動化租戶管理 (Automate tenant management)', + href: '/logto-cloud/automate-tenant-creation', + description: '透過 Logto Cloud API 與 Management API 以程式化方式建立與管理租戶。', + customProps: { + icon: , + }, + }, { type: 'link', label: 'Logto MCP Server', diff --git a/i18n/zh-TW/docusaurus-plugin-content-docs/current/logto-cloud/automate-tenant-creation.mdx b/i18n/zh-TW/docusaurus-plugin-content-docs/current/logto-cloud/automate-tenant-creation.mdx new file mode 100644 index 00000000000..a7fdd23b2c8 --- /dev/null +++ b/i18n/zh-TW/docusaurus-plugin-content-docs/current/logto-cloud/automate-tenant-creation.mdx @@ -0,0 +1,242 @@ +--- +id: automate-tenant-creation +title: 自動化租戶管理 +sidebar_position: 8 +--- + +# 自動化租戶管理 + +你可以透過程式化方式管理 Logto Cloud 租戶,包括建立租戶並持續進行設定,無需切換至 Console。 + +當你需要從自己的導入流程、內部平台、AI agent 或整合自動化中佈建租戶時,這會非常有用。 + +自動化流程如下: + +1. 使用 **Logto Cloud Personal Access Token (PAT)** 呼叫 Logto Cloud API。 +2. 透過 `POST /api/tenants` 建立租戶。 +3. 從建立回應中讀取預設機器對機器 (M2M, Machine-to-machine) 應用程式憑證。 +4. 使用預設 M2M 應用程式取得新租戶的 Management API 存取權杖 (Access token)。 +5. 呼叫新租戶的 Management API,持續佈建應用程式、使用者、角色 (Roles)、資源 (Resources)、組織 (Organizations) 及其他設定。 + +## 開始前的準備 \{#before-you-start} + +請準備以下變數: + +| Variable | Description | +| -------------------- | ------------------------------------------------------------------------- | +| `CLOUD_API_ENDPOINT` | Logto Cloud API 端點。對於 Logto Cloud,請使用 `https://cloud.logto.io`。 | +| `LOGTO_CLOUD_PAT` | 你的 Logto Cloud 帳號的 PAT。 | +| `TENANT_NAME` | 要建立的租戶顯示名稱。 | +| `TENANT_TAG` | 租戶類型。請使用 `development` 或 `production`。 | +| `REGION_NAME` | 租戶的區域識別碼。 | + +將它們設為環境變數: + +```bash +export CLOUD_API_ENDPOINT="https://cloud.logto.io" +export LOGTO_CLOUD_PAT="" +export TENANT_NAME="My automated tenant" +export TENANT_TAG="development" +export REGION_NAME="" +``` + +## 取得可用區域 \{#get-available-regions} + +在建立租戶前,先查詢你的 Logto Cloud 帳號可用的區域: + +```bash +curl "$CLOUD_API_ENDPOINT/api/me/regions" \ + -H "Authorization: Bearer $LOGTO_CLOUD_PAT" +``` + +回應內容包含可用區域。建立租戶時,請將 `name` 欄位作為 `REGION_NAME` 使用。 + +範例回應: + +```json +{ + "regions": [ + { + "name": "EU", + "displayName": "Europe" + }, + { + "name": "US", + "displayName": "United States" + } + ] +} +``` + +## 建立租戶 \{#create-a-tenant} + +使用 Logto Cloud PAT 呼叫 `POST /api/tenants`: + +```bash +curl "$CLOUD_API_ENDPOINT/api/tenants" \ + -X POST \ + -H "Authorization: Bearer $LOGTO_CLOUD_PAT" \ + -H "Content-Type: application/json" \ + -d '{ + "name": "'"$TENANT_NAME"'", + "tag": "'"$TENANT_TAG"'", + "regionName": "'"$REGION_NAME"'" + }' +``` + +回應內容包含已建立的租戶及預設 M2M 應用程式。該 M2M 應用程式會建立於新租戶中,並擁有該租戶的 Management API 存取權。 + +範例回應: + +```json +{ + "id": "new-tenant-id", + "name": "My automated tenant", + "tag": "development", + "indicator": "https://new-tenant-id.logto.app", + "regionName": "EU", + "defaultApplication": { + "id": "default-m2m-app-id", + "secret": "default-m2m-app-secret" + } +} +``` + +將你需要的值儲存以供下一步使用: + +```bash +export TENANT_ID="" +export TENANT_ENDPOINT="" +export DEFAULT_M2M_APP_ID="" +export DEFAULT_M2M_APP_SECRET="" +``` + +## 取得新租戶的 Management API 存取權杖 (Access token) \{#get-a-management-api-access-token-for-the-new-tenant} + +使用預設 M2M 應用程式憑證,向新租戶請求存取權杖: + +```bash +curl "$TENANT_ENDPOINT/oidc/token" \ + -X POST \ + -u "$DEFAULT_M2M_APP_ID:$DEFAULT_M2M_APP_SECRET" \ + -H "Content-Type: application/x-www-form-urlencoded" \ + -d "grant_type=client_credentials" \ + -d "resource=$TENANT_ENDPOINT/api" \ + -d "scope=all" +``` + +範例回應: + +```json +{ + "access_token": "eyJ...", + "expires_in": 3600, + "token_type": "Bearer", + "scope": "all" +} +``` + +儲存存取權杖: + +```bash +export MANAGEMENT_API_ACCESS_TOKEN="" +``` + +## 持續佈建新租戶 \{#continue-provisioning-the-new-tenant} + +使用 Management API 存取權杖呼叫新租戶的 Management API。 + +例如,列出應用程式: + +```bash +curl "$TENANT_ENDPOINT/api/applications" \ + -H "Authorization: Bearer $MANAGEMENT_API_ACCESS_TOKEN" +``` + +或建立一個應用程式: + +```bash +curl "$TENANT_ENDPOINT/api/applications" \ + -X POST \ + -H "Authorization: Bearer $MANAGEMENT_API_ACCESS_TOKEN" \ + -H "Content-Type: application/json" \ + -d '{ + "name": "My web app", + "type": "SPA", + "oidcClientMetadata": { + "redirectUris": ["https://example.com/callback"], + "postLogoutRedirectUris": ["https://example.com"] + } + }' +``` + +此時,你的自動化流程可以繼續進行任何 Management API 操作,例如建立使用者、應用程式、API 資源 (API resources)、角色 (Roles)、組織 (Organizations)、連接器 (Connectors) 或登入體驗 (Sign-in experience) 設定。 + +## 完整自動化範例 \{#full-automation-example} + +以下 Node.js 範例會建立租戶、用回傳的預設 M2M 憑證換取 Management API 存取權杖,並列出新租戶中的應用程式: + +```js +const cloudApiEndpoint = 'https://cloud.logto.io'; +const logtoCloudPat = process.env.LOGTO_CLOUD_PAT; + +const createTenantResponse = await fetch(`${cloudApiEndpoint}/api/tenants`, { + method: 'POST', + headers: { + authorization: `Bearer ${logtoCloudPat}`, + 'content-type': 'application/json', + }, + body: JSON.stringify({ + name: 'My automated tenant', + tag: 'development', + regionName: 'EU', + }), +}); + +if (!createTenantResponse.ok) { + throw new Error(`Failed to create tenant: ${await createTenantResponse.text()}`); +} + +const tenant = await createTenantResponse.json(); +const tenantEndpoint = tenant.indicator; +const { id: appId, secret: appSecret } = tenant.defaultApplication; + +const tokenResponse = await fetch(`${tenantEndpoint}/oidc/token`, { + method: 'POST', + headers: { + authorization: `Basic ${Buffer.from(`${appId}:${appSecret}`).toString('base64')}`, + 'content-type': 'application/x-www-form-urlencoded', + }, + body: new URLSearchParams({ + grant_type: 'client_credentials', + resource: `${tenantEndpoint}/api`, + scope: 'all', + }), +}); + +if (!tokenResponse.ok) { + throw new Error(`Failed to get Management API token: ${await tokenResponse.text()}`); +} + +const { access_token: managementApiAccessToken } = await tokenResponse.json(); + +const applicationsResponse = await fetch(`${tenantEndpoint}/api/applications`, { + headers: { + authorization: `Bearer ${managementApiAccessToken}`, + }, +}); + +if (!applicationsResponse.ok) { + throw new Error(`Failed to list applications: ${await applicationsResponse.text()}`); +} + +const applications = await applicationsResponse.json(); + +console.log({ tenantId: tenant.id, applications }); +``` + +## 相關資源 \{#related-resources} + +- [Personal access token](/user-management/personal-access-token) +- [與 Management API 互動](/integrate-logto/interact-with-management-api) +- [機器對機器快速入門](/quick-starts/m2m)