diff --git a/main/docs.json b/main/docs.json index 550304672..6ccedc18c 100644 --- a/main/docs.json +++ b/main/docs.json @@ -8,7 +8,7 @@ }, "seo": { "metatags": { - "canonical": "https://auth0.com/docs" + "canonical": "https://auth0.com" } }, "banner": { diff --git a/main/docs/authenticate/database-connections/password-change.mdx b/main/docs/authenticate/database-connections/password-change.mdx index 0ac90cb08..f1e66b157 100644 --- a/main/docs/authenticate/database-connections/password-change.mdx +++ b/main/docs/authenticate/database-connections/password-change.mdx @@ -12,6 +12,8 @@ title: Change Users' Passwords --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + Key Concepts @@ -59,16 +61,22 @@ Go to [Auth0 Dashboard > Applications > Applications](https://manage.auth0.com/# If your connection is a custom database, check to see if the user exists in the database before you invoke the Authentication API for `changePassword`. -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/dbconnections/change_password' \ --header 'content-type: application/json' \ - --data '{"client_id": "{yourClientId}","email": "","connection": "Username-Password-Authentication"}'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/dbconnections/change_password"); + --data '{"client_id": "{yourClientId}","email": "","connection": "Username-Password-Authentication"}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/dbconnections/change_password"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\"client_id\": \"{yourClientId}\",\"email\": \"\",\"connection\": \"Username-Password-Authentication\"}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{"client_id": "{yourClientId}","email": "","connection": "Username-Password-Authentication"}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -81,7 +89,7 @@ func main() { url := "https://{yourDomain}/dbconnections/change_password" - payload := strings.NewReader("{\"client_id\": \"{yourClientId}\",\"email\": \"\",\"connection\": \"Username-Password-Authentication\"}") + payload := strings.NewReader("{"client_id": "{yourClientId}","email": "","connection": "Username-Password-Authentication"}") req, _ := http.NewRequest("POST", url, payload) @@ -95,12 +103,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/dbconnections/change_password") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/dbconnections/change_password") .header("content-type", "application/json") - .body("{\"client_id\": \"{yourClientId}\",\"email\": \"\",\"connection\": \"Username-Password-Authentication\"}") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{"client_id": "{yourClientId}","email": "","connection": "Username-Password-Authentication"}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -117,8 +129,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json" }; NSDictionary *parameters = @{ @"client_id": @"{yourClientId}", @@ -144,8 +158,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/dbconnections/change_password", @@ -155,7 +171,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{\"client_id\": \"{yourClientId}\",\"email\": \"\",\"connection\": \"Username-Password-Authentication\"}", + CURLOPT_POSTFIELDS => "{"client_id": "{yourClientId}","email": "","connection": "Username-Password-Authentication"}", CURLOPT_HTTPHEADER => [ "content-type: application/json" ], @@ -170,12 +186,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"client_id\": \"{yourClientId}\",\"email\": \"\",\"connection\": \"Username-Password-Authentication\"}" +payload = "{"client_id": "{yourClientId}","email": "","connection": "Username-Password-Authentication"}" headers = { 'content-type': "application/json" } @@ -184,8 +202,10 @@ conn.request("POST", "/{yourDomain}/dbconnections/change_password", payload, hea res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -197,11 +217,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["content-type"] = 'application/json' -request.body = "{\"client_id\": \"{yourClientId}\",\"email\": \"\",\"connection\": \"Username-Password-Authentication\"}" +request.body = "{"client_id": "{yourClientId}","email": "","connection": "Username-Password-Authentication"}" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/json"] let parameters = [ @@ -229,20 +251,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ### Password reset email @@ -291,18 +302,24 @@ If you use Management API to set or update a user's password via the [Update a U -export const codeExample11 = `curl --request PATCH \ + +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/users/%7BuserId%7D' \ --header 'authorization: Bearer {yourMgmtApiAccessToken}' \ --header 'content-type: application/json' \ - --data '{"password": "newPassword","connection": "connectionName"}'`; -export const codeExample12 = `var client = new RestClient("https://{yourDomain}/api/v2/users/%7BuserId%7D"); + --data '{"password": "newPassword","connection": "connectionName"}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users/%7BuserId%7D"); var request = new RestRequest(Method.PATCH); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer {yourMgmtApiAccessToken}"); -request.AddParameter("application/json", "{\"password\": \"newPassword\",\"connection\": \"connectionName\"}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample13 = `package main +request.AddParameter("application/json", "{"password": "newPassword","connection": "connectionName"}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -315,7 +332,7 @@ func main() { url := "https://{yourDomain}/api/v2/users/%7BuserId%7D" - payload := strings.NewReader("{\"password\": \"newPassword\",\"connection\": \"connectionName\"}") + payload := strings.NewReader("{"password": "newPassword","connection": "connectionName"}") req, _ := http.NewRequest("PATCH", url, payload) @@ -330,13 +347,17 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample14 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/users/%7BuserId%7D") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/users/%7BuserId%7D") .header("content-type", "application/json") .header("authorization", "Bearer {yourMgmtApiAccessToken}") - .body("{\"password\": \"newPassword\",\"connection\": \"connectionName\"}") - .asString();`; -export const codeExample15 = `var axios = require("axios").default; + .body("{"password": "newPassword","connection": "connectionName"}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -352,8 +373,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample16 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer {yourMgmtApiAccessToken}" }; @@ -379,8 +402,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users/%7BuserId%7D", @@ -390,7 +415,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{\"password\": \"newPassword\",\"connection\": \"connectionName\"}", + CURLOPT_POSTFIELDS => "{"password": "newPassword","connection": "connectionName"}", CURLOPT_HTTPHEADER => [ "authorization: Bearer {yourMgmtApiAccessToken}", "content-type: application/json" @@ -406,12 +431,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"password\": \"newPassword\",\"connection\": \"connectionName\"}" +payload = "{"password": "newPassword","connection": "connectionName"}" headers = { 'content-type': "application/json", @@ -423,8 +450,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/users/%7BuserId%7D", payload, header res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -437,11 +466,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Patch.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer {yourMgmtApiAccessToken}' -request.body = "{\"password\": \"newPassword\",\"connection\": \"connectionName\"}" +request.body = "{"password": "newPassword","connection": "connectionName"}" response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -471,20 +502,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ### Manually set users' passwords using the Auth0 Dashboard diff --git a/main/docs/authenticate/identity-providers/calling-an-external-idp-api.mdx b/main/docs/authenticate/identity-providers/calling-an-external-idp-api.mdx index a3854b59a..fbdae9d9f 100644 --- a/main/docs/authenticate/identity-providers/calling-an-external-idp-api.mdx +++ b/main/docs/authenticate/identity-providers/calling-an-external-idp-api.mdx @@ -10,6 +10,8 @@ title: Call an Identity Provider API --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + If you have [Token Vault](/docs/secure/tokens/token-vault) enabled for your connection, access and refresh tokens will no longer be stored in the user’s `identities` array. Instead, they will be stored in a secure tokenset within the Token Vault. To enable Token Vault, read [Configure Token Vault](/docs/secure/tokens/token-vault/configure-token-vault). @@ -110,14 +112,20 @@ These tokens **cannot be revoked**. To minimize risk, we recommend issuing short To get a user's profile, call the [Get a User endpoint](https://auth0.com/docs/api/management/v2#!/Users/get_users_by_id) of the Management API using the Access Token you extracted in the previous section: -export const codeExample1 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/users/%7BuserId%7D' \ - --header 'authorization: Bearer {yourAccessToken}'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/users/%7BuserId%7D"); + --header 'authorization: Bearer {yourAccessToken}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users/%7BuserId%7D"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer {yourAccessToken}"); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -141,11 +149,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/users/%7BuserId%7D") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/users/%7BuserId%7D") .header("authorization", "Bearer {yourAccessToken}") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -157,8 +169,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer {yourAccessToken}" }; @@ -178,8 +192,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users/%7BuserId%7D", @@ -203,8 +219,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -215,8 +233,10 @@ conn.request("GET", "/{yourDomain}/api/v2/users/%7BuserId%7D", headers=headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -230,8 +250,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer {yourAccessToken}' response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer {yourAccessToken}"] @@ -251,20 +273,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + Replace these values: @@ -323,11 +334,6 @@ In this sample response, we see that our user has only one identity: `google-oau } ``` - - - - - You are now ready to call the IdP's API. Please refer to the IdP's documentation for specifics on how to do so. diff --git a/main/docs/authenticate/identity-providers/enterprise-identity-providers/oidc.mdx b/main/docs/authenticate/identity-providers/enterprise-identity-providers/oidc.mdx index 6379b5d70..0c7f7648f 100644 --- a/main/docs/authenticate/identity-providers/enterprise-identity-providers/oidc.mdx +++ b/main/docs/authenticate/identity-providers/enterprise-identity-providers/oidc.mdx @@ -12,6 +12,8 @@ title: Connect to OpenID Connect Identity Provider --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + ## Prerequisites * [Register your Application with Auth0](/docs/get-started/auth0-overview/create-applications). @@ -212,16 +214,22 @@ These examples will show you the variety of ways you can create the connection u #### Use front-channel with discovery endpoint -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/api/v2/connections' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ - --data '{ "strategy": "oidc", "name": "CONNECTION_NAME", "options": { "type": "front_channel", "discovery_url": "https://IDP_DOMAIN/.well-known/openid-configuration", "client_id" : "IDP_CLIENT_ID", "scopes": "openid profile" } }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/connections"); + --data '{ "strategy": "oidc", "name": "CONNECTION_NAME", "options": { "type": "front_channel", "discovery_url": "https://IDP_DOMAIN/.well-known/openid-configuration", "client_id" : "IDP_CLIENT_ID", "scopes": "openid profile" } }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/connections"); var request = new RestRequest(Method.POST); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); -request.AddParameter("undefined", "{ \"strategy\": \"oidc\", \"name\": \"CONNECTION_NAME\", \"options\": { \"type\": \"front_channel\", \"discovery_url\": \"https://IDP_DOMAIN/.well-known/openid-configuration\", \"client_id\" : \"IDP_CLIENT_ID\", \"scopes\": \"openid profile\" } }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("undefined", "{ "strategy": "oidc", "name": "CONNECTION_NAME", "options": { "type": "front_channel", "discovery_url": "https://IDP_DOMAIN/.well-known/openid-configuration", "client_id" : "IDP_CLIENT_ID", "scopes": "openid profile" } }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -234,7 +242,7 @@ func main() { url := "https://{yourDomain}/api/v2/connections" - payload := strings.NewReader("{ \"strategy\": \"oidc\", \"name\": \"CONNECTION_NAME\", \"options\": { \"type\": \"front_channel\", \"discovery_url\": \"https://IDP_DOMAIN/.well-known/openid-configuration\", \"client_id\" : \"IDP_CLIENT_ID\", \"scopes\": \"openid profile\" } }") + payload := strings.NewReader("{ "strategy": "oidc", "name": "CONNECTION_NAME", "options": { "type": "front_channel", "discovery_url": "https://IDP_DOMAIN/.well-known/openid-configuration", "client_id" : "IDP_CLIENT_ID", "scopes": "openid profile" } }") req, _ := http.NewRequest("POST", url, payload) @@ -248,12 +256,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/connections") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/connections") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") - .body("{ \"strategy\": \"oidc\", \"name\": \"CONNECTION_NAME\", \"options\": { \"type\": \"front_channel\", \"discovery_url\": \"https://IDP_DOMAIN/.well-known/openid-configuration\", \"client_id\" : \"IDP_CLIENT_ID\", \"scopes\": \"openid profile\" } }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "strategy": "oidc", "name": "CONNECTION_NAME", "options": { "type": "front_channel", "discovery_url": "https://IDP_DOMAIN/.well-known/openid-configuration", "client_id" : "IDP_CLIENT_ID", "scopes": "openid profile" } }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -275,8 +287,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN" }; NSDictionary *parameters = @{ @"strategy": @"oidc", @@ -302,8 +316,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/connections", @@ -313,7 +329,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{ \"strategy\": \"oidc\", \"name\": \"CONNECTION_NAME\", \"options\": { \"type\": \"front_channel\", \"discovery_url\": \"https://IDP_DOMAIN/.well-known/openid-configuration\", \"client_id\" : \"IDP_CLIENT_ID\", \"scopes\": \"openid profile\" } }", + CURLOPT_POSTFIELDS => "{ "strategy": "oidc", "name": "CONNECTION_NAME", "options": { "type": "front_channel", "discovery_url": "https://IDP_DOMAIN/.well-known/openid-configuration", "client_id" : "IDP_CLIENT_ID", "scopes": "openid profile" } }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN" ], @@ -328,12 +344,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"strategy\": \"oidc\", \"name\": \"CONNECTION_NAME\", \"options\": { \"type\": \"front_channel\", \"discovery_url\": \"https://IDP_DOMAIN/.well-known/openid-configuration\", \"client_id\" : \"IDP_CLIENT_ID\", \"scopes\": \"openid profile\" } }" +payload = "{ "strategy": "oidc", "name": "CONNECTION_NAME", "options": { "type": "front_channel", "discovery_url": "https://IDP_DOMAIN/.well-known/openid-configuration", "client_id" : "IDP_CLIENT_ID", "scopes": "openid profile" } }" headers = { 'authorization': "Bearer MGMT_API_ACCESS_TOKEN" } @@ -342,8 +360,10 @@ conn.request("POST", "/{yourDomain}/api/v2/connections", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -355,11 +375,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' -request.body = "{ \"strategy\": \"oidc\", \"name\": \"CONNECTION_NAME\", \"options\": { \"type\": \"front_channel\", \"discovery_url\": \"https://IDP_DOMAIN/.well-known/openid-configuration\", \"client_id\" : \"IDP_CLIENT_ID\", \"scopes\": \"openid profile\" } }" +request.body = "{ "strategy": "oidc", "name": "CONNECTION_NAME", "options": { "type": "front_channel", "discovery_url": "https://IDP_DOMAIN/.well-known/openid-configuration", "client_id" : "IDP_CLIENT_ID", "scopes": "openid profile" } }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer MGMT_API_ACCESS_TOKEN"] let parameters = [ @@ -392,33 +414,28 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + #### Use back-channel with discovery endpoint -export const codeExample11 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/api/v2/connections' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ - --data '{ "strategy": "oidc", "name": "CONNECTION_NAME", "options": { "type": "back_channel", "discovery_url": "https://IDP_DOMAIN/.well-known/openid-configuration", "client_id" : "IDP_CLIENT_ID", "client_secret" : "IDP_CLIENT_SECRET", "scopes": "openid profile" } }'`; -export const codeExample12 = `var client = new RestClient("https://{yourDomain}/api/v2/connections"); + --data '{ "strategy": "oidc", "name": "CONNECTION_NAME", "options": { "type": "back_channel", "discovery_url": "https://IDP_DOMAIN/.well-known/openid-configuration", "client_id" : "IDP_CLIENT_ID", "client_secret" : "IDP_CLIENT_SECRET", "scopes": "openid profile" } }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/connections"); var request = new RestRequest(Method.POST); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); -request.AddParameter("undefined", "{ \"strategy\": \"oidc\", \"name\": \"CONNECTION_NAME\", \"options\": { \"type\": \"back_channel\", \"discovery_url\": \"https://IDP_DOMAIN/.well-known/openid-configuration\", \"client_id\" : \"IDP_CLIENT_ID\", \"client_secret\" : \"IDP_CLIENT_SECRET\", \"scopes\": \"openid profile\" } }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample13 = `package main +request.AddParameter("undefined", "{ "strategy": "oidc", "name": "CONNECTION_NAME", "options": { "type": "back_channel", "discovery_url": "https://IDP_DOMAIN/.well-known/openid-configuration", "client_id" : "IDP_CLIENT_ID", "client_secret" : "IDP_CLIENT_SECRET", "scopes": "openid profile" } }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -431,7 +448,7 @@ func main() { url := "https://{yourDomain}/api/v2/connections" - payload := strings.NewReader("{ \"strategy\": \"oidc\", \"name\": \"CONNECTION_NAME\", \"options\": { \"type\": \"back_channel\", \"discovery_url\": \"https://IDP_DOMAIN/.well-known/openid-configuration\", \"client_id\" : \"IDP_CLIENT_ID\", \"client_secret\" : \"IDP_CLIENT_SECRET\", \"scopes\": \"openid profile\" } }") + payload := strings.NewReader("{ "strategy": "oidc", "name": "CONNECTION_NAME", "options": { "type": "back_channel", "discovery_url": "https://IDP_DOMAIN/.well-known/openid-configuration", "client_id" : "IDP_CLIENT_ID", "client_secret" : "IDP_CLIENT_SECRET", "scopes": "openid profile" } }") req, _ := http.NewRequest("POST", url, payload) @@ -445,12 +462,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample14 = `HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/connections") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/connections") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") - .body("{ \"strategy\": \"oidc\", \"name\": \"CONNECTION_NAME\", \"options\": { \"type\": \"back_channel\", \"discovery_url\": \"https://IDP_DOMAIN/.well-known/openid-configuration\", \"client_id\" : \"IDP_CLIENT_ID\", \"client_secret\" : \"IDP_CLIENT_SECRET\", \"scopes\": \"openid profile\" } }") - .asString();`; -export const codeExample15 = `var axios = require("axios").default; + .body("{ "strategy": "oidc", "name": "CONNECTION_NAME", "options": { "type": "back_channel", "discovery_url": "https://IDP_DOMAIN/.well-known/openid-configuration", "client_id" : "IDP_CLIENT_ID", "client_secret" : "IDP_CLIENT_SECRET", "scopes": "openid profile" } }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -473,8 +494,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample16 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN" }; NSDictionary *parameters = @{ @"strategy": @"oidc", @@ -500,8 +523,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/connections", @@ -511,7 +536,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{ \"strategy\": \"oidc\", \"name\": \"CONNECTION_NAME\", \"options\": { \"type\": \"back_channel\", \"discovery_url\": \"https://IDP_DOMAIN/.well-known/openid-configuration\", \"client_id\" : \"IDP_CLIENT_ID\", \"client_secret\" : \"IDP_CLIENT_SECRET\", \"scopes\": \"openid profile\" } }", + CURLOPT_POSTFIELDS => "{ "strategy": "oidc", "name": "CONNECTION_NAME", "options": { "type": "back_channel", "discovery_url": "https://IDP_DOMAIN/.well-known/openid-configuration", "client_id" : "IDP_CLIENT_ID", "client_secret" : "IDP_CLIENT_SECRET", "scopes": "openid profile" } }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN" ], @@ -526,12 +551,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"strategy\": \"oidc\", \"name\": \"CONNECTION_NAME\", \"options\": { \"type\": \"back_channel\", \"discovery_url\": \"https://IDP_DOMAIN/.well-known/openid-configuration\", \"client_id\" : \"IDP_CLIENT_ID\", \"client_secret\" : \"IDP_CLIENT_SECRET\", \"scopes\": \"openid profile\" } }" +payload = "{ "strategy": "oidc", "name": "CONNECTION_NAME", "options": { "type": "back_channel", "discovery_url": "https://IDP_DOMAIN/.well-known/openid-configuration", "client_id" : "IDP_CLIENT_ID", "client_secret" : "IDP_CLIENT_SECRET", "scopes": "openid profile" } }" headers = { 'authorization': "Bearer MGMT_API_ACCESS_TOKEN" } @@ -540,8 +567,10 @@ conn.request("POST", "/{yourDomain}/api/v2/connections", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -553,11 +582,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' -request.body = "{ \"strategy\": \"oidc\", \"name\": \"CONNECTION_NAME\", \"options\": { \"type\": \"back_channel\", \"discovery_url\": \"https://IDP_DOMAIN/.well-known/openid-configuration\", \"client_id\" : \"IDP_CLIENT_ID\", \"client_secret\" : \"IDP_CLIENT_SECRET\", \"scopes\": \"openid profile\" } }" +request.body = "{ "strategy": "oidc", "name": "CONNECTION_NAME", "options": { "type": "back_channel", "discovery_url": "https://IDP_DOMAIN/.well-known/openid-configuration", "client_id" : "IDP_CLIENT_ID", "client_secret" : "IDP_CLIENT_SECRET", "scopes": "openid profile" } }" response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer MGMT_API_ACCESS_TOKEN"] let parameters = [ @@ -591,33 +622,28 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + #### Use back-channel specifying issuer settings -export const codeExample21 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/api/v2/connections' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ - --data '{ "strategy": "oidc", "name": "CONNECTION_NAME", "options": { "type": "back_channel", "issuer": "https://IDP_DOMAIN", "authorization_endpoint": "https://IDP_DOMAIN/authorize", "client_secret" : "IDP_CLIENT_SECRET", "client_id" : "IDP_CLIENT_ID", "scopes": "openid profile" } }'`; -export const codeExample22 = `var client = new RestClient("https://{yourDomain}/api/v2/connections"); + --data '{ "strategy": "oidc", "name": "CONNECTION_NAME", "options": { "type": "back_channel", "issuer": "https://IDP_DOMAIN", "authorization_endpoint": "https://IDP_DOMAIN/authorize", "client_secret" : "IDP_CLIENT_SECRET", "client_id" : "IDP_CLIENT_ID", "scopes": "openid profile" } }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/connections"); var request = new RestRequest(Method.POST); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); -request.AddParameter("undefined", "{ \"strategy\": \"oidc\", \"name\": \"CONNECTION_NAME\", \"options\": { \"type\": \"back_channel\", \"issuer\": \"https://IDP_DOMAIN\", \"authorization_endpoint\": \"https://IDP_DOMAIN/authorize\", \"client_secret\" : \"IDP_CLIENT_SECRET\", \"client_id\" : \"IDP_CLIENT_ID\", \"scopes\": \"openid profile\" } }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample23 = `package main +request.AddParameter("undefined", "{ "strategy": "oidc", "name": "CONNECTION_NAME", "options": { "type": "back_channel", "issuer": "https://IDP_DOMAIN", "authorization_endpoint": "https://IDP_DOMAIN/authorize", "client_secret" : "IDP_CLIENT_SECRET", "client_id" : "IDP_CLIENT_ID", "scopes": "openid profile" } }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -630,7 +656,7 @@ func main() { url := "https://{yourDomain}/api/v2/connections" - payload := strings.NewReader("{ \"strategy\": \"oidc\", \"name\": \"CONNECTION_NAME\", \"options\": { \"type\": \"back_channel\", \"issuer\": \"https://IDP_DOMAIN\", \"authorization_endpoint\": \"https://IDP_DOMAIN/authorize\", \"client_secret\" : \"IDP_CLIENT_SECRET\", \"client_id\" : \"IDP_CLIENT_ID\", \"scopes\": \"openid profile\" } }") + payload := strings.NewReader("{ "strategy": "oidc", "name": "CONNECTION_NAME", "options": { "type": "back_channel", "issuer": "https://IDP_DOMAIN", "authorization_endpoint": "https://IDP_DOMAIN/authorize", "client_secret" : "IDP_CLIENT_SECRET", "client_id" : "IDP_CLIENT_ID", "scopes": "openid profile" } }") req, _ := http.NewRequest("POST", url, payload) @@ -644,12 +670,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample24 = `HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/connections") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/connections") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") - .body("{ \"strategy\": \"oidc\", \"name\": \"CONNECTION_NAME\", \"options\": { \"type\": \"back_channel\", \"issuer\": \"https://IDP_DOMAIN\", \"authorization_endpoint\": \"https://IDP_DOMAIN/authorize\", \"client_secret\" : \"IDP_CLIENT_SECRET\", \"client_id\" : \"IDP_CLIENT_ID\", \"scopes\": \"openid profile\" } }") - .asString();`; -export const codeExample25 = `var axios = require("axios").default; + .body("{ "strategy": "oidc", "name": "CONNECTION_NAME", "options": { "type": "back_channel", "issuer": "https://IDP_DOMAIN", "authorization_endpoint": "https://IDP_DOMAIN/authorize", "client_secret" : "IDP_CLIENT_SECRET", "client_id" : "IDP_CLIENT_ID", "scopes": "openid profile" } }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -673,8 +703,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample26 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN" }; NSDictionary *parameters = @{ @"strategy": @"oidc", @@ -700,8 +732,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample27 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/connections", @@ -711,7 +745,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{ \"strategy\": \"oidc\", \"name\": \"CONNECTION_NAME\", \"options\": { \"type\": \"back_channel\", \"issuer\": \"https://IDP_DOMAIN\", \"authorization_endpoint\": \"https://IDP_DOMAIN/authorize\", \"client_secret\" : \"IDP_CLIENT_SECRET\", \"client_id\" : \"IDP_CLIENT_ID\", \"scopes\": \"openid profile\" } }", + CURLOPT_POSTFIELDS => "{ "strategy": "oidc", "name": "CONNECTION_NAME", "options": { "type": "back_channel", "issuer": "https://IDP_DOMAIN", "authorization_endpoint": "https://IDP_DOMAIN/authorize", "client_secret" : "IDP_CLIENT_SECRET", "client_id" : "IDP_CLIENT_ID", "scopes": "openid profile" } }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN" ], @@ -726,12 +760,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample28 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"strategy\": \"oidc\", \"name\": \"CONNECTION_NAME\", \"options\": { \"type\": \"back_channel\", \"issuer\": \"https://IDP_DOMAIN\", \"authorization_endpoint\": \"https://IDP_DOMAIN/authorize\", \"client_secret\" : \"IDP_CLIENT_SECRET\", \"client_id\" : \"IDP_CLIENT_ID\", \"scopes\": \"openid profile\" } }" +payload = "{ "strategy": "oidc", "name": "CONNECTION_NAME", "options": { "type": "back_channel", "issuer": "https://IDP_DOMAIN", "authorization_endpoint": "https://IDP_DOMAIN/authorize", "client_secret" : "IDP_CLIENT_SECRET", "client_id" : "IDP_CLIENT_ID", "scopes": "openid profile" } }" headers = { 'authorization': "Bearer MGMT_API_ACCESS_TOKEN" } @@ -740,8 +776,10 @@ conn.request("POST", "/{yourDomain}/api/v2/connections", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample29 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -753,11 +791,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' -request.body = "{ \"strategy\": \"oidc\", \"name\": \"CONNECTION_NAME\", \"options\": { \"type\": \"back_channel\", \"issuer\": \"https://IDP_DOMAIN\", \"authorization_endpoint\": \"https://IDP_DOMAIN/authorize\", \"client_secret\" : \"IDP_CLIENT_SECRET\", \"client_id\" : \"IDP_CLIENT_ID\", \"scopes\": \"openid profile\" } }" +request.body = "{ "strategy": "oidc", "name": "CONNECTION_NAME", "options": { "type": "back_channel", "issuer": "https://IDP_DOMAIN", "authorization_endpoint": "https://IDP_DOMAIN/authorize", "client_secret" : "IDP_CLIENT_SECRET", "client_id" : "IDP_CLIENT_ID", "scopes": "openid profile" } }" response = http.request(request) -puts response.read_body`; -export const codeExample30 = `imimport Foundation +puts response.read_body +``` +```swift Swift +imimport Foundation let headers = ["authorization": "Bearer MGMT_API_ACCESS_TOKEN"] let parameters = [ @@ -792,33 +832,28 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + #### Use front-channel specifying issuer settings -export const codeExample31 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/api/v2/connections' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ - --data '{ "strategy": "oidc", "name": "CONNECTION_NAME", "options": { "type": "front_channel", "issuer": "https://IDP_DOMAIN", "authorization_endpoint": "https://IDP_DOMAIN/authorize", "token_endpoint": "https://IDP_DOMAIN/oauth/token", "client_id" : "IDP_CLIENT_ID", "scopes": "openid profile" } }'`; -export const codeExample32 = `var client = new RestClient("https://{yourDomain}/api/v2/connections"); + --data '{ "strategy": "oidc", "name": "CONNECTION_NAME", "options": { "type": "front_channel", "issuer": "https://IDP_DOMAIN", "authorization_endpoint": "https://IDP_DOMAIN/authorize", "token_endpoint": "https://IDP_DOMAIN/oauth/token", "client_id" : "IDP_CLIENT_ID", "scopes": "openid profile" } }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/connections"); var request = new RestRequest(Method.POST); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); -request.AddParameter("undefined", "{ \"strategy\": \"oidc\", \"name\": \"CONNECTION_NAME\", \"options\": { \"type\": \"front_channel\", \"issuer\": \"https://IDP_DOMAIN\", \"authorization_endpoint\": \"https://IDP_DOMAIN/authorize\", \"token_endpoint\": \"https://IDP_DOMAIN/oauth/token\", \"client_id\" : \"IDP_CLIENT_ID\", \"scopes\": \"openid profile\" } }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample33 = `package main +request.AddParameter("undefined", "{ "strategy": "oidc", "name": "CONNECTION_NAME", "options": { "type": "front_channel", "issuer": "https://IDP_DOMAIN", "authorization_endpoint": "https://IDP_DOMAIN/authorize", "token_endpoint": "https://IDP_DOMAIN/oauth/token", "client_id" : "IDP_CLIENT_ID", "scopes": "openid profile" } }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -831,7 +866,7 @@ func main() { url := "https://{yourDomain}/api/v2/connections" - payload := strings.NewReader("{ \"strategy\": \"oidc\", \"name\": \"CONNECTION_NAME\", \"options\": { \"type\": \"front_channel\", \"issuer\": \"https://IDP_DOMAIN\", \"authorization_endpoint\": \"https://IDP_DOMAIN/authorize\", \"token_endpoint\": \"https://IDP_DOMAIN/oauth/token\", \"client_id\" : \"IDP_CLIENT_ID\", \"scopes\": \"openid profile\" } }") + payload := strings.NewReader("{ "strategy": "oidc", "name": "CONNECTION_NAME", "options": { "type": "front_channel", "issuer": "https://IDP_DOMAIN", "authorization_endpoint": "https://IDP_DOMAIN/authorize", "token_endpoint": "https://IDP_DOMAIN/oauth/token", "client_id" : "IDP_CLIENT_ID", "scopes": "openid profile" } }") req, _ := http.NewRequest("POST", url, payload) @@ -845,12 +880,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample34 = `HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/connections") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/connections") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") - .body("{ \"strategy\": \"oidc\", \"name\": \"CONNECTION_NAME\", \"options\": { \"type\": \"front_channel\", \"issuer\": \"https://IDP_DOMAIN\", \"authorization_endpoint\": \"https://IDP_DOMAIN/authorize\", \"token_endpoint\": \"https://IDP_DOMAIN/oauth/token\", \"client_id\" : \"IDP_CLIENT_ID\", \"scopes\": \"openid profile\" } }") - .asString();`; -export const codeExample35 = `var axios = require("axios").default; + .body("{ "strategy": "oidc", "name": "CONNECTION_NAME", "options": { "type": "front_channel", "issuer": "https://IDP_DOMAIN", "authorization_endpoint": "https://IDP_DOMAIN/authorize", "token_endpoint": "https://IDP_DOMAIN/oauth/token", "client_id" : "IDP_CLIENT_ID", "scopes": "openid profile" } }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -874,8 +913,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample36 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN" }; NSDictionary *parameters = @{ @"strategy": @"oidc", @@ -901,8 +942,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample37 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/connections", @@ -912,7 +955,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{ \"strategy\": \"oidc\", \"name\": \"CONNECTION_NAME\", \"options\": { \"type\": \"front_channel\", \"issuer\": \"https://IDP_DOMAIN\", \"authorization_endpoint\": \"https://IDP_DOMAIN/authorize\", \"token_endpoint\": \"https://IDP_DOMAIN/oauth/token\", \"client_id\" : \"IDP_CLIENT_ID\", \"scopes\": \"openid profile\" } }", + CURLOPT_POSTFIELDS => "{ "strategy": "oidc", "name": "CONNECTION_NAME", "options": { "type": "front_channel", "issuer": "https://IDP_DOMAIN", "authorization_endpoint": "https://IDP_DOMAIN/authorize", "token_endpoint": "https://IDP_DOMAIN/oauth/token", "client_id" : "IDP_CLIENT_ID", "scopes": "openid profile" } }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN" ], @@ -927,12 +970,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample38 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"strategy\": \"oidc\", \"name\": \"CONNECTION_NAME\", \"options\": { \"type\": \"front_channel\", \"issuer\": \"https://IDP_DOMAIN\", \"authorization_endpoint\": \"https://IDP_DOMAIN/authorize\", \"token_endpoint\": \"https://IDP_DOMAIN/oauth/token\", \"client_id\" : \"IDP_CLIENT_ID\", \"scopes\": \"openid profile\" } }" +payload = "{ "strategy": "oidc", "name": "CONNECTION_NAME", "options": { "type": "front_channel", "issuer": "https://IDP_DOMAIN", "authorization_endpoint": "https://IDP_DOMAIN/authorize", "token_endpoint": "https://IDP_DOMAIN/oauth/token", "client_id" : "IDP_CLIENT_ID", "scopes": "openid profile" } }" headers = { 'authorization': "Bearer MGMT_API_ACCESS_TOKEN" } @@ -941,8 +986,10 @@ conn.request("POST", "/{yourDomain}/api/v2/connections", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample39 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -954,11 +1001,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' -request.body = "{ \"strategy\": \"oidc\", \"name\": \"CONNECTION_NAME\", \"options\": { \"type\": \"front_channel\", \"issuer\": \"https://IDP_DOMAIN\", \"authorization_endpoint\": \"https://IDP_DOMAIN/authorize\", \"token_endpoint\": \"https://IDP_DOMAIN/oauth/token\", \"client_id\" : \"IDP_CLIENT_ID\", \"scopes\": \"openid profile\" } }" +request.body = "{ "strategy": "oidc", "name": "CONNECTION_NAME", "options": { "type": "front_channel", "issuer": "https://IDP_DOMAIN", "authorization_endpoint": "https://IDP_DOMAIN/authorize", "token_endpoint": "https://IDP_DOMAIN/oauth/token", "client_id" : "IDP_CLIENT_ID", "scopes": "openid profile" } }" response = http.request(request) -puts response.read_body`; -export const codeExample40 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer MGMT_API_ACCESS_TOKEN"] let parameters = [ @@ -993,20 +1042,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ## Configure PKCE and claims mapping diff --git a/main/docs/authenticate/identity-providers/enterprise-identity-providers/saml.mdx b/main/docs/authenticate/identity-providers/enterprise-identity-providers/saml.mdx index 1e793cf12..211fe445b 100644 --- a/main/docs/authenticate/identity-providers/enterprise-identity-providers/saml.mdx +++ b/main/docs/authenticate/identity-providers/enterprise-identity-providers/saml.mdx @@ -12,6 +12,8 @@ title: Connect Your App to SAML Identity Providers --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + Auth0 lets you create SAML Identity Provider (IdP) connections. ## Prerequisites @@ -179,20 +181,26 @@ You can also use the [Management API](https://auth0.com/docs/api/management/v2) Make a `POST` call to the [Create a Connection endpoint](https://auth0.com/docs/api/management/v2#!/Connections/patch_connections_by_id). Be sure to replace `MGMT_API_ACCESS_TOKEN`, `CONNECTION_NAME`, `SIGN_IN_ENDPOINT_URL`, `SIGN_OUT_ENDPOINT_URL`, and `BASE64_SIGNING_CERT` placeholder values with your Management API Access Token, connection name, sign in URL, sign out URL, and Base64-encoded signing certificate (in PEM or CER format), respectively. -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/api/v2/connections' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{ "strategy": "samlp", "name": "CONNECTION_NAME", "options": { "signInEndpoint": "SIGN_IN_ENDPOINT_URL", "signOutEndpoint": "SIGN_OUT_ENDPOINT_URL", "signatureAlgorithm": "rsa-sha256", "digestAlgorithm": "sha256", "fieldsMap": {}, "signingCert": "BASE64_SIGNING_CERT" } }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/connections"); + --data '{ "strategy": "samlp", "name": "CONNECTION_NAME", "options": { "signInEndpoint": "SIGN_IN_ENDPOINT_URL", "signOutEndpoint": "SIGN_OUT_ENDPOINT_URL", "signatureAlgorithm": "rsa-sha256", "digestAlgorithm": "sha256", "fieldsMap": {}, "signingCert": "BASE64_SIGNING_CERT" } }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/connections"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{ \"strategy\": \"samlp\", \"name\": \"CONNECTION_NAME\", \"options\": { \"signInEndpoint\": \"SIGN_IN_ENDPOINT_URL\", \"signOutEndpoint\": \"SIGN_OUT_ENDPOINT_URL\", \"signatureAlgorithm\": \"rsa-sha256\", \"digestAlgorithm\": \"sha256\", \"fieldsMap\": {}, \"signingCert\": \"BASE64_SIGNING_CERT\" } }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "strategy": "samlp", "name": "CONNECTION_NAME", "options": { "signInEndpoint": "SIGN_IN_ENDPOINT_URL", "signOutEndpoint": "SIGN_OUT_ENDPOINT_URL", "signatureAlgorithm": "rsa-sha256", "digestAlgorithm": "sha256", "fieldsMap": {}, "signingCert": "BASE64_SIGNING_CERT" } }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -205,7 +213,7 @@ func main() { url := "https://{yourDomain}/api/v2/connections" - payload := strings.NewReader("{ \"strategy\": \"samlp\", \"name\": \"CONNECTION_NAME\", \"options\": { \"signInEndpoint\": \"SIGN_IN_ENDPOINT_URL\", \"signOutEndpoint\": \"SIGN_OUT_ENDPOINT_URL\", \"signatureAlgorithm\": \"rsa-sha256\", \"digestAlgorithm\": \"sha256\", \"fieldsMap\": {}, \"signingCert\": \"BASE64_SIGNING_CERT\" } }") + payload := strings.NewReader("{ "strategy": "samlp", "name": "CONNECTION_NAME", "options": { "signInEndpoint": "SIGN_IN_ENDPOINT_URL", "signOutEndpoint": "SIGN_OUT_ENDPOINT_URL", "signatureAlgorithm": "rsa-sha256", "digestAlgorithm": "sha256", "fieldsMap": {}, "signingCert": "BASE64_SIGNING_CERT" } }") req, _ := http.NewRequest("POST", url, payload) @@ -221,14 +229,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/connections") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/connections") .header("content-type", "application/json") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ \"strategy\": \"samlp\", \"name\": \"CONNECTION_NAME\", \"options\": { \"signInEndpoint\": \"SIGN_IN_ENDPOINT_URL\", \"signOutEndpoint\": \"SIGN_OUT_ENDPOINT_URL\", \"signatureAlgorithm\": \"rsa-sha256\", \"digestAlgorithm\": \"sha256\", \"fieldsMap\": {}, \"signingCert\": \"BASE64_SIGNING_CERT\" } }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "strategy": "samlp", "name": "CONNECTION_NAME", "options": { "signInEndpoint": "SIGN_IN_ENDPOINT_URL", "signOutEndpoint": "SIGN_OUT_ENDPOINT_URL", "signatureAlgorithm": "rsa-sha256", "digestAlgorithm": "sha256", "fieldsMap": {}, "signingCert": "BASE64_SIGNING_CERT" } }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -256,8 +268,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @@ -285,8 +299,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/connections", @@ -296,7 +312,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{ \"strategy\": \"samlp\", \"name\": \"CONNECTION_NAME\", \"options\": { \"signInEndpoint\": \"SIGN_IN_ENDPOINT_URL\", \"signOutEndpoint\": \"SIGN_OUT_ENDPOINT_URL\", \"signatureAlgorithm\": \"rsa-sha256\", \"digestAlgorithm\": \"sha256\", \"fieldsMap\": {}, \"signingCert\": \"BASE64_SIGNING_CERT\" } }", + CURLOPT_POSTFIELDS => "{ "strategy": "samlp", "name": "CONNECTION_NAME", "options": { "signInEndpoint": "SIGN_IN_ENDPOINT_URL", "signOutEndpoint": "SIGN_OUT_ENDPOINT_URL", "signatureAlgorithm": "rsa-sha256", "digestAlgorithm": "sha256", "fieldsMap": {}, "signingCert": "BASE64_SIGNING_CERT" } }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "cache-control: no-cache", @@ -313,12 +329,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"strategy\": \"samlp\", \"name\": \"CONNECTION_NAME\", \"options\": { \"signInEndpoint\": \"SIGN_IN_ENDPOINT_URL\", \"signOutEndpoint\": \"SIGN_OUT_ENDPOINT_URL\", \"signatureAlgorithm\": \"rsa-sha256\", \"digestAlgorithm\": \"sha256\", \"fieldsMap\": {}, \"signingCert\": \"BASE64_SIGNING_CERT\" } }" +payload = "{ "strategy": "samlp", "name": "CONNECTION_NAME", "options": { "signInEndpoint": "SIGN_IN_ENDPOINT_URL", "signOutEndpoint": "SIGN_OUT_ENDPOINT_URL", "signatureAlgorithm": "rsa-sha256", "digestAlgorithm": "sha256", "fieldsMap": {}, "signingCert": "BASE64_SIGNING_CERT" } }" headers = { 'content-type': "application/json", @@ -331,8 +349,10 @@ conn.request("POST", "/{yourDomain}/api/v2/connections", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -346,11 +366,13 @@ request = Net::HTTP::Post.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ \"strategy\": \"samlp\", \"name\": \"CONNECTION_NAME\", \"options\": { \"signInEndpoint\": \"SIGN_IN_ENDPOINT_URL\", \"signOutEndpoint\": \"SIGN_OUT_ENDPOINT_URL\", \"signatureAlgorithm\": \"rsa-sha256\", \"digestAlgorithm\": \"sha256\", \"fieldsMap\": {}, \"signingCert\": \"BASE64_SIGNING_CERT\" } }" +request.body = "{ "strategy": "samlp", "name": "CONNECTION_NAME", "options": { "signInEndpoint": "SIGN_IN_ENDPOINT_URL", "signOutEndpoint": "SIGN_OUT_ENDPOINT_URL", "signatureAlgorithm": "rsa-sha256", "digestAlgorithm": "sha256", "fieldsMap": {}, "signingCert": "BASE64_SIGNING_CERT" } }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -389,20 +411,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + @@ -453,11 +464,6 @@ Or, in JSON: } ``` - - - - - #### Create a connection using SAML metadata Rather than specifying each SAML configuration field, you can specify a SAML metadata document that contains the configuration values. When specifying a SAML metadata document, you may provide either the XML content of the document (`metadataXml`) or the URL of the document (`metadataUrl`). When providing the URL, content is downloaded only once; the connection will not automatically reconfigure if the content of the URL changes in the future. @@ -466,20 +472,26 @@ Rather than specifying each SAML configuration field, you can specify a SAML met Use the `metadataXml` option to provide content of the document: -export const codeExample11 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/api/v2/connections' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{ "strategy": "samlp", "name": "CONNECTION_NAME", "options": { "metadataXml": "..." } }'`; -export const codeExample12 = `var client = new RestClient("https://{yourDomain}/api/v2/connections"); + --data '{ "strategy": "samlp", "name": "CONNECTION_NAME", "options": { "metadataXml": "..." } }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/connections"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{ \"strategy\": \"samlp\", \"name\": \"CONNECTION_NAME\", \"options\": { \"metadataXml\": \"...\" } }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample13 = `package main +request.AddParameter("application/json", "{ "strategy": "samlp", "name": "CONNECTION_NAME", "options": { "metadataXml": "..." } }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -492,7 +504,7 @@ func main() { url := "https://{yourDomain}/api/v2/connections" - payload := strings.NewReader("{ \"strategy\": \"samlp\", \"name\": \"CONNECTION_NAME\", \"options\": { \"metadataXml\": \"...\" } }") + payload := strings.NewReader("{ "strategy": "samlp", "name": "CONNECTION_NAME", "options": { "metadataXml": "..." } }") req, _ := http.NewRequest("POST", url, payload) @@ -508,14 +520,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample14 = `HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/connections") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/connections") .header("content-type", "application/json") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ \"strategy\": \"samlp\", \"name\": \"CONNECTION_NAME\", \"options\": { \"metadataXml\": \"...\" } }") - .asString();`; -export const codeExample15 = `var axios = require("axios").default; + .body("{ "strategy": "samlp", "name": "CONNECTION_NAME", "options": { "metadataXml": "..." } }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -529,7 +545,7 @@ var options = { strategy: 'samlp', name: 'CONNECTION_NAME', options: { - metadataXml: '...' + metadataXml: '...' } } }; @@ -538,8 +554,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample16 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @@ -567,8 +585,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/connections", @@ -578,7 +598,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{ \"strategy\": \"samlp\", \"name\": \"CONNECTION_NAME\", \"options\": { \"metadataXml\": \"...\" } }", + CURLOPT_POSTFIELDS => "{ "strategy": "samlp", "name": "CONNECTION_NAME", "options": { "metadataXml": "..." } }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "cache-control: no-cache", @@ -595,12 +615,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `iimport http.client +} +``` +```python Python +iimport http.client conn = http.client.HTTPSConnection("") -payload = "{ \"strategy\": \"samlp\", \"name\": \"CONNECTION_NAME\", \"options\": { \"metadataXml\": \"...\" } }" +payload = "{ "strategy": "samlp", "name": "CONNECTION_NAME", "options": { "metadataXml": "..." } }" headers = { 'content-type': "application/json", @@ -613,8 +635,10 @@ conn.request("POST", "/{yourDomain}/api/v2/connections", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -628,11 +652,13 @@ request = Net::HTTP::Post.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ \"strategy\": \"samlp\", \"name\": \"CONNECTION_NAME\", \"options\": { \"metadataXml\": \"...\" } }" +request.body = "{ "strategy": "samlp", "name": "CONNECTION_NAME", "options": { "metadataXml": "..." } }" response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -664,39 +690,34 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ##### Provide a metadata document URL Use the `metadataUrl` option to provide the URL of the document: -export const codeExample21 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/api/v2/connections' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{ "strategy": "samlp", "name": "CONNECTION_NAME", "options": { "metadataUrl": "https://saml-idp/samlp/metadata/uarlU13n63e0feZNJxOCNZ1To3a9H7jX" } }'`; -export const codeExample22 = `var client = new RestClient("https://{yourDomain}/api/v2/connections"); + --data '{ "strategy": "samlp", "name": "CONNECTION_NAME", "options": { "metadataUrl": "https://saml-idp/samlp/metadata/uarlU13n63e0feZNJxOCNZ1To3a9H7jX" } }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/connections"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{ \"strategy\": \"samlp\", \"name\": \"CONNECTION_NAME\", \"options\": { \"metadataUrl\": \"https://saml-idp/samlp/metadata/uarlU13n63e0feZNJxOCNZ1To3a9H7jX\" } }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample23 = `package main +request.AddParameter("application/json", "{ "strategy": "samlp", "name": "CONNECTION_NAME", "options": { "metadataUrl": "https://saml-idp/samlp/metadata/uarlU13n63e0feZNJxOCNZ1To3a9H7jX" } }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -709,7 +730,7 @@ func main() { url := "https://{yourDomain}/api/v2/connections" - payload := strings.NewReader("{ \"strategy\": \"samlp\", \"name\": \"CONNECTION_NAME\", \"options\": { \"metadataUrl\": \"https://saml-idp/samlp/metadata/uarlU13n63e0feZNJxOCNZ1To3a9H7jX\" } }") + payload := strings.NewReader("{ "strategy": "samlp", "name": "CONNECTION_NAME", "options": { "metadataUrl": "https://saml-idp/samlp/metadata/uarlU13n63e0feZNJxOCNZ1To3a9H7jX" } }") req, _ := http.NewRequest("POST", url, payload) @@ -725,14 +746,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample24 = `HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/connections") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/connections") .header("content-type", "application/json") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ \"strategy\": \"samlp\", \"name\": \"CONNECTION_NAME\", \"options\": { \"metadataUrl\": \"https://saml-idp/samlp/metadata/uarlU13n63e0feZNJxOCNZ1To3a9H7jX\" } }") - .asString();`; -export const codeExample25 = `var axios = require("axios").default; + .body("{ "strategy": "samlp", "name": "CONNECTION_NAME", "options": { "metadataUrl": "https://saml-idp/samlp/metadata/uarlU13n63e0feZNJxOCNZ1To3a9H7jX" } }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -755,8 +780,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample26 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @@ -784,8 +811,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample27 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/connections", @@ -795,7 +824,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{ \"strategy\": \"samlp\", \"name\": \"CONNECTION_NAME\", \"options\": { \"metadataUrl\": \"https://saml-idp/samlp/metadata/uarlU13n63e0feZNJxOCNZ1To3a9H7jX\" } }", + CURLOPT_POSTFIELDS => "{ "strategy": "samlp", "name": "CONNECTION_NAME", "options": { "metadataUrl": "https://saml-idp/samlp/metadata/uarlU13n63e0feZNJxOCNZ1To3a9H7jX" } }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "cache-control: no-cache", @@ -812,12 +841,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample28 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"strategy\": \"samlp\", \"name\": \"CONNECTION_NAME\", \"options\": { \"metadataUrl\": \"https://saml-idp/samlp/metadata/uarlU13n63e0feZNJxOCNZ1To3a9H7jX\" } }" +payload = "{ "strategy": "samlp", "name": "CONNECTION_NAME", "options": { "metadataUrl": "https://saml-idp/samlp/metadata/uarlU13n63e0feZNJxOCNZ1To3a9H7jX" } }" headers = { 'content-type': "application/json", @@ -830,8 +861,10 @@ conn.request("POST", "/{yourDomain}/api/v2/connections", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample29 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -845,11 +878,13 @@ request = Net::HTTP::Post.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ \"strategy\": \"samlp\", \"name\": \"CONNECTION_NAME\", \"options\": { \"metadataUrl\": \"https://saml-idp/samlp/metadata/uarlU13n63e0feZNJxOCNZ1To3a9H7jX\" } }" +request.body = "{ "strategy": "samlp", "name": "CONNECTION_NAME", "options": { "metadataUrl": "https://saml-idp/samlp/metadata/uarlU13n63e0feZNJxOCNZ1To3a9H7jX" } }" response = http.request(request) -puts response.read_body`; -export const codeExample30 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -881,20 +916,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + When providing the URL, content is downloaded only once; the connection will not automatically reconfigure if the content of the URL changes in the future. @@ -937,11 +961,6 @@ The JSON example below can be used to create a new SAML connection using the SAM } ``` - - - - - ## Enable the enterprise connection for your Auth0 application To use your new SAML enterprise connection, you must first [enable the connection](/docs/authenticate/identity-providers/enterprise-identity-providers/enable-enterprise-connections) for your Auth0 Applications. @@ -967,11 +986,6 @@ Select the **Mappings** view, enter mappings between the `{}`, and select **Save } ``` - - - - - **Mappings for SSO Circle** ```json lines @@ -982,11 +996,6 @@ Select the **Mappings** view, enter mappings between the `{}`, and select **Save } ``` - - - - - **Map either of two claims to one user attribute** ```json lines @@ -998,11 +1007,6 @@ Select the **Mappings** view, enter mappings between the `{}`, and select **Save } ``` - - - - - **How to map name identifier to a user attribute** ```json lines @@ -1015,11 +1019,6 @@ Select the **Mappings** view, enter mappings between the `{}`, and select **Save } ``` - - - - - ## Test the connection Now you're ready to [test your connection](/docs/authenticate/identity-providers/enterprise-identity-providers/test-enterprise-connections). diff --git a/main/docs/authenticate/identity-providers/pass-parameters-to-idps.mdx b/main/docs/authenticate/identity-providers/pass-parameters-to-idps.mdx index 90c1afda5..966ed2224 100644 --- a/main/docs/authenticate/identity-providers/pass-parameters-to-idps.mdx +++ b/main/docs/authenticate/identity-providers/pass-parameters-to-idps.mdx @@ -10,6 +10,8 @@ title: Pass Parameters to Identity Providers --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + You can pass provider-specific parameters to an Identity Provider (IdP) during authentication. The values can either be static per connection or dynamic per user. ## Limitations @@ -36,16 +38,22 @@ To follow this example, you'll need a working [WordPress Social connection](http Call the Management API [Get a connection](https://auth0.com/docs/api/management/v2#!/Connections/get_connections_by_id) endpoint to retrieve the existing values of the `options` object: -export const codeExample1 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/connections/%7ByourWordpressConnectionId%7D' \ --header 'authorization: Bearer {yourMgmtApiAccessToken}' \ - --header 'content-type: application/json'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/connections/%7ByourWordpressConnectionId%7D"); + --header 'content-type: application/json' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/connections/%7ByourWordpressConnectionId%7D"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer {yourMgmtApiAccessToken}"); request.AddHeader("content-type", "application/json"); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -70,12 +78,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/connections/%7ByourWordpressConnectionId%7D") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/connections/%7ByourWordpressConnectionId%7D") .header("authorization", "Bearer {yourMgmtApiAccessToken}") .header("content-type", "application/json") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -90,8 +102,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer {yourMgmtApiAccessToken}", @"content-type": @"application/json" }; @@ -112,8 +126,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/connections/%7ByourWordpressConnectionId%7D", @@ -138,8 +154,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -153,8 +171,10 @@ conn.request("GET", "/{yourDomain}/api/v2/connections/%7ByourWordpressConnection res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -169,8 +189,10 @@ request["authorization"] = 'Bearer {yourMgmtApiAccessToken}' request["content-type"] = 'application/json' response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "authorization": "Bearer {yourMgmtApiAccessToken}", @@ -193,20 +215,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + The `options` object will look something like this: @@ -220,11 +231,6 @@ The `options` object will look something like this: } ``` - - - - - #### Update the connection (static) Copy the existing `options` object, and then add the `upstream_params` object with the `blog` field as an attribute: @@ -242,25 +248,26 @@ Copy the existing `options` object, and then add the `upstream_params` object wi } ``` - - - - - Call the Management API [Update a connection](https://auth0.com/docs/api/management/v2/#!/Connections/patch_connections_by_id) endpoint with the `options` object in the body: -export const codeExample11 = `curl --request PATCH \ + +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/connections/%7ByourWordpressConnectionId%7D' \ --header 'authorization: Bearer {yourMgmtApiAccessToken}' \ --header 'content-type: application/json' \ - --data '{"options":{"client_id":"","profile":true,"scope":["profile"],"upstream_params":{"blog":{"value":"myblog.wordpress.com"}}}}'`; -export const codeExample12 = `var client = new RestClient("https://{yourDomain}/api/v2/connections/%7ByourWordpressConnectionId%7D"); + --data '{"options":{"client_id":"","profile":true,"scope":["profile"],"upstream_params":{"blog":{"value":"myblog.wordpress.com"}}}}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/connections/%7ByourWordpressConnectionId%7D"); var request = new RestRequest(Method.PATCH); request.AddHeader("authorization", "Bearer {yourMgmtApiAccessToken}"); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\"options\":{\"client_id\":\"\",\"profile\":true,\"scope\":[\"profile\"],\"upstream_params\":{\"blog\":{\"value\":\"myblog.wordpress.com\"}}}}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample13 = `package main +request.AddParameter("application/json", "{"options":{"client_id":"","profile":true,"scope":["profile"],"upstream_params":{"blog":{"value":"myblog.wordpress.com"}}}}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -273,7 +280,7 @@ func main() { url := "https://{yourDomain}/api/v2/connections/%7ByourWordpressConnectionId%7D" - payload := strings.NewReader("{\"options\":{\"client_id\":\"\",\"profile\":true,\"scope\":[\"profile\"],\"upstream_params\":{\"blog\":{\"value\":\"myblog.wordpress.com\"}}}}") + payload := strings.NewReader("{"options":{"client_id":"","profile":true,"scope":["profile"],"upstream_params":{"blog":{"value":"myblog.wordpress.com"}}}}") req, _ := http.NewRequest("PATCH", url, payload) @@ -288,13 +295,17 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample14 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/connections/%7ByourWordpressConnectionId%7D") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/connections/%7ByourWordpressConnectionId%7D") .header("authorization", "Bearer {yourMgmtApiAccessToken}") .header("content-type", "application/json") - .body("{\"options\":{\"client_id\":\"\",\"profile\":true,\"scope\":[\"profile\"],\"upstream_params\":{\"blog\":{\"value\":\"myblog.wordpress.com\"}}}}") - .asString();`; -export const codeExample15 = `var axios = require("axios").default; + .body("{"options":{"client_id":"","profile":true,"scope":["profile"],"upstream_params":{"blog":{"value":"myblog.wordpress.com"}}}}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -317,8 +328,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample16 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer {yourMgmtApiAccessToken}", @"content-type": @"application/json" }; @@ -343,8 +356,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/connections/%7ByourWordpressConnectionId%7D", @@ -354,7 +369,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{\"options\":{\"client_id\":\"\",\"profile\":true,\"scope\":[\"profile\"],\"upstream_params\":{\"blog\":{\"value\":\"myblog.wordpress.com\"}}}}", + CURLOPT_POSTFIELDS => "{"options":{"client_id":"","profile":true,"scope":["profile"],"upstream_params":{"blog":{"value":"myblog.wordpress.com"}}}}", CURLOPT_HTTPHEADER => [ "authorization: Bearer {yourMgmtApiAccessToken}", "content-type: application/json" @@ -370,12 +385,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"options\":{\"client_id\":\"\",\"profile\":true,\"scope\":[\"profile\"],\"upstream_params\":{\"blog\":{\"value\":\"myblog.wordpress.com\"}}}}" +payload = "{"options":{"client_id":"","profile":true,"scope":["profile"],"upstream_params":{"blog":{"value":"myblog.wordpress.com"}}}}" headers = { 'authorization': "Bearer {yourMgmtApiAccessToken}", @@ -387,8 +404,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/connections/%7ByourWordpressConnecti res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -401,11 +420,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Patch.new(url) request["authorization"] = 'Bearer {yourMgmtApiAccessToken}' request["content-type"] = 'application/json' -request.body = "{\"options\":{\"client_id\":\"\",\"profile\":true,\"scope\":[\"profile\"],\"upstream_params\":{\"blog\":{\"value\":\"myblog.wordpress.com\"}}}}" +request.body = "{"options":{"client_id":"","profile":true,"scope":["profile"],"upstream_params":{"blog":{"value":"myblog.wordpress.com"}}}}" response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "authorization": "Bearer {yourMgmtApiAccessToken}", @@ -437,20 +458,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + Now every time a user authenticates with this connection, the request to the Wordpress authorization endpoint will include the query parameter `blog=myblog.wordpress.com`. @@ -474,11 +484,6 @@ Here's a sample `options` object that we'll revisit later in the X example: } ``` - - - - - ### Available fields These are the available fields for the `alias` attribute: @@ -506,16 +511,22 @@ To follow this example, you'll need a working [Twitter Social connection](https: Call the Management API [Get a connection](https://auth0.com/docs/api/management/v2#!/Connections/get_connections_by_id) endpoint to retrieve the existing values of the `options` object: -export const codeExample21 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/connections/%7ByourXConnectionId%7D' \ --header 'authorization: Bearer {yourMgmtApiAccessToken}' \ - --header 'content-type: application/json'`; -export const codeExample22 = `var client = new RestClient("https://{yourDomain}/api/v2/connections/%7ByourXConnectionId%7D"); + --header 'content-type: application/json' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/connections/%7ByourXConnectionId%7D"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer {yourMgmtApiAccessToken}"); request.AddHeader("content-type", "application/json"); -IRestResponse response = client.Execute(request);`; -export const codeExample23 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -540,12 +551,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample24 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/connections/%7ByourXConnectionId%7D") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/connections/%7ByourXConnectionId%7D") .header("authorization", "Bearer {yourMgmtApiAccessToken}") .header("content-type", "application/json") - .asString();`; -export const codeExample25 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -560,8 +575,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample26 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer {yourMgmtApiAccessToken}", @"content-type": @"application/json" }; @@ -582,8 +599,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample27 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/connections/%7ByourXConnectionId%7D", @@ -608,8 +627,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample28 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -623,8 +644,10 @@ conn.request("GET", "/{yourDomain}/api/v2/connections/%7ByourXConnectionId%7D", res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample29 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -639,8 +662,10 @@ request["authorization"] = 'Bearer {yourMgmtApiAccessToken}' request["content-type"] = 'application/json' response = http.request(request) -puts response.read_body`; -export const codeExample30 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "authorization": "Bearer {yourMgmtApiAccessToken}", @@ -663,20 +688,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + The `options` object will look something like this: @@ -688,11 +702,6 @@ The `options` object will look something like this: } ``` - - - - - #### Update the connection (dynamic) Copy the existing `options` object, add the `upstream_params` object with the `screen_name` field as an attribute, and then set the `alias` attribute to `login_hint`: @@ -712,25 +721,26 @@ Copy the existing `options` object, add the `upstream_params` object with the `s } ``` - - - - - Call the Management API [Update a connection](https://auth0.com/docs/api/management/v2/#!/Connections/patch_connections_by_id) endpoint with the `options` object in the body: -export const codeExample31 = `curl --request PATCH \ + +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/connections/%7ByourXConnectionId%7D' \ --header 'authorization: Bearer {yourMgmtApiAccessToken}' \ --header 'content-type: application/json' \ - --data '{"options": {"client_id": "{clientId}", "client_secret": "{clientSecret}", "profile": true, "upstream_params": {"screen_name": {"alias": "login_hint"}}}}'`; -export const codeExample32 = `var client = new RestClient("https://{yourDomain}/api/v2/connections/%7ByourXConnectionId%7D"); + --data '{"options": {"client_id": "{clientId}", "client_secret": "{clientSecret}", "profile": true, "upstream_params": {"screen_name": {"alias": "login_hint"}}}}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/connections/%7ByourXConnectionId%7D"); var request = new RestRequest(Method.PATCH); request.AddHeader("authorization", "Bearer {yourMgmtApiAccessToken}"); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\"options\": {\"client_id\": \"{clientId}\", \"client_secret\": \"{clientSecret}\", \"profile\": true, \"upstream_params\": {\"screen_name\": {\"alias\": \"login_hint\"}}}}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample33 = `package main +request.AddParameter("application/json", "{"options": {"client_id": "{clientId}", "client_secret": "{clientSecret}", "profile": true, "upstream_params": {"screen_name": {"alias": "login_hint"}}}}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -743,7 +753,7 @@ func main() { url := "https://{yourDomain}/api/v2/connections/%7ByourXConnectionId%7D" - payload := strings.NewReader("{\"options\": {\"client_id\": \"{clientId}\", \"client_secret\": \"{clientSecret}\", \"profile\": true, \"upstream_params\": {\"screen_name\": {\"alias\": \"login_hint\"}}}}") + payload := strings.NewReader("{"options": {"client_id": "{clientId}", "client_secret": "{clientSecret}", "profile": true, "upstream_params": {"screen_name": {"alias": "login_hint"}}}}") req, _ := http.NewRequest("PATCH", url, payload) @@ -758,13 +768,17 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample34 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/connections/%7ByourXConnectionId%7D") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/connections/%7ByourXConnectionId%7D") .header("authorization", "Bearer {yourMgmtApiAccessToken}") .header("content-type", "application/json") - .body("{\"options\": {\"client_id\": \"{clientId}\", \"client_secret\": \"{clientSecret}\", \"profile\": true, \"upstream_params\": {\"screen_name\": {\"alias\": \"login_hint\"}}}}") - .asString();`; -export const codeExample35 = `var axios = require("axios").default; + .body("{"options": {"client_id": "{clientId}", "client_secret": "{clientSecret}", "profile": true, "upstream_params": {"screen_name": {"alias": "login_hint"}}}}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -787,8 +801,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample36 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer {yourMgmtApiAccessToken}", @"content-type": @"application/json" }; @@ -813,8 +829,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample37 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/connections/%7ByourXConnectionId%7D", @@ -824,7 +842,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{\"options\": {\"client_id\": \"{clientId}\", \"client_secret\": \"{clientSecret}\", \"profile\": true, \"upstream_params\": {\"screen_name\": {\"alias\": \"login_hint\"}}}}", + CURLOPT_POSTFIELDS => "{"options": {"client_id": "{clientId}", "client_secret": "{clientSecret}", "profile": true, "upstream_params": {"screen_name": {"alias": "login_hint"}}}}", CURLOPT_HTTPHEADER => [ "authorization: Bearer {yourMgmtApiAccessToken}", "content-type: application/json" @@ -840,12 +858,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample38 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"options\": {\"client_id\": \"{clientId}\", \"client_secret\": \"{clientSecret}\", \"profile\": true, \"upstream_params\": {\"screen_name\": {\"alias\": \"login_hint\"}}}}" +payload = "{"options": {"client_id": "{clientId}", "client_secret": "{clientSecret}", "profile": true, "upstream_params": {"screen_name": {"alias": "login_hint"}}}}" headers = { 'authorization': "Bearer {yourMgmtApiAccessToken}", @@ -857,8 +877,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/connections/%7ByourXConnectionId%7D" res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample39 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -871,11 +893,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Patch.new(url) request["authorization"] = 'Bearer {yourMgmtApiAccessToken}' request["content-type"] = 'application/json' -request.body = "{\"options\": {\"client_id\": \"{clientId}\", \"client_secret\": \"{clientSecret}\", \"profile\": true, \"upstream_params\": {\"screen_name\": {\"alias\": \"login_hint\"}}}}" +request.body = "{"options": {"client_id": "{clientId}", "client_secret": "{clientSecret}", "profile": true, "upstream_params": {"screen_name": {"alias": "login_hint"}}}}" response = http.request(request) -puts response.read_body`; -export const codeExample40 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "authorization": "Bearer {yourMgmtApiAccessToken}", @@ -907,20 +931,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + #### Call the login endpoint @@ -935,11 +948,6 @@ export const codeExample41 = `https://{yourDomain}/authorize - - - - - This value will then be passed to the X authorization endpoint as the `screen_name` parameter: ```text lines @@ -948,5 +956,3 @@ https://api.twitter.com/oauth/authorize &screen_name=user@domain.com ``` - - diff --git a/main/docs/authenticate/identity-providers/promote-connections-to-domain-level.mdx b/main/docs/authenticate/identity-providers/promote-connections-to-domain-level.mdx index c9282bba8..20ce7ec56 100644 --- a/main/docs/authenticate/identity-providers/promote-connections-to-domain-level.mdx +++ b/main/docs/authenticate/identity-providers/promote-connections-to-domain-level.mdx @@ -12,26 +12,34 @@ title: Promote Connections to Domain Level --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + If your tenant has [Dynamic Client Registration](/docs/get-started/applications/dynamic-client-registration) enabled, you can let [third party applications](/docs/get-started/applications/confidential-and-public-applications/enable-third-party-applications) use a connection by promoting it to a domain level connection. Domain level connections are enabled or disabled for all applications in a tenant. You can promote a connection to domain level using Auth0's Management API. Make a `PATCH` call to the [Update a Connection endpoint](https://auth0.com/docs/api/management/v2#!/Connections/patch_connections_by_id). Be sure to replace `CONNECTION_ID` and `MGMT_API_ACCESS_TOKEN` placeholder values with your connection ID and Management API Access Token, respectively. -export const codeExample1 = `curl --request PATCH \ + +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/connections/CONNECTION_ID' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{ "is_domain_connection": true }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/connections/CONNECTION_ID"); + --data '{ "is_domain_connection": true }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/connections/CONNECTION_ID"); var request = new RestRequest(Method.PATCH); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{ \"is_domain_connection\": true }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "is_domain_connection": true }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -44,7 +52,7 @@ func main() { url := "https://{yourDomain}/api/v2/connections/CONNECTION_ID" - payload := strings.NewReader("{ \"is_domain_connection\": true }") + payload := strings.NewReader("{ "is_domain_connection": true }") req, _ := http.NewRequest("PATCH", url, payload) @@ -60,14 +68,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/connections/CONNECTION_ID") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/connections/CONNECTION_ID") .header("content-type", "application/json") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ \"is_domain_connection\": true }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "is_domain_connection": true }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -84,8 +96,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @@ -111,8 +125,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/connections/CONNECTION_ID", @@ -122,7 +138,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{ \"is_domain_connection\": true }", + CURLOPT_POSTFIELDS => "{ "is_domain_connection": true }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "cache-control: no-cache", @@ -139,12 +155,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"is_domain_connection\": true }" +payload = "{ "is_domain_connection": true }" headers = { 'content-type': "application/json", @@ -157,8 +175,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/connections/CONNECTION_ID", payload, res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -172,11 +192,13 @@ request = Net::HTTP::Patch.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ \"is_domain_connection\": true }" +request.body = "{ "is_domain_connection": true }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -204,20 +226,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
diff --git a/main/docs/authenticate/identity-providers/retrieve-connection-options.mdx b/main/docs/authenticate/identity-providers/retrieve-connection-options.mdx index 55ca168b6..2b8c2064a 100644 --- a/main/docs/authenticate/identity-providers/retrieve-connection-options.mdx +++ b/main/docs/authenticate/identity-providers/retrieve-connection-options.mdx @@ -12,18 +12,26 @@ title: Retrieve Connection Options --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + You can retrieve the options object for a [connection](/docs/authenticate/identity-providers) using Auth0's Management API. Make a `GET` call to the [Get Connection endpoint](https://auth0.com/docs/api/management/v2#!/Connections/get_connections_by_id). Be sure to replace `CONNECTION_ID` and `MGMT_API_ACCESS_TOKEN` placeholder values with your connection ID and Management API Access Token, respectively. -export const codeExample1 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/connections/CONNECTION-ID?fields=options' \ - --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/connections/CONNECTION-ID?fields=options"); + --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/connections/CONNECTION-ID?fields=options"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -47,11 +55,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/connections/CONNECTION-ID?fields=options") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/connections/CONNECTION-ID?fields=options") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -64,8 +76,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN" }; @@ -85,8 +99,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/connections/CONNECTION-ID?fields=options", @@ -110,8 +126,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = ` +} +``` +```import http.client + conn = http.client.HTTPSConnection("") headers = { 'authorization': "Bearer MGMT_API_ACCESS_TOKEN" } @@ -121,8 +139,10 @@ conn.request("GET", "/{yourDomain}/api/v2/connections/CONNECTION-ID?fields=optio res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -136,8 +156,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer MGMT_API_ACCESS_TOKEN"] @@ -157,20 +179,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
diff --git a/main/docs/authenticate/identity-providers/social-identity-providers/oauth2.mdx b/main/docs/authenticate/identity-providers/social-identity-providers/oauth2.mdx index 2fe33a884..06aef0d94 100644 --- a/main/docs/authenticate/identity-providers/social-identity-providers/oauth2.mdx +++ b/main/docs/authenticate/identity-providers/social-identity-providers/oauth2.mdx @@ -11,6 +11,8 @@ title: Connect Apps to Generic OAuth2 Authorization Servers --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + The most common [identity providers (IdP)](/docs/authenticate/identity-providers) are available in [Auth0 Dashboard](https://manage.auth0.com/#) and in the [Auth0 Marketplace](https://marketplace.auth0.com/features/social-connections). You can, however, add any OAuth 2.0 provider as a **Custom Social Connection** in the Auth0 Dashboard. 1. In the Dashboard, go to [Authentication > Social](https://manage.auth0.com/#/connections/social). @@ -70,7 +72,6 @@ When you create a connection, the default OAuth 2.0 grant type assigned to the c } ``` - @@ -119,11 +120,6 @@ function fetchUserProfile(accessToken, context, callback) { } ``` - - - - - The `user_id` property in the returned profile is required, and the `email` property is optional but highly recommended. To learn more about what attributes can be returned, see [User Profile Root Attributes](/docs/manage-users/user-accounts/user-profiles/root-attributes/update-root-attributes-for-users). You can filter, add, or remove anything from the profile returned from the provider. However, it is recommended that you keep this script as simple as possible. More sophisticated manipulation of user information can be achieved through the use of [Rules](/docs/customize/rules). One advantage of using Rules is that they apply to any connection. @@ -141,11 +137,6 @@ export const codeExample1 = `https://{yourDomain}/authorize - - - - - ## Modify the icon and display name To add an icon to the identity provider's login button or change the text used on the login button, you can use the `icon_url` property of the `options` object and the `display_name` property, respectively, via the [Management API](https://auth0.com/docs/api/management/v2#!/Connections/patch_connections_by_id). @@ -157,16 +148,22 @@ To add an icon to the identity provider's login button or change the text used o -export const codeExample2 = `curl --request PATCH \ + +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/connections/CONNECTION-ID' \ --header 'content-type: application/json' \ - --data '{ "options": { "client_id": "...", "client_secret": "...", "icon_url": "https://cdn.example.com/assets/icon.png", "scripts": { "fetchUserProfile": "..." }, "authorizationURL": "https://public-auth.example.com/oauth2/authorize", "tokenURL": "https://auth.example.com/oauth2/token", "scope": "auth" }, "enabled_clients": [ "..." ] }, "display_name": "Connection Name"'`; -export const codeExample3 = `var client = new RestClient("https://{yourDomain}/api/v2/connections/CONNECTION-ID"); + --data '{ "options": { "client_id": "...", "client_secret": "...", "icon_url": "https://cdn.example.com/assets/icon.png", "scripts": { "fetchUserProfile": "..." }, "authorizationURL": "https://public-auth.example.com/oauth2/authorize", "tokenURL": "https://auth.example.com/oauth2/token", "scope": "auth" }, "enabled_clients": [ "..." ] }, "display_name": "Connection Name"' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/connections/CONNECTION-ID"); var request = new RestRequest(Method.PATCH); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{ \"options\": { \"client_id\": \"...\", \"client_secret\": \"...\", \"icon_url\": \"https://cdn.example.com/assets/icon.png\", \"scripts\": { \"fetchUserProfile\": \"...\" }, \"authorizationURL\": \"https://public-auth.example.com/oauth2/authorize\", \"tokenURL\": \"https://auth.example.com/oauth2/token\", \"scope\": \"auth\" }, \"enabled_clients\": [ \"...\" ] }, \"display_name\": \"Connection Name\"", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample4 = `package main +request.AddParameter("application/json", "{ "options": { "client_id": "...", "client_secret": "...", "icon_url": "https://cdn.example.com/assets/icon.png", "scripts": { "fetchUserProfile": "..." }, "authorizationURL": "https://public-auth.example.com/oauth2/authorize", "tokenURL": "https://auth.example.com/oauth2/token", "scope": "auth" }, "enabled_clients": [ "..." ] }, "display_name": "Connection Name"", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -179,7 +176,7 @@ func main() { url := "https://{yourDomain}/api/v2/connections/CONNECTION-ID" - payload := strings.NewReader("{ \"options\": { \"client_id\": \"...\", \"client_secret\": \"...\", \"icon_url\": \"https://cdn.example.com/assets/icon.png\", \"scripts\": { \"fetchUserProfile\": \"...\" }, \"authorizationURL\": \"https://public-auth.example.com/oauth2/authorize\", \"tokenURL\": \"https://auth.example.com/oauth2/token\", \"scope\": \"auth\" }, \"enabled_clients\": [ \"...\" ] }, \"display_name\": \"Connection Name\"") + payload := strings.NewReader("{ "options": { "client_id": "...", "client_secret": "...", "icon_url": "https://cdn.example.com/assets/icon.png", "scripts": { "fetchUserProfile": "..." }, "authorizationURL": "https://public-auth.example.com/oauth2/authorize", "tokenURL": "https://auth.example.com/oauth2/token", "scope": "auth" }, "enabled_clients": [ "..." ] }, "display_name": "Connection Name"") req, _ := http.NewRequest("PATCH", url, payload) @@ -193,12 +190,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample5 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/connections/CONNECTION-ID") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/connections/CONNECTION-ID") .header("content-type", "application/json") - .body("{ \"options\": { \"client_id\": \"...\", \"client_secret\": \"...\", \"icon_url\": \"https://cdn.example.com/assets/icon.png\", \"scripts\": { \"fetchUserProfile\": \"...\" }, \"authorizationURL\": \"https://public-auth.example.com/oauth2/authorize\", \"tokenURL\": \"https://auth.example.com/oauth2/token\", \"scope\": \"auth\" }, \"enabled_clients\": [ \"...\" ] }, \"display_name\": \"Connection Name\"") - .asString();`; -export const codeExample6 = `var axios = require("axios").default; + .body("{ "options": { "client_id": "...", "client_secret": "...", "icon_url": "https://cdn.example.com/assets/icon.png", "scripts": { "fetchUserProfile": "..." }, "authorizationURL": "https://public-auth.example.com/oauth2/authorize", "tokenURL": "https://auth.example.com/oauth2/token", "scope": "auth" }, "enabled_clients": [ "..." ] }, "display_name": "Connection Name"") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -211,8 +212,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample7 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json" }; @@ -235,8 +238,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample8 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/connections/CONNECTION-ID", @@ -246,7 +251,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{ \"options\": { \"client_id\": \"...\", \"client_secret\": \"...\", \"icon_url\": \"https://cdn.example.com/assets/icon.png\", \"scripts\": { \"fetchUserProfile\": \"...\" }, \"authorizationURL\": \"https://public-auth.example.com/oauth2/authorize\", \"tokenURL\": \"https://auth.example.com/oauth2/token\", \"scope\": \"auth\" }, \"enabled_clients\": [ \"...\" ] }, \"display_name\": \"Connection Name\"", + CURLOPT_POSTFIELDS => "{ "options": { "client_id": "...", "client_secret": "...", "icon_url": "https://cdn.example.com/assets/icon.png", "scripts": { "fetchUserProfile": "..." }, "authorizationURL": "https://public-auth.example.com/oauth2/authorize", "tokenURL": "https://auth.example.com/oauth2/token", "scope": "auth" }, "enabled_clients": [ "..." ] }, "display_name": "Connection Name"", CURLOPT_HTTPHEADER => [ "content-type: application/json" ], @@ -261,12 +266,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample9 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"options\": { \"client_id\": \"...\", \"client_secret\": \"...\", \"icon_url\": \"https://cdn.example.com/assets/icon.png\", \"scripts\": { \"fetchUserProfile\": \"...\" }, \"authorizationURL\": \"https://public-auth.example.com/oauth2/authorize\", \"tokenURL\": \"https://auth.example.com/oauth2/token\", \"scope\": \"auth\" }, \"enabled_clients\": [ \"...\" ] }, \"display_name\": \"Connection Name\"" +payload = "{ "options": { "client_id": "...", "client_secret": "...", "icon_url": "https://cdn.example.com/assets/icon.png", "scripts": { "fetchUserProfile": "..." }, "authorizationURL": "https://public-auth.example.com/oauth2/authorize", "tokenURL": "https://auth.example.com/oauth2/token", "scope": "auth" }, "enabled_clients": [ "..." ] }, "display_name": "Connection Name"" headers = { 'content-type': "application/json" } @@ -275,8 +282,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/connections/CONNECTION-ID", payload, res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample10 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -288,11 +297,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Patch.new(url) request["content-type"] = 'application/json' -request.body = "{ \"options\": { \"client_id\": \"...\", \"client_secret\": \"...\", \"icon_url\": \"https://cdn.example.com/assets/icon.png\", \"scripts\": { \"fetchUserProfile\": \"...\" }, \"authorizationURL\": \"https://public-auth.example.com/oauth2/authorize\", \"tokenURL\": \"https://auth.example.com/oauth2/token\", \"scope\": \"auth\" }, \"enabled_clients\": [ \"...\" ] }, \"display_name\": \"Connection Name\"" +request.body = "{ "options": { "client_id": "...", "client_secret": "...", "icon_url": "https://cdn.example.com/assets/icon.png", "scripts": { "fetchUserProfile": "..." }, "authorizationURL": "https://public-auth.example.com/oauth2/authorize", "tokenURL": "https://auth.example.com/oauth2/token", "scope": "auth" }, "enabled_clients": [ "..." ] }, "display_name": "Connection Name"" response = http.request(request) -puts response.read_body`; -export const codeExample11 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/json"] @@ -315,20 +326,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ## Pass provider-specific parameters @@ -338,16 +338,22 @@ You can pass provider-specific parameters to the Authorization endpoint of OAuth To pass static parameters (parameters that are sent with every authorization request), you can use the `authParams` element of the `options` when configuring an OAuth 2.0 connection via the [Management API](https://auth0.com/docs/api/management/v2#!/Connections/patch_connections_by_id). The call below will set a static parameter of `custom_param` set to `custom.param.value` on all authorization requests: -export const codeExample12 = `curl --request PATCH \ + +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/connections/CONNECTION-ID' \ --header 'content-type: application/json' \ - --data '{ "options": { "client_id": "...", "client_secret": "...", "authParams": { "custom_param": "custom.param.value" }, "scripts": { "fetchUserProfile": "..." }, "authorizationURL": "https://public-auth.example.com/oauth2/authorize", "tokenURL": "https://auth.example.com/oauth2/token", "scope": "auth" }, "enabled_clients": [ "..." ] }'`; -export const codeExample13 = `var client = new RestClient("https://{yourDomain}/api/v2/connections/CONNECTION-ID"); + --data '{ "options": { "client_id": "...", "client_secret": "...", "authParams": { "custom_param": "custom.param.value" }, "scripts": { "fetchUserProfile": "..." }, "authorizationURL": "https://public-auth.example.com/oauth2/authorize", "tokenURL": "https://auth.example.com/oauth2/token", "scope": "auth" }, "enabled_clients": [ "..." ] }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/connections/CONNECTION-ID"); var request = new RestRequest(Method.PATCH); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{ \"options\": { \"client_id\": \"...\", \"client_secret\": \"...\", \"authParams\": { \"custom_param\": \"custom.param.value\" }, \"scripts\": { \"fetchUserProfile\": \"...\" }, \"authorizationURL\": \"https://public-auth.example.com/oauth2/authorize\", \"tokenURL\": \"https://auth.example.com/oauth2/token\", \"scope\": \"auth\" }, \"enabled_clients\": [ \"...\" ] }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample14 = `package main +request.AddParameter("application/json", "{ "options": { "client_id": "...", "client_secret": "...", "authParams": { "custom_param": "custom.param.value" }, "scripts": { "fetchUserProfile": "..." }, "authorizationURL": "https://public-auth.example.com/oauth2/authorize", "tokenURL": "https://auth.example.com/oauth2/token", "scope": "auth" }, "enabled_clients": [ "..." ] }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -360,7 +366,7 @@ func main() { url := "https://{yourDomain}/api/v2/connections/CONNECTION-ID" - payload := strings.NewReader("{ \"options\": { \"client_id\": \"...\", \"client_secret\": \"...\", \"authParams\": { \"custom_param\": \"custom.param.value\" }, \"scripts\": { \"fetchUserProfile\": \"...\" }, \"authorizationURL\": \"https://public-auth.example.com/oauth2/authorize\", \"tokenURL\": \"https://auth.example.com/oauth2/token\", \"scope\": \"auth\" }, \"enabled_clients\": [ \"...\" ] }") + payload := strings.NewReader("{ "options": { "client_id": "...", "client_secret": "...", "authParams": { "custom_param": "custom.param.value" }, "scripts": { "fetchUserProfile": "..." }, "authorizationURL": "https://public-auth.example.com/oauth2/authorize", "tokenURL": "https://auth.example.com/oauth2/token", "scope": "auth" }, "enabled_clients": [ "..." ] }") req, _ := http.NewRequest("PATCH", url, payload) @@ -374,12 +380,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample15 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/connections/CONNECTION-ID") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/connections/CONNECTION-ID") .header("content-type", "application/json") - .body("{ \"options\": { \"client_id\": \"...\", \"client_secret\": \"...\", \"authParams\": { \"custom_param\": \"custom.param.value\" }, \"scripts\": { \"fetchUserProfile\": \"...\" }, \"authorizationURL\": \"https://public-auth.example.com/oauth2/authorize\", \"tokenURL\": \"https://auth.example.com/oauth2/token\", \"scope\": \"auth\" }, \"enabled_clients\": [ \"...\" ] }") - .asString();`; -export const codeExample16 = `var axios = require("axios").default; + .body("{ "options": { "client_id": "...", "client_secret": "...", "authParams": { "custom_param": "custom.param.value" }, "scripts": { "fetchUserProfile": "..." }, "authorizationURL": "https://public-auth.example.com/oauth2/authorize", "tokenURL": "https://auth.example.com/oauth2/token", "scope": "auth" }, "enabled_clients": [ "..." ] }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -403,8 +413,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample17 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json" }; NSDictionary *parameters = @{ @"options": @{ @"client_id": @"...", @"client_secret": @"...", @"authParams": @{ @"custom_param": @"custom.param.value" }, @"scripts": @{ @"fetchUserProfile": @"..." }, @"authorizationURL": @"https://public-auth.example.com/oauth2/authorize", @"tokenURL": @"https://auth.example.com/oauth2/token", @"scope": @"auth" }, @@ -429,8 +441,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample18 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/connections/CONNECTION-ID", @@ -440,7 +454,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{ \"options\": { \"client_id\": \"...\", \"client_secret\": \"...\", \"authParams\": { \"custom_param\": \"custom.param.value\" }, \"scripts\": { \"fetchUserProfile\": \"...\" }, \"authorizationURL\": \"https://public-auth.example.com/oauth2/authorize\", \"tokenURL\": \"https://auth.example.com/oauth2/token\", \"scope\": \"auth\" }, \"enabled_clients\": [ \"...\" ] }", + CURLOPT_POSTFIELDS => "{ "options": { "client_id": "...", "client_secret": "...", "authParams": { "custom_param": "custom.param.value" }, "scripts": { "fetchUserProfile": "..." }, "authorizationURL": "https://public-auth.example.com/oauth2/authorize", "tokenURL": "https://auth.example.com/oauth2/token", "scope": "auth" }, "enabled_clients": [ "..." ] }", CURLOPT_HTTPHEADER => [ "content-type: application/json" ], @@ -455,12 +469,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample19 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"options\": { \"client_id\": \"...\", \"client_secret\": \"...\", \"authParams\": { \"custom_param\": \"custom.param.value\" }, \"scripts\": { \"fetchUserProfile\": \"...\" }, \"authorizationURL\": \"https://public-auth.example.com/oauth2/authorize\", \"tokenURL\": \"https://auth.example.com/oauth2/token\", \"scope\": \"auth\" }, \"enabled_clients\": [ \"...\" ] }" +payload = "{ "options": { "client_id": "...", "client_secret": "...", "authParams": { "custom_param": "custom.param.value" }, "scripts": { "fetchUserProfile": "..." }, "authorizationURL": "https://public-auth.example.com/oauth2/authorize", "tokenURL": "https://auth.example.com/oauth2/token", "scope": "auth" }, "enabled_clients": [ "..." ] }" headers = { 'content-type': "application/json" } @@ -469,8 +485,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/connections/CONNECTION-ID", payload, res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample20 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -482,11 +500,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Patch.new(url) request["content-type"] = 'application/json' -request.body = "{ \"options\": { \"client_id\": \"...\", \"client_secret\": \"...\", \"authParams\": { \"custom_param\": \"custom.param.value\" }, \"scripts\": { \"fetchUserProfile\": \"...\" }, \"authorizationURL\": \"https://public-auth.example.com/oauth2/authorize\", \"tokenURL\": \"https://auth.example.com/oauth2/token\", \"scope\": \"auth\" }, \"enabled_clients\": [ \"...\" ] }" +request.body = "{ "options": { "client_id": "...", "client_secret": "...", "authParams": { "custom_param": "custom.param.value" }, "scripts": { "fetchUserProfile": "..." }, "authorizationURL": "https://public-auth.example.com/oauth2/authorize", "tokenURL": "https://auth.example.com/oauth2/token", "scope": "auth" }, "enabled_clients": [ "..." ] }" response = http.request(request) -puts response.read_body`; -export const codeExample21 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/json"] let parameters = [ @@ -521,20 +541,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ### Pass dynamic parameters @@ -544,16 +553,22 @@ Using the same example above, let's assume that you want to pass the `custom_par In this case, you can use one of the existing addition parameters accepted by the `/authorize` endpoint, such as `access_type`, and map that to the `custom_param` parameter: -export const codeExample22 = `curl --request PATCH \ + +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/connections/CONNECTION-ID' \ --header 'content-type: application/json' \ - --data '{ "options": { "client_id": "...", "client_secret": "...", "authParamsMap": { "custom_param": "access_type" }, "scripts": { "fetchUserProfile": "..." }, "authorizationURL": "https://auth.example.com/oauth2/authorize", "tokenURL": "https://auth.example.com/oauth2/token", "scope": "auth" }, "enabled_clients": [ "..." ] }'`; -export const codeExample23 = `var client = new RestClient("https://{yourDomain}/api/v2/connections/CONNECTION-ID"); + --data '{ "options": { "client_id": "...", "client_secret": "...", "authParamsMap": { "custom_param": "access_type" }, "scripts": { "fetchUserProfile": "..." }, "authorizationURL": "https://auth.example.com/oauth2/authorize", "tokenURL": "https://auth.example.com/oauth2/token", "scope": "auth" }, "enabled_clients": [ "..." ] }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/connections/CONNECTION-ID"); var request = new RestRequest(Method.PATCH); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{ \"options\": { \"client_id\": \"...\", \"client_secret\": \"...\", \"authParamsMap\": { \"custom_param\": \"access_type\" }, \"scripts\": { \"fetchUserProfile\": \"...\" }, \"authorizationURL\": \"https://auth.example.com/oauth2/authorize\", \"tokenURL\": \"https://auth.example.com/oauth2/token\", \"scope\": \"auth\" }, \"enabled_clients\": [ \"...\" ] }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample24 = `package main +request.AddParameter("application/json", "{ "options": { "client_id": "...", "client_secret": "...", "authParamsMap": { "custom_param": "access_type" }, "scripts": { "fetchUserProfile": "..." }, "authorizationURL": "https://auth.example.com/oauth2/authorize", "tokenURL": "https://auth.example.com/oauth2/token", "scope": "auth" }, "enabled_clients": [ "..." ] }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -566,7 +581,7 @@ func main() { url := "https://{yourDomain}/api/v2/connections/CONNECTION-ID" - payload := strings.NewReader("{ \"options\": { \"client_id\": \"...\", \"client_secret\": \"...\", \"authParamsMap\": { \"custom_param\": \"access_type\" }, \"scripts\": { \"fetchUserProfile\": \"...\" }, \"authorizationURL\": \"https://auth.example.com/oauth2/authorize\", \"tokenURL\": \"https://auth.example.com/oauth2/token\", \"scope\": \"auth\" }, \"enabled_clients\": [ \"...\" ] }") + payload := strings.NewReader("{ "options": { "client_id": "...", "client_secret": "...", "authParamsMap": { "custom_param": "access_type" }, "scripts": { "fetchUserProfile": "..." }, "authorizationURL": "https://auth.example.com/oauth2/authorize", "tokenURL": "https://auth.example.com/oauth2/token", "scope": "auth" }, "enabled_clients": [ "..." ] }") req, _ := http.NewRequest("PATCH", url, payload) @@ -580,12 +595,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample25 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/connections/CONNECTION-ID") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/connections/CONNECTION-ID") .header("content-type", "application/json") - .body("{ \"options\": { \"client_id\": \"...\", \"client_secret\": \"...\", \"authParamsMap\": { \"custom_param\": \"access_type\" }, \"scripts\": { \"fetchUserProfile\": \"...\" }, \"authorizationURL\": \"https://auth.example.com/oauth2/authorize\", \"tokenURL\": \"https://auth.example.com/oauth2/token\", \"scope\": \"auth\" }, \"enabled_clients\": [ \"...\" ] }") - .asString();`; -export const codeExample26 = `var axios = require("axios").default; + .body("{ "options": { "client_id": "...", "client_secret": "...", "authParamsMap": { "custom_param": "access_type" }, "scripts": { "fetchUserProfile": "..." }, "authorizationURL": "https://auth.example.com/oauth2/authorize", "tokenURL": "https://auth.example.com/oauth2/token", "scope": "auth" }, "enabled_clients": [ "..." ] }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -609,8 +628,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample27 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json" }; NSDictionary *parameters = @{ @"options": @{ @"client_id": @"...", @"client_secret": @"...", @"authParamsMap": @{ @"custom_param": @"access_type" }, @"scripts": @{ @"fetchUserProfile": @"..." }, @"authorizationURL": @"https://auth.example.com/oauth2/authorize", @"tokenURL": @"https://auth.example.com/oauth2/token", @"scope": @"auth" }, @@ -635,8 +656,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample28 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/connections/CONNECTION-ID", @@ -646,7 +669,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{ \"options\": { \"client_id\": \"...\", \"client_secret\": \"...\", \"authParamsMap\": { \"custom_param\": \"access_type\" }, \"scripts\": { \"fetchUserProfile\": \"...\" }, \"authorizationURL\": \"https://auth.example.com/oauth2/authorize\", \"tokenURL\": \"https://auth.example.com/oauth2/token\", \"scope\": \"auth\" }, \"enabled_clients\": [ \"...\" ] }", + CURLOPT_POSTFIELDS => "{ "options": { "client_id": "...", "client_secret": "...", "authParamsMap": { "custom_param": "access_type" }, "scripts": { "fetchUserProfile": "..." }, "authorizationURL": "https://auth.example.com/oauth2/authorize", "tokenURL": "https://auth.example.com/oauth2/token", "scope": "auth" }, "enabled_clients": [ "..." ] }", CURLOPT_HTTPHEADER => [ "content-type: application/json" ], @@ -661,12 +684,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample29 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"options\": { \"client_id\": \"...\", \"client_secret\": \"...\", \"authParamsMap\": { \"custom_param\": \"access_type\" }, \"scripts\": { \"fetchUserProfile\": \"...\" }, \"authorizationURL\": \"https://auth.example.com/oauth2/authorize\", \"tokenURL\": \"https://auth.example.com/oauth2/token\", \"scope\": \"auth\" }, \"enabled_clients\": [ \"...\" ] }" +payload = "{ "options": { "client_id": "...", "client_secret": "...", "authParamsMap": { "custom_param": "access_type" }, "scripts": { "fetchUserProfile": "..." }, "authorizationURL": "https://auth.example.com/oauth2/authorize", "tokenURL": "https://auth.example.com/oauth2/token", "scope": "auth" }, "enabled_clients": [ "..." ] }" headers = { 'content-type': "application/json" } @@ -675,8 +700,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/connections/CONNECTION-ID", payload, res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample30 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -688,11 +715,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Patch.new(url) request["content-type"] = 'application/json' -request.body = "{ \"options\": { \"client_id\": \"...\", \"client_secret\": \"...\", \"authParamsMap\": { \"custom_param\": \"access_type\" }, \"scripts\": { \"fetchUserProfile\": \"...\" }, \"authorizationURL\": \"https://auth.example.com/oauth2/authorize\", \"tokenURL\": \"https://auth.example.com/oauth2/token\", \"scope\": \"auth\" }, \"enabled_clients\": [ \"...\" ] }" +request.body = "{ "options": { "client_id": "...", "client_secret": "...", "authParamsMap": { "custom_param": "access_type" }, "scripts": { "fetchUserProfile": "..." }, "authorizationURL": "https://auth.example.com/oauth2/authorize", "tokenURL": "https://auth.example.com/oauth2/token", "scope": "auth" }, "enabled_clients": [ "..." ] }" response = http.request(request) -puts response.read_body`; -export const codeExample31 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/json"] let parameters = [ @@ -727,20 +756,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + Now when calling the `/authorize` endpoint, you can pass the access type in the `access_type` parameter, and that value will in turn be passed along to the authorization endpoint in the `custom_param` parameter. @@ -755,11 +773,6 @@ In some instances, you will need to pass extra headers to the Management API. -export const codeExample1 = `curl --request PATCH \ + +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/clients/{yourClientId}' \ --header 'authorization: Bearer API2_ACCESS_TOKEN' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{"initiate_login_uri": ""}'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/clients/{yourClientId}"); + --data '{"initiate_login_uri": ""}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/clients/{yourClientId}"); var request = new RestRequest(Method.PATCH); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer API2_ACCESS_TOKEN"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{\"initiate_login_uri\": \"\"}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{"initiate_login_uri": ""}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -44,7 +52,7 @@ func main() { url := "https://{yourDomain}/api/v2/clients/{yourClientId}" - payload := strings.NewReader("{\"initiate_login_uri\": \"\"}") + payload := strings.NewReader("{"initiate_login_uri": ""}") req, _ := http.NewRequest("PATCH", url, payload) @@ -60,14 +68,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/clients/{yourClientId}") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/clients/{yourClientId}") .header("content-type", "application/json") .header("authorization", "Bearer API2_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{\"initiate_login_uri\": \"\"}") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{"initiate_login_uri": ""}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -84,8 +96,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer API2_ACCESS_TOKEN", @@ -111,8 +125,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/clients/{yourClientId}", @@ -122,7 +138,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{\"initiate_login_uri\": \"\"}", + CURLOPT_POSTFIELDS => "{"initiate_login_uri": ""}", CURLOPT_HTTPHEADER => [ "authorization: Bearer API2_ACCESS_TOKEN", "cache-control: no-cache", @@ -139,12 +155,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"initiate_login_uri\": \"\"}" +payload = "{"initiate_login_uri": ""}" headers = { 'content-type': "application/json", @@ -157,8 +175,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/clients/{yourClientId}", payload, he res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -172,11 +192,13 @@ request = Net::HTTP::Patch.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer API2_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{\"initiate_login_uri\": \"\"}" +request.body = "{"initiate_login_uri": ""}" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -204,37 +226,32 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + -export const codeExample11 = `curl --request PATCH \ + +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/tenants/settings' \ --header 'authorization: Bearer API2_ACCESS_TOKEN' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{"default_redirection_uri": ""}'`; -export const codeExample12 = `var client = new RestClient("https://{yourDomain}/api/v2/tenants/settings"); + --data '{"default_redirection_uri": ""}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/tenants/settings"); var request = new RestRequest(Method.PATCH); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer API2_ACCESS_TOKEN"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{\"default_redirection_uri\": \"\"}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample13 = `package main +request.AddParameter("application/json", "{"default_redirection_uri": ""}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -247,7 +264,7 @@ func main() { url := "https://{yourDomain}/api/v2/tenants/settings" - payload := strings.NewReader("{\"default_redirection_uri\": \"\"}") + payload := strings.NewReader("{"default_redirection_uri": ""}") req, _ := http.NewRequest("PATCH", url, payload) @@ -263,14 +280,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample14 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/tenants/settings") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/tenants/settings") .header("content-type", "application/json") .header("authorization", "Bearer API2_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{\"default_redirection_uri\": \"\"}") - .asString();`; -export const codeExample15 = `var axios = require("axios").default; + .body("{"default_redirection_uri": ""}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -287,8 +308,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample16 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer API2_ACCESS_TOKEN", @@ -314,8 +337,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/tenants/settings", @@ -325,7 +350,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{\"default_redirection_uri\": \"\"}", + CURLOPT_POSTFIELDS => "{"default_redirection_uri": ""}", CURLOPT_HTTPHEADER => [ "authorization: Bearer API2_ACCESS_TOKEN", "cache-control: no-cache", @@ -342,12 +367,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"default_redirection_uri\": \"\"}" +payload = "{"default_redirection_uri": ""}" headers = { 'content-type': "application/json", @@ -360,8 +387,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/tenants/settings", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -375,11 +404,13 @@ request = Net::HTTP::Patch.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer API2_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{\"default_redirection_uri\": \"\"}" +request.body = "{"default_redirection_uri": ""}" response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -407,20 +438,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + @@ -452,18 +472,24 @@ This behavior only happens when you enable the response = Unirest.post("https://{yourDomain}/api/v2/tickets/password-change") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/tickets/password-change") .header("content-type", "application/json") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") - .body("{ \"user_id\": \"A_USER_ID\", \"client_id\": \"A_CLIENT_ID\" }") - .asString();`; -export const codeExample25 = `var axios = require("axios").default; + .body("{ "user_id": "A_USER_ID", "client_id": "A_CLIENT_ID" }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -513,8 +543,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample26 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN" }; @@ -540,8 +572,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample27 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/tickets/password-change", @@ -551,7 +585,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{ \"user_id\": \"A_USER_ID\", \"client_id\": \"A_CLIENT_ID\" }", + CURLOPT_POSTFIELDS => "{ "user_id": "A_USER_ID", "client_id": "A_CLIENT_ID" }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "content-type: application/json" @@ -567,12 +601,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample28 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"user_id\": \"A_USER_ID\", \"client_id\": \"A_CLIENT_ID\" }" +payload = "{ "user_id": "A_USER_ID", "client_id": "A_CLIENT_ID" }" headers = { 'content-type': "application/json", @@ -584,8 +620,10 @@ conn.request("POST", "/{yourDomain}/api/v2/tickets/password-change", payload, he res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample29 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -598,11 +636,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' -request.body = "{ \"user_id\": \"A_USER_ID\", \"client_id\": \"A_CLIENT_ID\" }" +request.body = "{ "user_id": "A_USER_ID", "client_id": "A_CLIENT_ID" }" response = http.request(request) -puts response.read_body`; -export const codeExample30 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -632,20 +672,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ### Complete email verification flow diff --git a/main/docs/authenticate/login/logout/log-users-out-of-auth0.mdx b/main/docs/authenticate/login/logout/log-users-out-of-auth0.mdx index 737e2f887..6e88eec9a 100644 --- a/main/docs/authenticate/login/logout/log-users-out-of-auth0.mdx +++ b/main/docs/authenticate/login/logout/log-users-out-of-auth0.mdx @@ -10,6 +10,8 @@ title: Log Users Out of Auth0 with OIDC Endpoint --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + Auth0 implements OpenID Connect’s [RP-Initiated Logout 1.0](https://openid.net/specs/openid-connect-rpinitiated-1_0.html) for end-user logout. This standard is part of the OpenID Connect collection of [final specifications](https://openid.net/developers/specs/). ## How it works @@ -145,17 +147,18 @@ The ID token contains the registered claims issuer (`iss`), - - + --data 'post_logout_redirect_uri={yourCallbackUrl}' +``` + #### logout_hint parameter @@ -173,16 +176,10 @@ You must use the session ID (`sid`) associated with the ID token issued by Auth0 {/* codeblockOld.header.login.logInButton codeblockOld.header.login.configureSnippet */} - export const codeExample3 = `https://{yourDomain}/oidc/logout?{clientId}={yourClientId}&logout_hint={sessionId}`; - - - - - #### post_logout_redirect_uri parameter The value of the `post_logout_redirect_uri` parameter must be a valid, encoded URL that has been registered in the list of **Allowed Logout URLs** in your: @@ -196,11 +193,6 @@ export const codeExample4 = `https://{yourDomain}/oidc/logout?post_logout_redire - - - - - ##### Update application Allowed Logout URLs You can register a URL with your application’s list of **Allowed Logout URLs** in the Auth0 Dashboard or with the Auth0 Management API. diff --git a/main/docs/authenticate/login/oidc-conformant-authentication/oidc-adoption-auth-code-flow.mdx b/main/docs/authenticate/login/oidc-conformant-authentication/oidc-adoption-auth-code-flow.mdx index aee62d444..39f4ce484 100644 --- a/main/docs/authenticate/login/oidc-conformant-authentication/oidc-adoption-auth-code-flow.mdx +++ b/main/docs/authenticate/login/oidc-conformant-authentication/oidc-adoption-auth-code-flow.mdx @@ -12,6 +12,8 @@ title: Authorization Code Flow with OIDC --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + The [Authorization Code Flow](/docs/get-started/authentication-and-authorization-flow/authorization-code-flow) is used by server-side applications that are capable of securely storing secrets, or by native applications through [Authorization Code Flow with PKCE](/docs/get-started/authentication-and-authorization-flow/authorization-code-flow-with-pkce). The OIDC-conformant pipeline affects the Authorization Code Flow in the following areas: @@ -37,11 +39,6 @@ GET /authorize?     &device=my-device-name ``` - - - - - The `device` parameter is only needed if requesting a refresh token by passing the `offline_access` scope. To learn more, read, [Refresh Tokens](/docs/secure/tokens/refresh-tokens). ### OIDC-conformant @@ -56,11 +53,6 @@ GET /authorize?     &audience=https://api.example.com ``` - - - - - * `favorite_color` is no longer a valid scope value. * The `device` parameter is removed. * The `audience` parameter is optional. @@ -76,29 +68,30 @@ Location: https://app.example.com/callback?     &state=af0ifjsldkj ``` - - - - - ## Code exchange request - Authorization Code flow An authorization code can be exchanged in the same way in both pipelines: -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=authorization_code \ --data 'client_id={yourClientId}' \ --data client_secret=YOUR_CLIENT_SECRET \ --data code=YOUR_AUTHORIZATION_CODE \ - --data 'redirect_uri={https://yourApp/callback}'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data 'redirect_uri={https://yourApp/callback}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=authorization_code&client_id={yourClientId}&client_secret=YOUR_CLIENT_SECRET&code=YOUR_AUTHORIZATION_CODE&redirect_uri={https://yourApp/callback}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -125,12 +118,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=authorization_code&client_id={yourClientId}&client_secret=YOUR_CLIENT_SECRET&code=YOUR_AUTHORIZATION_CODE&redirect_uri={https://yourApp/callback}") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -149,8 +146,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -177,8 +176,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -203,8 +204,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -217,8 +220,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -233,8 +238,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=authorization_code&client_id={yourClientId}&client_secret=YOUR_CLIENT_SECRET&code=YOUR_AUTHORIZATION_CODE&redirect_uri={https://yourApp/callback}" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -261,39 +268,34 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ## Code exchange request - Authorization Code flow with PKCE An authorization code can be exchanged in the same way in both pipelines: -export const codeExample11 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=authorization_code \ --data 'client_id={yourClientId}' \ --data code_verifier=YOUR_GENERATED_CODE_VERIFIER \ --data code=YOUR_AUTHORIZATION_CODE \ - --data 'redirect_uri={https://yourApp/callback}'`; -export const codeExample12 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data 'redirect_uri={https://yourApp/callback}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=authorization_code&client_id={yourClientId}&code_verifier=YOUR_GENERATED_CODE_VERIFIER&code=YOUR_AUTHORIZATION_CODE&redirect_uri={https://yourApp/callback}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample13 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -320,12 +322,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample14 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=authorization_code&client_id={yourClientId}&code_verifier=YOUR_GENERATED_CODE_VERIFIER&code=YOUR_AUTHORIZATION_CODE&redirect_uri={https://yourApp/callback}") - .asString();`; -export const codeExample15 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -344,8 +350,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample16 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -372,8 +380,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -398,8 +408,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -412,8 +424,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -428,8 +442,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=authorization_code&client_id={yourClientId}&code_verifier=YOUR_GENERATED_CODE_VERIFIER&code=YOUR_AUTHORIZATION_CODE&redirect_uri={https://yourApp/callback}" response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -456,20 +472,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ## Code exchange response @@ -489,11 +494,6 @@ Pragma: no-cache } ``` - - - - - * The returned Access Token is only valid for calling the [`/userinfo`](https://auth0.com/docs/api/authentication#get-user-info) endpoint. * A refresh token will be returned only if a `device` parameter was passed and the `offline_access` scope was requested. @@ -513,11 +513,6 @@ Pragma: no-cache } ``` - - - - - * The returned access token is valid for optionally calling the API specified in the `audience` parameter and the [`/userinfo`](https://auth0.com/docs/api/authentication#get-user-info) endpoint (provided that the API uses `RS256` as the [signing algorithm](/docs/get-started/applications/signing-algorithms) and `openid` is used as a `scope` parameter). If you are not implementing your own Resource Server (API), then you can use `https://{$account.namespace}/userinfo` as the `audience` parameter, which will return an opaque Access Token. * A refresh token will be returned only if the `offline_access` scope was granted. @@ -538,11 +533,6 @@ export const codeExample21 = `{ - - - - - ### OIDC-conformant export const codeExample22 = `{ @@ -558,11 +548,6 @@ export const codeExample22 = `{ - - - - - The `favorite_color` claim must be added through an Auth0 Action. To learn more, read [Create Custom Claims](/docs/secure/tokens/json-web-tokens/create-custom-claims). ## Access token structure (optional) @@ -573,11 +558,6 @@ The `favorite_color` claim must be added through an Auth0 Action. To learn more, SlAV32hkKG ``` - - - - - The returned access token is opaque and only valid for calling the [`/userinfo`](https://auth0.com/docs/api/authentication#get-user-info) endpoint. ### OIDC-conformant @@ -597,11 +577,6 @@ export const codeExample23 = `{ - - - - - The returned access token is valid for optionally calling the API specified in the `audience` parameter and the [`/userinfo`](https://auth0.com/docs/api/authentication#get-user-info) endpoint (provided that the API uses `RS256` as the signing algorithm and `openid` is used as a `scope` parameter). If you are not implementing your own resource server (API), then you can use `https://{$account.namespace}/userinfo` as the `audience` parameter, which will return an opaque access token. diff --git a/main/docs/authenticate/passwordless/authentication-methods/use-sms-gateway-passwordless.mdx b/main/docs/authenticate/passwordless/authentication-methods/use-sms-gateway-passwordless.mdx index cda64c953..a1a7c8065 100644 --- a/main/docs/authenticate/passwordless/authentication-methods/use-sms-gateway-passwordless.mdx +++ b/main/docs/authenticate/passwordless/authentication-methods/use-sms-gateway-passwordless.mdx @@ -8,6 +8,9 @@ title: Set Up Custom SMS Gateway for Passwordless Connections 'twitter:description': Learn how to set up a custom SMS gateway for Passwordless connections. 'twitter:title': Set Up Custom SMS Gateway for Passwordless Connections --- + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + This guide will show you how to use a custom SMS gateway to send out your one-time-use codes. By default, [Passwordless SMS connections](/docs/authenticate/passwordless/authentication-methods/sms-otp) use [Twilio](https://www.twilio.com) to send out one-time use codes. However, if you have a custom SMS gateway, you can modify your connection to use that instead. @@ -23,7 +26,7 @@ Auth0 does not support basic SMS authentication. 3. Use the [GET Connections](https://auth0.com/docs/api/management/v2#!/Connections/get_connections) endpoint to retrieve information about the connections associated with your tenant. More specifically, you need to get the ID for your Passwordless SMS connection so that you can use it in a later API call that updates the connection itself. Be sure to replace `ACCESS_TOKEN` with the token you obtained in step 1 before making the following call to the Management API: - + ```bash cURL lines curl --request GET \ --url https://your-auth0-tenant.com/api/v2/connections \ @@ -190,7 +193,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + The response from the endpoint will be an array of objects. Each object represents one connection affiliated with your tenant. 4. Identify your connection ID. You can find the ID associated with your Passwordless connection by reviewing the array of objects you returned from the [GET Connections endpoint](https://auth0.com/docs/api/management/v2#!/Connections/get_connections) in step 2. diff --git a/main/docs/authenticate/passwordless/implement-login/embedded-login/native.mdx b/main/docs/authenticate/passwordless/implement-login/embedded-login/native.mdx index fae12a1c7..b87ed8860 100644 --- a/main/docs/authenticate/passwordless/implement-login/embedded-login/native.mdx +++ b/main/docs/authenticate/passwordless/implement-login/embedded-login/native.mdx @@ -12,6 +12,8 @@ title: Embedded Passwordless Login in Native Applications --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + To use the Embedded Passwordless APIs in Native applications, make sure you enable the **Passwordless OTP** grant at [Auth0 Dashboard > Applications > Applications](https://manage.auth0.com/#/applications) in your application's settings under **Advanced Settings** > **Grant Types**. Passwordless authentication for Native applications consists of two steps: @@ -23,16 +25,22 @@ Below we list a few code snippets that can be used to call these API endpoints f **Send a one-time-use password via email** -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/passwordless/start' \ --header 'content-type: application/json' \ - --data '{"client_id": "{yourClientId}", "connection": "email", "email": "USER_EMAIL", "send": "code"}'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/passwordless/start"); + --data '{"client_id": "{yourClientId}", "connection": "email", "email": "USER_EMAIL", "send": "code"}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/passwordless/start"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\"client_id\": \"{yourClientId}\", \"connection\": \"email\", \"email\": \"USER_EMAIL\", \"send\": \"code\"}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{"client_id": "{yourClientId}", "connection": "email", "email": "USER_EMAIL", "send": "code"}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -45,7 +53,7 @@ func main() { url := "https://{yourDomain}/passwordless/start" - payload := strings.NewReader("{\"client_id\": \"{yourClientId}\", \"connection\": \"email\", \"email\": \"USER_EMAIL\", \"send\": \"code\"}") + payload := strings.NewReader("{"client_id": "{yourClientId}", "connection": "email", "email": "USER_EMAIL", "send": "code"}") req, _ := http.NewRequest("POST", url, payload) @@ -59,12 +67,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/passwordless/start") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/passwordless/start") .header("content-type", "application/json") - .body("{\"client_id\": \"{yourClientId}\", \"connection\": \"email\", \"email\": \"USER_EMAIL\", \"send\": \"code\"}") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{"client_id": "{yourClientId}", "connection": "email", "email": "USER_EMAIL", "send": "code"}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -82,8 +94,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json" }; NSDictionary *parameters = @{ @"client_id": @"{yourClientId}", @@ -110,8 +124,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/passwordless/start", @@ -121,7 +137,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{\"client_id\": \"{yourClientId}\", \"connection\": \"email\", \"email\": \"USER_EMAIL\", \"send\": \"code\"}", + CURLOPT_POSTFIELDS => "{"client_id": "{yourClientId}", "connection": "email", "email": "USER_EMAIL", "send": "code"}", CURLOPT_HTTPHEADER => [ "content-type: application/json" ], @@ -136,12 +152,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"client_id\": \"{yourClientId}\", \"connection\": \"email\", \"email\": \"USER_EMAIL\", \"send\": \"code\"}" +payload = "{"client_id": "{yourClientId}", "connection": "email", "email": "USER_EMAIL", "send": "code"}" headers = { 'content-type': "application/json" } @@ -150,8 +168,10 @@ conn.request("POST", "/{yourDomain}/passwordless/start", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -163,11 +183,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["content-type"] = 'application/json' -request.body = "{\"client_id\": \"{yourClientId}\", \"connection\": \"email\", \"email\": \"USER_EMAIL\", \"send\": \"code\"}" +request.body = "{"client_id": "{yourClientId}", "connection": "email", "email": "USER_EMAIL", "send": "code"}" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/json"] let parameters = [ @@ -196,33 +218,28 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + **Send a magic link via email** -export const codeExample11 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/passwordless/start' \ --header 'content-type: application/json' \ - --data '{ "client_id": "{yourClientId}", "connection": "email", "email": "USER_EMAIL", "send": "link"}'`; -export const codeExample12 = `var client = new RestClient("https://{yourDomain}/passwordless/start"); + --data '{ "client_id": "{yourClientId}", "connection": "email", "email": "USER_EMAIL", "send": "link"}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/passwordless/start"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{ \"client_id\": \"{yourClientId}\", \"connection\": \"email\", \"email\": \"USER_EMAIL\", \"send\": \"link\"}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample13 = `package main +request.AddParameter("application/json", "{ "client_id": "{yourClientId}", "connection": "email", "email": "USER_EMAIL", "send": "link"}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -235,7 +252,7 @@ func main() { url := "https://{yourDomain}/passwordless/start" - payload := strings.NewReader("{ \"client_id\": \"{yourClientId}\", \"connection\": \"email\", \"email\": \"USER_EMAIL\", \"send\": \"link\"}") + payload := strings.NewReader("{ "client_id": "{yourClientId}", "connection": "email", "email": "USER_EMAIL", "send": "link"}") req, _ := http.NewRequest("POST", url, payload) @@ -249,12 +266,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample14 = `HttpResponse response = Unirest.post("https://{yourDomain}/passwordless/start") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/passwordless/start") .header("content-type", "application/json") - .body("{ \"client_id\": \"{yourClientId}\", \"connection\": \"email\", \"email\": \"USER_EMAIL\", \"send\": \"link\"}") - .asString();`; -export const codeExample15 = `var axios = require("axios").default; + .body("{ "client_id": "{yourClientId}", "connection": "email", "email": "USER_EMAIL", "send": "link"}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -272,8 +293,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample16 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json" }; NSDictionary *parameters = @{ @"client_id": @"{yourClientId}", @@ -300,8 +323,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/passwordless/start", @@ -311,7 +336,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{ \"client_id\": \"{yourClientId}\", \"connection\": \"email\", \"email\": \"USER_EMAIL\", \"send\": \"link\"}", + CURLOPT_POSTFIELDS => "{ "client_id": "{yourClientId}", "connection": "email", "email": "USER_EMAIL", "send": "link"}", CURLOPT_HTTPHEADER => [ "content-type: application/json" ], @@ -326,12 +351,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"client_id\": \"{yourClientId}\", \"connection\": \"email\", \"email\": \"USER_EMAIL\", \"send\": \"link\"}" +payload = "{ "client_id": "{yourClientId}", "connection": "email", "email": "USER_EMAIL", "send": "link"}" headers = { 'content-type': "application/json" } @@ -340,8 +367,10 @@ conn.request("POST", "/{yourDomain}/passwordless/start", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -353,11 +382,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["content-type"] = 'application/json' -request.body = "{ \"client_id\": \"{yourClientId}\", \"connection\": \"email\", \"email\": \"USER_EMAIL\", \"send\": \"link\"}" +request.body = "{ "client_id": "{yourClientId}", "connection": "email", "email": "USER_EMAIL", "send": "link"}" response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/json"] let parameters = [ @@ -386,33 +417,28 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + **Send a one-time-use password via SMS** -export const codeExample21 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/passwordless/start' \ --header 'content-type: application/json' \ - --data '{ "client_id": "{yourClientId}", "connection": "sms", "phone_number": "USER_PHONE_NUMBER", "send": "code"}'`; -export const codeExample22 = `var client = new RestClient("https://{yourDomain}/passwordless/start"); + --data '{ "client_id": "{yourClientId}", "connection": "sms", "phone_number": "USER_PHONE_NUMBER", "send": "code"}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/passwordless/start"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{ \"client_id\": \"{yourClientId}\", \"connection\": \"sms\", \"phone_number\": \"USER_PHONE_NUMBER\", \"send\": \"code\"}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample23 = `package main +request.AddParameter("application/json", "{ "client_id": "{yourClientId}", "connection": "sms", "phone_number": "USER_PHONE_NUMBER", "send": "code"}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -425,7 +451,7 @@ func main() { url := "https://{yourDomain}/passwordless/start" - payload := strings.NewReader("{ \"client_id\": \"{yourClientId}\", \"connection\": \"sms\", \"phone_number\": \"USER_PHONE_NUMBER\", \"send\": \"code\"}") + payload := strings.NewReader("{ "client_id": "{yourClientId}", "connection": "sms", "phone_number": "USER_PHONE_NUMBER", "send": "code"}") req, _ := http.NewRequest("POST", url, payload) @@ -439,12 +465,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample24 = `HttpResponse response = Unirest.post("https://{yourDomain}/passwordless/start") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/passwordless/start") .header("content-type", "application/json") - .body("{ \"client_id\": \"{yourClientId}\", \"connection\": \"sms\", \"phone_number\": \"USER_PHONE_NUMBER\", \"send\": \"code\"}") - .asString();`; -export const codeExample25 = `var axios = require("axios").default; + .body("{ "client_id": "{yourClientId}", "connection": "sms", "phone_number": "USER_PHONE_NUMBER", "send": "code"}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -462,8 +492,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample26 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json" }; NSDictionary *parameters = @{ @"client_id": @"{yourClientId}", @@ -490,8 +522,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample27 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/passwordless/start", @@ -501,7 +535,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{ \"client_id\": \"{yourClientId}\", \"connection\": \"sms\", \"phone_number\": \"USER_PHONE_NUMBER\", \"send\": \"code\"}", + CURLOPT_POSTFIELDS => "{ "client_id": "{yourClientId}", "connection": "sms", "phone_number": "USER_PHONE_NUMBER", "send": "code"}", CURLOPT_HTTPHEADER => [ "content-type: application/json" ], @@ -516,12 +550,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample28 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"client_id\": \"{yourClientId}\", \"connection\": \"sms\", \"phone_number\": \"USER_PHONE_NUMBER\", \"send\": \"code\"}" +payload = "{ "client_id": "{yourClientId}", "connection": "sms", "phone_number": "USER_PHONE_NUMBER", "send": "code"}" headers = { 'content-type': "application/json" } @@ -530,8 +566,10 @@ conn.request("POST", "/{yourDomain}/passwordless/start", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample29 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -543,11 +581,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["content-type"] = 'application/json' -request.body = "{ \"client_id\": \"{yourClientId}\", \"connection\": \"sms\", \"phone_number\": \"USER_PHONE_NUMBER\", \"send\": \"code\"}" +request.body = "{ "client_id": "{yourClientId}", "connection": "sms", "phone_number": "USER_PHONE_NUMBER", "send": "code"}" response = http.request(request) -puts response.read_body`; -export const codeExample30 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/json"] let parameters = [ @@ -576,33 +616,28 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + **Authenticate an SMS user** -export const codeExample31 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/json' \ - --data '{ "grant_type": "http://auth0.com/oauth/grant-type/passwordless/otp", "client_id": "{yourClientId}", "username": "USER_PHONE_NUMBER", "otp": "code", "realm": "sms", "audience": "your-api-audience", "scope": "openid profile email"}'`; -export const codeExample32 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data '{ "grant_type": "http://auth0.com/oauth/grant-type/passwordless/otp", "client_id": "{yourClientId}", "username": "USER_PHONE_NUMBER", "otp": "code", "realm": "sms", "audience": "your-api-audience", "scope": "openid profile email"}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{ \"grant_type\": \"http://auth0.com/oauth/grant-type/passwordless/otp\", \"client_id\": \"{yourClientId}\", \"username\": \"USER_PHONE_NUMBER\", \"otp\": \"code\", \"realm\": \"sms\", \"audience\": \"your-api-audience\", \"scope\": \"openid profile email\"}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample33 = `package main +request.AddParameter("application/json", "{ "grant_type": "http://auth0.com/oauth/grant-type/passwordless/otp", "client_id": "{yourClientId}", "username": "USER_PHONE_NUMBER", "otp": "code", "realm": "sms", "audience": "your-api-audience", "scope": "openid profile email"}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -615,7 +650,7 @@ func main() { url := "https://{yourDomain}/oauth/token" - payload := strings.NewReader("{ \"grant_type\": \"http://auth0.com/oauth/grant-type/passwordless/otp\", \"client_id\": \"{yourClientId}\", \"username\": \"USER_PHONE_NUMBER\", \"otp\": \"code\", \"realm\": \"sms\", \"audience\": \"your-api-audience\", \"scope\": \"openid profile email\"}") + payload := strings.NewReader("{ "grant_type": "http://auth0.com/oauth/grant-type/passwordless/otp", "client_id": "{yourClientId}", "username": "USER_PHONE_NUMBER", "otp": "code", "realm": "sms", "audience": "your-api-audience", "scope": "openid profile email"}") req, _ := http.NewRequest("POST", url, payload) @@ -629,8 +664,10 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample34 = `var axios = require("axios").default; +} +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -651,8 +688,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample35 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json" }; NSDictionary *parameters = @{ @"grant_type": @"http://auth0.com/oauth/grant-type/passwordless/otp", @@ -682,8 +721,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample36 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -693,7 +734,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{ \"grant_type\": \"http://auth0.com/oauth/grant-type/passwordless/otp\", \"client_id\": \"{yourClientId}\", \"username\": \"USER_PHONE_NUMBER\", \"otp\": \"code\", \"realm\": \"sms\", \"audience\": \"your-api-audience\", \"scope\": \"openid profile email\"}", + CURLOPT_POSTFIELDS => "{ "grant_type": "http://auth0.com/oauth/grant-type/passwordless/otp", "client_id": "{yourClientId}", "username": "USER_PHONE_NUMBER", "otp": "code", "realm": "sms", "audience": "your-api-audience", "scope": "openid profile email"}", CURLOPT_HTTPHEADER => [ "content-type: application/json" ], @@ -708,12 +749,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample37 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"grant_type\": \"http://auth0.com/oauth/grant-type/passwordless/otp\", \"client_id\": \"{yourClientId}\", \"username\": \"USER_PHONE_NUMBER\", \"otp\": \"code\", \"realm\": \"sms\", \"audience\": \"your-api-audience\", \"scope\": \"openid profile email\"}" +payload = "{ "grant_type": "http://auth0.com/oauth/grant-type/passwordless/otp", "client_id": "{yourClientId}", "username": "USER_PHONE_NUMBER", "otp": "code", "realm": "sms", "audience": "your-api-audience", "scope": "openid profile email"}" headers = { 'content-type': "application/json" } @@ -722,8 +765,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample38 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -735,11 +780,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["content-type"] = 'application/json' -request.body = "{ \"grant_type\": \"http://auth0.com/oauth/grant-type/passwordless/otp\", \"client_id\": \"{yourClientId}\", \"username\": \"USER_PHONE_NUMBER\", \"otp\": \"code\", \"realm\": \"sms\", \"audience\": \"your-api-audience\", \"scope\": \"openid profile email\"}" +request.body = "{ "grant_type": "http://auth0.com/oauth/grant-type/passwordless/otp", "client_id": "{yourClientId}", "username": "USER_PHONE_NUMBER", "otp": "code", "realm": "sms", "audience": "your-api-audience", "scope": "openid profile email"}" response = http.request(request) -puts response.read_body`; -export const codeExample39 = `imimport Foundation +puts response.read_body +``` +```swift Swift +imimport Foundation let headers = ["content-type": "application/json"] let parameters = [ @@ -771,32 +818,28 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - +dataTask.resume() +``` + **Authenticate an Email user** -export const codeExample40 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/json' \ - --data '{"grant_type": "http://auth0.com/oauth/grant-type/passwordless/otp", "client_id": "{yourClientId}", "username": "USER_EMAIL", "otp": "code", "realm": "email", "audience": "your-api-audience", "scope": "openid profile email"}'`; -export const codeExample41 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data '{"grant_type": "http://auth0.com/oauth/grant-type/passwordless/otp", "client_id": "{yourClientId}", "username": "USER_EMAIL", "otp": "code", "realm": "email", "audience": "your-api-audience", "scope": "openid profile email"}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\"grant_type\": \"http://auth0.com/oauth/grant-type/passwordless/otp\", \"client_id\": \"{yourClientId}\", \"username\": \"USER_EMAIL\", \"otp\": \"code\", \"realm\": \"email\", \"audience\": \"your-api-audience\", \"scope\": \"openid profile email\"}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample42 = `package main +request.AddParameter("application/json", "{"grant_type": "http://auth0.com/oauth/grant-type/passwordless/otp", "client_id": "{yourClientId}", "username": "USER_EMAIL", "otp": "code", "realm": "email", "audience": "your-api-audience", "scope": "openid profile email"}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -809,7 +852,7 @@ func main() { url := "https://{yourDomain}/oauth/token" - payload := strings.NewReader("{\"grant_type\": \"http://auth0.com/oauth/grant-type/passwordless/otp\", \"client_id\": \"{yourClientId}\", \"username\": \"USER_EMAIL\", \"otp\": \"code\", \"realm\": \"email\", \"audience\": \"your-api-audience\", \"scope\": \"openid profile email\"}") + payload := strings.NewReader("{"grant_type": "http://auth0.com/oauth/grant-type/passwordless/otp", "client_id": "{yourClientId}", "username": "USER_EMAIL", "otp": "code", "realm": "email", "audience": "your-api-audience", "scope": "openid profile email"}") req, _ := http.NewRequest("POST", url, payload) @@ -823,12 +866,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample43 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/json") - .body("{\"grant_type\": \"http://auth0.com/oauth/grant-type/passwordless/otp\", \"client_id\": \"{yourClientId}\", \"username\": \"USER_EMAIL\", \"otp\": \"code\", \"realm\": \"email\", \"audience\": \"your-api-audience\", \"scope\": \"openid profile email\"}") - .asString();`; -export const codeExample44 = `var axios = require("axios").default; + .body("{"grant_type": "http://auth0.com/oauth/grant-type/passwordless/otp", "client_id": "{yourClientId}", "username": "USER_EMAIL", "otp": "code", "realm": "email", "audience": "your-api-audience", "scope": "openid profile email"}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -849,8 +896,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample45 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json" }; NSDictionary *parameters = @{ @"grant_type": @"http://auth0.com/oauth/grant-type/passwordless/otp", @@ -880,8 +929,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample46 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -891,7 +942,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{\"grant_type\": \"http://auth0.com/oauth/grant-type/passwordless/otp\", \"client_id\": \"{yourClientId}\", \"username\": \"USER_EMAIL\", \"otp\": \"code\", \"realm\": \"email\", \"audience\": \"your-api-audience\", \"scope\": \"openid profile email\"}", + CURLOPT_POSTFIELDS => "{"grant_type": "http://auth0.com/oauth/grant-type/passwordless/otp", "client_id": "{yourClientId}", "username": "USER_EMAIL", "otp": "code", "realm": "email", "audience": "your-api-audience", "scope": "openid profile email"}", CURLOPT_HTTPHEADER => [ "content-type: application/json" ], @@ -906,12 +957,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample47 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"grant_type\": \"http://auth0.com/oauth/grant-type/passwordless/otp\", \"client_id\": \"{yourClientId}\", \"username\": \"USER_EMAIL\", \"otp\": \"code\", \"realm\": \"email\", \"audience\": \"your-api-audience\", \"scope\": \"openid profile email\"}" +payload = "{"grant_type": "http://auth0.com/oauth/grant-type/passwordless/otp", "client_id": "{yourClientId}", "username": "USER_EMAIL", "otp": "code", "realm": "email", "audience": "your-api-audience", "scope": "openid profile email"}" headers = { 'content-type': "application/json" } @@ -920,8 +973,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample48 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -933,11 +988,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["content-type"] = 'application/json' -request.body = "{\"grant_type\": \"http://auth0.com/oauth/grant-type/passwordless/otp\", \"client_id\": \"{yourClientId}\", \"username\": \"USER_EMAIL\", \"otp\": \"code\", \"realm\": \"email\", \"audience\": \"your-api-audience\", \"scope\": \"openid profile email\"}" +request.body = "{"grant_type": "http://auth0.com/oauth/grant-type/passwordless/otp", "client_id": "{yourClientId}", "username": "USER_EMAIL", "otp": "code", "realm": "email", "audience": "your-api-audience", "scope": "openid profile email"}" response = http.request(request) -puts response.read_body`; -export const codeExample49 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/json"] let parameters = [ @@ -969,20 +1026,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + If you prefer, you can use the Android or iOS SDKs, which wrap this APIs in a platform-friendly way: diff --git a/main/docs/authenticate/passwordless/implement-login/embedded-login/webapps.mdx b/main/docs/authenticate/passwordless/implement-login/embedded-login/webapps.mdx index acc2bcabb..487de24f0 100644 --- a/main/docs/authenticate/passwordless/implement-login/embedded-login/webapps.mdx +++ b/main/docs/authenticate/passwordless/implement-login/embedded-login/webapps.mdx @@ -12,6 +12,8 @@ title: Embedded Passwordless Login in Regular Web Applications --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + To use the Embedded Passwordless APIs in Regular Web Applications, make sure you enable the **Passwordless OTP** grant at [Auth0 Dashboard > Applications > Applications](https://manage.auth0.com/#/applications) in your application's settings under **Advanced Settings** > **Grant Types**. Passwordless authentication for Regular Web Applications consists of two steps: @@ -25,16 +27,22 @@ Below, we list a few code snippets that can be used to call these API endpoints **Send a one-time-use code via email** -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/passwordless/start' \ --header 'content-type: application/json' \ - --data '{"client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "connection": "email", "email": "{userEmail}","send": "code"}'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/passwordless/start"); + --data '{"client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "connection": "email", "email": "{userEmail}","send": "code"}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/passwordless/start"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"connection\": \"email\", \"email\": \"{userEmail}\",\"send\": \"code\"}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{"client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "connection": "email", "email": "{userEmail}","send": "code"}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -47,7 +55,7 @@ func main() { url := "https://{yourDomain}/passwordless/start" - payload := strings.NewReader("{\"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"connection\": \"email\", \"email\": \"{userEmail}\",\"send\": \"code\"}") + payload := strings.NewReader("{"client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "connection": "email", "email": "{userEmail}","send": "code"}") req, _ := http.NewRequest("POST", url, payload) @@ -61,12 +69,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/passwordless/start") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/passwordless/start") .header("content-type", "application/json") - .body("{\"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"connection\": \"email\", \"email\": \"{userEmail}\",\"send\": \"code\"}") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{"client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "connection": "email", "email": "{userEmail}","send": "code"}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -85,8 +97,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json" }; NSDictionary *parameters = @{ @"client_id": @"{yourClientId}", @@ -114,8 +128,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/passwordless/start", @@ -125,7 +141,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{\"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"connection\": \"email\", \"email\": \"{userEmail}\",\"send\": \"code\"}", + CURLOPT_POSTFIELDS => "{"client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "connection": "email", "email": "{userEmail}","send": "code"}", CURLOPT_HTTPHEADER => [ "content-type: application/json" ], @@ -140,12 +156,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"connection\": \"email\", \"email\": \"{userEmail}\",\"send\": \"code\"}" +payload = "{"client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "connection": "email", "email": "{userEmail}","send": "code"}" headers = { 'content-type': "application/json" } @@ -154,8 +172,10 @@ conn.request("POST", "/{yourDomain}/passwordless/start", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -167,11 +187,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["content-type"] = 'application/json' -request.body = "{\"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"connection\": \"email\", \"email\": \"{userEmail}\",\"send\": \"code\"}" +request.body = "{"client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "connection": "email", "email": "{userEmail}","send": "code"}" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/json"] let parameters = [ @@ -201,35 +223,30 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + **Send a magic link via email** You need to specify `send: link`. -export const codeExample11 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/passwordless/start' \ --header 'content-type: application/json' \ - --data '{"client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "connection": "email", "email": "{userEmail}","send": "link"}'`; -export const codeExample12 = `var client = new RestClient("https://{yourDomain}/passwordless/start"); + --data '{"client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "connection": "email", "email": "{userEmail}","send": "link"}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/passwordless/start"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"connection\": \"email\", \"email\": \"{userEmail}\",\"send\": \"link\"}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample13 = `package main +request.AddParameter("application/json", "{"client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "connection": "email", "email": "{userEmail}","send": "link"}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -242,7 +259,7 @@ func main() { url := "https://{yourDomain}/passwordless/start" - payload := strings.NewReader("{\"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"connection\": \"email\", \"email\": \"{userEmail}\",\"send\": \"link\"}") + payload := strings.NewReader("{"client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "connection": "email", "email": "{userEmail}","send": "link"}") req, _ := http.NewRequest("POST", url, payload) @@ -256,12 +273,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample14 = `HttpResponse response = Unirest.post("https://{yourDomain}/passwordless/start") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/passwordless/start") .header("content-type", "application/json") - .body("{\"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"connection\": \"email\", \"email\": \"{userEmail}\",\"send\": \"link\"}") - .asString();`; -export const codeExample15 = `var axios = require("axios").default; + .body("{"client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "connection": "email", "email": "{userEmail}","send": "link"}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -280,8 +301,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample16 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json" }; NSDictionary *parameters = @{ @"client_id": @"{yourClientId}", @@ -309,8 +332,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/passwordless/start", @@ -320,7 +345,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{\"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"connection\": \"email\", \"email\": \"{userEmail}\",\"send\": \"link\"}", + CURLOPT_POSTFIELDS => "{"client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "connection": "email", "email": "{userEmail}","send": "link"}", CURLOPT_HTTPHEADER => [ "content-type: application/json" ], @@ -335,12 +360,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"connection\": \"email\", \"email\": \"{userEmail}\",\"send\": \"link\"}" +payload = "{"client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "connection": "email", "email": "{userEmail}","send": "link"}" headers = { 'content-type': "application/json" } @@ -349,8 +376,10 @@ conn.request("POST", "/{yourDomain}/passwordless/start", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -362,11 +391,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["content-type"] = 'application/json' -request.body = "{\"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"connection\": \"email\", \"email\": \"{userEmail}\",\"send\": \"link\"}" +request.body = "{"client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "connection": "email", "email": "{userEmail}","send": "link"}" response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/json"] let parameters = [ @@ -396,33 +427,28 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + **Send a one-time-use password via SMS** -export const codeExample21 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/passwordless/start' \ --header 'content-type: application/json' \ - --data '{"client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "connection": "sms", "phone_number": "{userPhoneNumber}","send": "code"}'`; -export const codeExample22 = `var client = new RestClient("https://{yourDomain}/passwordless/start"); + --data '{"client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "connection": "sms", "phone_number": "{userPhoneNumber}","send": "code"}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/passwordless/start"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"connection\": \"sms\", \"phone_number\": \"{userPhoneNumber}\",\"send\": \"code\"}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample23 = `package main +request.AddParameter("application/json", "{"client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "connection": "sms", "phone_number": "{userPhoneNumber}","send": "code"}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -435,7 +461,7 @@ func main() { url := "https://{yourDomain}/passwordless/start" - payload := strings.NewReader("{\"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"connection\": \"sms\", \"phone_number\": \"{userPhoneNumber}\",\"send\": \"code\"}") + payload := strings.NewReader("{"client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "connection": "sms", "phone_number": "{userPhoneNumber}","send": "code"}") req, _ := http.NewRequest("POST", url, payload) @@ -449,12 +475,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample24 = `HttpResponse response = Unirest.post("https://{yourDomain}/passwordless/start") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/passwordless/start") .header("content-type", "application/json") - .body("{\"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"connection\": \"sms\", \"phone_number\": \"{userPhoneNumber}\",\"send\": \"code\"}") - .asString();`; -export const codeExample25 = `var axios = require("axios").default; + .body("{"client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "connection": "sms", "phone_number": "{userPhoneNumber}","send": "code"}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -473,8 +503,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample26 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json" }; NSDictionary *parameters = @{ @"client_id": @"{yourClientId}", @@ -502,8 +534,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample27 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/passwordless/start", @@ -513,7 +547,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{\"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"connection\": \"sms\", \"phone_number\": \"{userPhoneNumber}\",\"send\": \"code\"}", + CURLOPT_POSTFIELDS => "{"client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "connection": "sms", "phone_number": "{userPhoneNumber}","send": "code"}", CURLOPT_HTTPHEADER => [ "content-type: application/json" ], @@ -528,12 +562,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample28 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"connection\": \"sms\", \"phone_number\": \"{userPhoneNumber}\",\"send\": \"code\"}" +payload = "{"client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "connection": "sms", "phone_number": "{userPhoneNumber}","send": "code"}" headers = { 'content-type': "application/json" } @@ -542,8 +578,10 @@ conn.request("POST", "/{yourDomain}/passwordless/start", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample29 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -555,11 +593,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["content-type"] = 'application/json' -request.body = "{\"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"connection\": \"sms\", \"phone_number\": \"{userPhoneNumber}\",\"send\": \"code\"}" +request.body = "{"client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "connection": "sms", "phone_number": "{userPhoneNumber}","send": "code"}" response = http.request(request) -puts response.read_body`; -export const codeExample30 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/json"] let parameters = [ @@ -589,33 +629,28 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + **Authenticate an SMS user** -export const codeExample31 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/json' \ - --data '{"grant_type": "http://auth0.com/oauth/grant-type/passwordless/otp", "client_id": "{yourClientId}", "client_secret": "YOUR_CLIENT_SECRET", "username": "USER_PHONE_NUMBER", "otp": "code", "realm": "sms", "audience": "your-api-audience","scope": "openid profile email"}'`; -export const codeExample32 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data '{"grant_type": "http://auth0.com/oauth/grant-type/passwordless/otp", "client_id": "{yourClientId}", "client_secret": "YOUR_CLIENT_SECRET", "username": "USER_PHONE_NUMBER", "otp": "code", "realm": "sms", "audience": "your-api-audience","scope": "openid profile email"}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\"grant_type\": \"http://auth0.com/oauth/grant-type/passwordless/otp\", \"client_id\": \"{yourClientId}\", \"client_secret\": \"YOUR_CLIENT_SECRET\", \"username\": \"USER_PHONE_NUMBER\", \"otp\": \"code\", \"realm\": \"sms\", \"audience\": \"your-api-audience\",\"scope\": \"openid profile email\"}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample33 = `package main +request.AddParameter("application/json", "{"grant_type": "http://auth0.com/oauth/grant-type/passwordless/otp", "client_id": "{yourClientId}", "client_secret": "YOUR_CLIENT_SECRET", "username": "USER_PHONE_NUMBER", "otp": "code", "realm": "sms", "audience": "your-api-audience","scope": "openid profile email"}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -628,7 +663,7 @@ func main() { url := "https://{yourDomain}/oauth/token" - payload := strings.NewReader("{\"grant_type\": \"http://auth0.com/oauth/grant-type/passwordless/otp\", \"client_id\": \"{yourClientId}\", \"client_secret\": \"YOUR_CLIENT_SECRET\", \"username\": \"USER_PHONE_NUMBER\", \"otp\": \"code\", \"realm\": \"sms\", \"audience\": \"your-api-audience\",\"scope\": \"openid profile email\"}") + payload := strings.NewReader("{"grant_type": "http://auth0.com/oauth/grant-type/passwordless/otp", "client_id": "{yourClientId}", "client_secret": "YOUR_CLIENT_SECRET", "username": "USER_PHONE_NUMBER", "otp": "code", "realm": "sms", "audience": "your-api-audience","scope": "openid profile email"}") req, _ := http.NewRequest("POST", url, payload) @@ -642,12 +677,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample34 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/json") - .body("{\"grant_type\": \"http://auth0.com/oauth/grant-type/passwordless/otp\", \"client_id\": \"{yourClientId}\", \"client_secret\": \"YOUR_CLIENT_SECRET\", \"username\": \"USER_PHONE_NUMBER\", \"otp\": \"code\", \"realm\": \"sms\", \"audience\": \"your-api-audience\",\"scope\": \"openid profile email\"}") - .asString();`; -export const codeExample35 = `var axios = require("axios").default; + .body("{"grant_type": "http://auth0.com/oauth/grant-type/passwordless/otp", "client_id": "{yourClientId}", "client_secret": "YOUR_CLIENT_SECRET", "username": "USER_PHONE_NUMBER", "otp": "code", "realm": "sms", "audience": "your-api-audience","scope": "openid profile email"}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -669,8 +708,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample36 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json" }; NSDictionary *parameters = @{ @"grant_type": @"http://auth0.com/oauth/grant-type/passwordless/otp", @@ -701,8 +742,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample37 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -712,7 +755,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{\"grant_type\": \"http://auth0.com/oauth/grant-type/passwordless/otp\", \"client_id\": \"{yourClientId}\", \"client_secret\": \"YOUR_CLIENT_SECRET\", \"username\": \"USER_PHONE_NUMBER\", \"otp\": \"code\", \"realm\": \"sms\", \"audience\": \"your-api-audience\",\"scope\": \"openid profile email\"}", + CURLOPT_POSTFIELDS => "{"grant_type": "http://auth0.com/oauth/grant-type/passwordless/otp", "client_id": "{yourClientId}", "client_secret": "YOUR_CLIENT_SECRET", "username": "USER_PHONE_NUMBER", "otp": "code", "realm": "sms", "audience": "your-api-audience","scope": "openid profile email"}", CURLOPT_HTTPHEADER => [ "content-type: application/json" ], @@ -727,12 +770,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample38 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"grant_type\": \"http://auth0.com/oauth/grant-type/passwordless/otp\", \"client_id\": \"{yourClientId}\", \"client_secret\": \"YOUR_CLIENT_SECRET\", \"username\": \"USER_PHONE_NUMBER\", \"otp\": \"code\", \"realm\": \"sms\", \"audience\": \"your-api-audience\",\"scope\": \"openid profile email\"}" +payload = "{"grant_type": "http://auth0.com/oauth/grant-type/passwordless/otp", "client_id": "{yourClientId}", "client_secret": "YOUR_CLIENT_SECRET", "username": "USER_PHONE_NUMBER", "otp": "code", "realm": "sms", "audience": "your-api-audience","scope": "openid profile email"}" headers = { 'content-type': "application/json" } @@ -741,8 +786,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample39 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -754,11 +801,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["content-type"] = 'application/json' -request.body = "{\"grant_type\": \"http://auth0.com/oauth/grant-type/passwordless/otp\", \"client_id\": \"{yourClientId}\", \"client_secret\": \"YOUR_CLIENT_SECRET\", \"username\": \"USER_PHONE_NUMBER\", \"otp\": \"code\", \"realm\": \"sms\", \"audience\": \"your-api-audience\",\"scope\": \"openid profile email\"}" +request.body = "{"grant_type": "http://auth0.com/oauth/grant-type/passwordless/otp", "client_id": "{yourClientId}", "client_secret": "YOUR_CLIENT_SECRET", "username": "USER_PHONE_NUMBER", "otp": "code", "realm": "sms", "audience": "your-api-audience","scope": "openid profile email"}" response = http.request(request) -puts response.read_body`; -export const codeExample40 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/json"] let parameters = [ @@ -791,33 +840,28 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + **Authenticate an Email user** -export const codeExample41 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/json' \ - --data '{"grant_type": "http://auth0.com/oauth/grant-type/passwordless/otp", "client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "username": "{userPhoneNumber}", "otp": "code", "realm": "email", "audience": "your-api-audience", "scope": "openid profile email"}'`; -export const codeExample42 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data '{"grant_type": "http://auth0.com/oauth/grant-type/passwordless/otp", "client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "username": "{userPhoneNumber}", "otp": "code", "realm": "email", "audience": "your-api-audience", "scope": "openid profile email"}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\"grant_type\": \"http://auth0.com/oauth/grant-type/passwordless/otp\", \"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"username\": \"{userPhoneNumber}\", \"otp\": \"code\", \"realm\": \"email\", \"audience\": \"your-api-audience\", \"scope\": \"openid profile email\"}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample43 = `package main +request.AddParameter("application/json", "{"grant_type": "http://auth0.com/oauth/grant-type/passwordless/otp", "client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "username": "{userPhoneNumber}", "otp": "code", "realm": "email", "audience": "your-api-audience", "scope": "openid profile email"}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -830,7 +874,7 @@ func main() { url := "https://{yourDomain}/oauth/token" - payload := strings.NewReader("{\"grant_type\": \"http://auth0.com/oauth/grant-type/passwordless/otp\", \"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"username\": \"{userPhoneNumber}\", \"otp\": \"code\", \"realm\": \"email\", \"audience\": \"your-api-audience\", \"scope\": \"openid profile email\"}") + payload := strings.NewReader("{"grant_type": "http://auth0.com/oauth/grant-type/passwordless/otp", "client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "username": "{userPhoneNumber}", "otp": "code", "realm": "email", "audience": "your-api-audience", "scope": "openid profile email"}") req, _ := http.NewRequest("POST", url, payload) @@ -844,12 +888,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample44 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/json") - .body("{\"grant_type\": \"http://auth0.com/oauth/grant-type/passwordless/otp\", \"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"username\": \"{userPhoneNumber}\", \"otp\": \"code\", \"realm\": \"email\", \"audience\": \"your-api-audience\", \"scope\": \"openid profile email\"}") - .asString();`; -export const codeExample45 = `var axios = require("axios").default; + .body("{"grant_type": "http://auth0.com/oauth/grant-type/passwordless/otp", "client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "username": "{userPhoneNumber}", "otp": "code", "realm": "email", "audience": "your-api-audience", "scope": "openid profile email"}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -871,8 +919,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample46 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json" }; NSDictionary *parameters = @{ @"grant_type": @"http://auth0.com/oauth/grant-type/passwordless/otp", @@ -903,8 +953,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample47 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -914,7 +966,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{\"grant_type\": \"http://auth0.com/oauth/grant-type/passwordless/otp\", \"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"username\": \"{userPhoneNumber}\", \"otp\": \"code\", \"realm\": \"email\", \"audience\": \"your-api-audience\", \"scope\": \"openid profile email\"}", + CURLOPT_POSTFIELDS => "{"grant_type": "http://auth0.com/oauth/grant-type/passwordless/otp", "client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "username": "{userPhoneNumber}", "otp": "code", "realm": "email", "audience": "your-api-audience", "scope": "openid profile email"}", CURLOPT_HTTPHEADER => [ "content-type: application/json" ], @@ -929,12 +981,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample48 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"grant_type\": \"http://auth0.com/oauth/grant-type/passwordless/otp\", \"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"username\": \"{userPhoneNumber}\", \"otp\": \"code\", \"realm\": \"email\", \"audience\": \"your-api-audience\", \"scope\": \"openid profile email\"}" +payload = "{"grant_type": "http://auth0.com/oauth/grant-type/passwordless/otp", "client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "username": "{userPhoneNumber}", "otp": "code", "realm": "email", "audience": "your-api-audience", "scope": "openid profile email"}" headers = { 'content-type': "application/json" } @@ -943,8 +997,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample49 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -956,11 +1012,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["content-type"] = 'application/json' -request.body = "{\"grant_type\": \"http://auth0.com/oauth/grant-type/passwordless/otp\", \"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"username\": \"{userPhoneNumber}\", \"otp\": \"code\", \"realm\": \"email\", \"audience\": \"your-api-audience\", \"scope\": \"openid profile email\"}" +request.body = "{"grant_type": "http://auth0.com/oauth/grant-type/passwordless/otp", "client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "username": "{userPhoneNumber}", "otp": "code", "realm": "email", "audience": "your-api-audience", "scope": "openid profile email"}" response = http.request(request) -puts response.read_body`; -export const codeExample50 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/json"] let parameters = [ @@ -993,20 +1051,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + **Authenticate a user through a magic link** @@ -1043,7 +1090,6 @@ When using [Lock for Web](/docs/libraries/lock#2-authenticating-and-getting-user } ``` - Use the `mfa_token` to call the [`mfa/authenticator`](https://auth0.com/docs/api/authentication/muti-factor-authentication/list-authenticators) endpoint to list all factors the user has enrolled and match the same `type` your application supports. You also need to obtain the matching `authenticator_type` to issue challenges: ```json lines @@ -1063,7 +1109,6 @@ Use the `mfa_token` to call the [`mfa/authenticator`](https://auth0.com/docs/api ] ``` - Proceed to enforce the MFA challenge by calling the [`request/mfa/challenge`](https://auth0.com/docs/api/authentication/muti-factor-authentication/request-mfa-challenge) endpoint. Further customize your MFA flow with Auth0 Actions. To learn more, read [Actions Triggers: post-challenge - API Object](/docs/customize/actions/explore-triggers/password-reset-triggers/post-challenge-trigger/post-challenge-api-object). \ No newline at end of file diff --git a/main/docs/authenticate/protocols/saml/saml-identity-provider-configuration-settings.mdx b/main/docs/authenticate/protocols/saml/saml-identity-provider-configuration-settings.mdx index 573cc2fd2..8a6d2f5fc 100644 --- a/main/docs/authenticate/protocols/saml/saml-identity-provider-configuration-settings.mdx +++ b/main/docs/authenticate/protocols/saml/saml-identity-provider-configuration-settings.mdx @@ -10,6 +10,8 @@ title: SAML Identity Provider Configuration Settings --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + ## Common settings These are the settings used to configure a SAML identity provider (IdP). @@ -28,22 +30,12 @@ export const codeExample1 = `https://{yourDomain}/login/callback?connection={you - - - - - If you are using the [Organizations](/docs/manage-users/organizations) feature, you can optionally include an organization parameter containing the organization ID of the desired organization: export const codeExample2 = `https://{yourDomain}/login/callback?connection={yourConnectionName}&organization={yourCustomersOrganizationId}`; - - - - - In order for users to successfully log-in using this method, the connection must be enabled for the Organization. Additionally, you must either configure [auto-membership](/docs/manage-users/organizations/configure-organizations/grant-just-in-time-membership) for the enabled connection or ensure users have membership for the Organization. @@ -58,23 +50,24 @@ The ID of the service provider is: urn:auth0:{yourTenant}:{yourConnectionName} ``` - - - - - You can create a custom Entity ID using the property `connection.options.entityId`. To learn more, read [Specify a Custom Entity ID](/docs/authenticate/identity-providers/enterprise-identity-providers/saml#specify-a-custom-entity-id). You can obtain the custom Entity ID value using the Get a Connection endpoint: -export const codeExample3 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/connections/%7ByourConnectionID%7D' \ - --header 'authorization: Bearer {yourAccessToken}'`; -export const codeExample4 = `var client = new RestClient("https://{yourDomain}/api/v2/connections/%7ByourConnectionID%7D"); + --header 'authorization: Bearer {yourAccessToken}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/connections/%7ByourConnectionID%7D"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer {yourAccessToken}"); -IRestResponse response = client.Execute(request);`; -export const codeExample5 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -98,11 +91,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample6 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/connections/%7ByourConnectionID%7D") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/connections/%7ByourConnectionID%7D") .header("authorization", "Bearer {yourAccessToken}") - .asString();`; -export const codeExample7 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -114,8 +111,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample8 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer {yourAccessToken}" }; @@ -135,8 +134,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample9 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/connections/%7ByourConnectionID%7D", @@ -160,8 +161,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample10 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -172,8 +175,10 @@ conn.request("GET", "/{yourDomain}/api/v2/connections/%7ByourConnectionID%7D", h res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample11 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -187,8 +192,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer {yourAccessToken}' response = http.request(request) -puts response.read_body`; -export const codeExample12 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer {yourAccessToken}"] @@ -208,20 +215,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + Replace the `ACCESS_TOKEN` header value, with a Management APIv2 access token. @@ -273,11 +269,6 @@ export const codeExample13 = `https://{yourDomain}/logout`; - - - - - SAML logout requests must be signed by the identity provider. ## Signed assertions @@ -304,11 +295,6 @@ export const codeExample14 = `https://{yourDomain}/samlp/metadata?connection={yo - - - - - ## Organizations Use the ACS URL for your organization in the federated IdP to start the Organizations login flow. @@ -317,7 +303,6 @@ export const codeExample15 = `https://{yourDomain}/samlp?connection={yourConnect - ## Learn more * [Locate the Connection ID or Name](/docs/authenticate/identity-providers/locate-the-connection-id) diff --git a/main/docs/authenticate/single-sign-on/native-to-web/configure-implement-native-to-web.mdx b/main/docs/authenticate/single-sign-on/native-to-web/configure-implement-native-to-web.mdx index 46025291f..be0994f7a 100644 --- a/main/docs/authenticate/single-sign-on/native-to-web/configure-implement-native-to-web.mdx +++ b/main/docs/authenticate/single-sign-on/native-to-web/configure-implement-native-to-web.mdx @@ -12,6 +12,8 @@ title: Configure and Implement Native to Web SSO --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + Native to Web SSO is currently available in Early Access. To use this feature, you must have an Enterprise plan. By using this feature, you agree to the applicable Free Trial terms in Okta’s [Master Subscription Agreement](https://www.okta.com/legal). To learn more about Auth0's product release cycle, read [Product Release Stages](https://auth0.com/docs/troubleshoot/product-lifecycle/product-release-stages). @@ -59,11 +61,6 @@ For existing applications, make a `PATCH` call to the [Update a Client](https:// } ``` - - - - - ### Configure native applications Once a user is authenticated, Auth0 returns an [Access token](/docs/secure/tokens/access-tokens), and [ID token](/docs/secure/tokens/id-tokens), and (optionally) a [Refresh token](/docs/secure/tokens/refresh-tokens). @@ -74,7 +71,6 @@ You can configure your native application to exchange a - - - - - * Update your native application using [Auth0 CLI](https://auth0.github.io/auth0-cli/auth0_apps_session-transfer_update.html): export const codeExample2 = `auth0 apps session-transfer update {yourClientId} --can-create-token=true`; - - - - - ### Configure web applications Before you enable Session Transfer Token, make sure you have configured your web application’s **Application Login URI** to handle extra parameters. To learn more about URIs, read [Application Settings](/docs/get-started/applications/application-settings#application-uris). @@ -112,7 +98,6 @@ Before you enable Session Transfer Token, make sure you have configured your web {/* codeblockOld.header.login.logInButton codeblockOld.header.login.configureSnippet */} - export const codeExample3 = `curl --request PATCH \ --url '{yourDomain}/api/v2/clients//{yourClientId}' \ --header 'authorization: Bearer {yourMgmtApiAccessToken}' \ @@ -128,22 +113,12 @@ export const codeExample3 = `curl --request PATCH \ - - - - - * Update your web application using [Auth0 CLI](https://auth0.github.io/auth0-cli/auth0_apps_session-transfer_update.html): export const codeExample4 = `auth0 apps session-transfer update {yourClientId} --allowed-auth-methods=cookie,query --enforce-device-binding=ip`; - - - - - ## Implement Native to Web SSO Native to Web Single SSO provides a seamless user experience transitioning authenticated users from your native application to your web application. @@ -188,11 +163,6 @@ do { } ``` - - - - - ```swift lines @@ -209,18 +179,12 @@ authentication }) ``` - - - - - * Exchange a refresh token for a session transfer token using HTTP: {/* codeblockOld.header.login.logInButton codeblockOld.header.login.configureSnippet */} - export const codeExample5 = `curl -X POST https://{yourDomain}/oauth/token \ -H 'Content-type: application/json' \ -d '{"grant_type":"refresh_token", @@ -230,11 +194,6 @@ export const codeExample5 = `curl -X POST https://{yourDomain}/oauth/token \ - - - - - These samples use placeholder variables for dynamic variables. Replace the placeholders using your Auth0 domain, client_id and an existing refresh_token. @@ -252,11 +211,6 @@ The Auth0 tenant returns a single-use and short-lived (1-minute lifetime) sessio } ``` - - - - - If refresh token rotation is enabled, the exchange will also return a refresh token. @@ -282,11 +236,6 @@ export const codeExample6 = `curl --cookie auth0_session_transfer_token=YOUR_SES - - - - - ##### Option 2: Send the session_transfer_token as a URL parameter If your web application does not support cookie injection, you can configure your native application using URL parameters to: @@ -295,7 +244,7 @@ If your web application does not support cookie injection, you can configure you * Open the web application using  WebView or browser. * Log the web application appending the `session_transfer_token` as a URL parameter to the [/authorize](https://auth0.com/docs/api/authentication/authorization-code-flow/authorize-application) endpoint. The Auth0 tenant authenticates the user without requiring first-factor authentication, as the session_transfer_token is valid and trusted - + ```bash cURL lines curl --request GET \ --url 'https://your_web_app_login_url/?session_transfer_token=YOUR_SESSION_TRANSFER_TOKEN' @@ -405,7 +354,7 @@ request = Net::HTTP::Get.new(url) response = http.request(request) puts response.read_body ``` - + ### In your web application @@ -421,12 +370,18 @@ Implement Native to Web Web Single SSO in your web application using URL paramet From the application login URL, redirect to the `/authorize` endpoint when the `session_transfer_token` is sent as a URL parameter. -export const codeExample7 = `curl --request GET \ - --url 'https://{yourDomain}/authorize?session_transfer_token=YOUR_SESSION_TRANSFER_TOKEN&client_ID={yourClientId}&redirect_uri=YOUR_REDIRECT_URI&response_type=code'`; -export const codeExample8 = `var client = new RestClient("https://{yourDomain}/authorize?session_transfer_token=YOUR_SESSION_TRANSFER_TOKEN&client_ID={yourClientId}&redirect_uri=YOUR_REDIRECT_URI&response_type=code"); + +```bash cURL +curl --request GET \ + --url 'https://{yourDomain}/authorize?session_transfer_token=YOUR_SESSION_TRANSFER_TOKEN&client_ID={yourClientId}&redirect_uri=YOUR_REDIRECT_URI&response_type=code' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/authorize?session_transfer_token=YOUR_SESSION_TRANSFER_TOKEN&client_ID={yourClientId}&redirect_uri=YOUR_REDIRECT_URI&response_type=code"); var request = new RestRequest(Method.GET); -IRestResponse response = client.Execute(request);`; -export const codeExample9 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -448,10 +403,14 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample10 = `HttpResponse response = Unirest.get("https://{yourDomain}/authorize?session_transfer_token=YOUR_SESSION_TRANSFER_TOKEN&client_ID={yourClientId}&redirect_uri=YOUR_REDIRECT_URI&response_type=code") - .asString();`; -export const codeExample11 = `var axios = require("axios").default; +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/authorize?session_transfer_token=YOUR_SESSION_TRANSFER_TOKEN&client_ID={yourClientId}&redirect_uri=YOUR_REDIRECT_URI&response_type=code") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -468,8 +427,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample12 = `$curl = curl_init(); +}); +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/authorize?session_transfer_token=YOUR_SESSION_TRANSFER_TOKEN&client_ID={yourClientId}&redirect_uri=YOUR_REDIRECT_URI&response_type=code", @@ -490,8 +451,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample13 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -500,17 +463,9 @@ conn.request("GET", "/{yourDomain}/authorize?session_transfer_token=YOUR_SESSION res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; - - - - - - - - - - +print(data.decode("utf-8")) +``` + #### Option 2: Add the Session Transfer Token to web applications using Auth0 SDKs @@ -545,24 +500,25 @@ app.use((req, res, next) => { }); ``` - - - - - ##### SAML and WS-Federation If your web application uses SAML or WS-Fed service provider and Auth0 as the IdP, you can send the `session_transfer_token` as an URL parameter to the Auth0 `/authorize` endpoint and the `redirect_uri` is the SAML or WS-Fed sign-in URL. -export const codeExample14 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/samlp//{yourClientId}?session_transfer_token=YOUR_SESSION_TRANSFER_TOKEN' \ --header 'cookie: session_transfer_token=YOUR_SESSION_TRANSFER_TOKEN' \ - --cookie session_transfer_token=YOUR_SESSION_TRANSFER_TOKEN`; -export const codeExample15 = `var client = new RestClient("https://{yourDomain}/samlp//{yourClientId}?session_transfer_token=YOUR_SESSION_TRANSFER_TOKEN"); + --cookie session_transfer_token=YOUR_SESSION_TRANSFER_TOKEN +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/samlp//{yourClientId}?session_transfer_token=YOUR_SESSION_TRANSFER_TOKEN"); var request = new RestRequest(Method.GET); request.AddHeader("cookie", "session_transfer_token=YOUR_SESSION_TRANSFER_TOKEN"); -IRestResponse response = client.Execute(request);`; -export const codeExample16 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -585,11 +541,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample17 = `HttpResponse response = Unirest.get("https://{yourDomain}/samlp//{yourClientId}?session_transfer_token=YOUR_SESSION_TRANSFER_TOKEN") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/samlp//{yourClientId}?session_transfer_token=YOUR_SESSION_TRANSFER_TOKEN") .header("cookie", "session_transfer_token=YOUR_SESSION_TRANSFER_TOKEN") - .asString();`; -export const codeExample18 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -602,8 +562,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample19 = `$curl = curl_init(); +}); +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/samlp//{yourClientId}?session_transfer_token=YOUR_SESSION_TRANSFER_TOKEN", @@ -627,8 +589,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample20 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -639,8 +603,10 @@ conn.request("GET", "/{yourDomain}/samlp//{yourClientId}?session_transfer_token= res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample21 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -654,18 +620,9 @@ request = Net::HTTP::Get.new(url) request["cookie"] = 'session_transfer_token=YOUR_SESSION_TRANSFER_TOKEN' response = http.request(request) -puts response.read_body`; - - - - - - - - - - - +puts response.read_body +``` + ## Session Transfer Token with Actions @@ -692,11 +649,6 @@ exports.onExecutePostLogin = async (event, api) => { }; ``` - - - - - ## Monitoring You can monitor the Native to Web SSO activity by reviewing the Tenant [logs](/docs/deploy-monitor/logs). diff --git a/main/docs/css/styles.css b/main/docs/css/styles.css index b80e65040..a0c80fa7b 100644 --- a/main/docs/css/styles.css +++ b/main/docs/css/styles.css @@ -527,7 +527,9 @@ ul.flex.items-center > li > a[href*="/u/login"] { background-color: #282828 !important; } */ -.nav-tabs a[href="/"] { +/* REMOVE HOMEPAGE TAB */ +.nav-tabs a[href="/"], +.nav-tabs a[href="/docs"] { display: none; } diff --git a/main/docs/customize/custom-domains/multiple-custom-domains.mdx b/main/docs/customize/custom-domains/multiple-custom-domains.mdx index 53d5e9986..5e92dfce7 100644 --- a/main/docs/customize/custom-domains/multiple-custom-domains.mdx +++ b/main/docs/customize/custom-domains/multiple-custom-domains.mdx @@ -12,6 +12,7 @@ title: Multiple Custom Domains --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Multiple Custom Domains is currently available in Early Access. To use this feature, you must have an Enterprise plan. By using this feature, you agree to the applicable Free Trial terms in Okta’s [Master Subscription Agreement](https://www.okta.com/legal). To learn more about Auth0's product release cycle, read [Product Release Stages](https://auth0.com/docs/troubleshoot/product-lifecycle/product-release-stages). @@ -69,7 +70,9 @@ To create a custom domain with the Management API, you need a machine-to-machine You can create a new custom domain by sending a `POST` request to the `/api/v2/custom-domains` endpoint. See the example below to create a new custom domain using the Management API explorer, using the credentials retrieved above: -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/api/v2/custom-domains' \ --header 'accept: application/json' \ --header 'authorization: Bearer {yourMgmtApiAccessToken}' \ @@ -81,15 +84,26 @@ export const codeExample1 = `curl --request POST \ "custom_client_ip_header": "true-client-ip", "domain_metadata": { "environment": "development"} -}'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/custom-domains"); +}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/custom-domains"); var request = new RestRequest(Method.POST); request.AddHeader("authorization", "Bearer {yourMgmtApiAccessToken}"); request.AddHeader("content-type", "application/json"); request.AddHeader("accept", "application/json"); -request.AddParameter("application/json", "{ \n \"domain\": \"your.example-custom-domain.com\", \n \"type\": \"auth0_managed_certs\", \n \"tls_policy\": \"recommended\", \n \"custom_client_ip_header\": \"true-client-ip\", \n \"domain_metadata\": {\n \"environment\": \"development\"} \n}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ + "domain": "your.example-custom-domain.com", + "type": "auth0_managed_certs", + "tls_policy": "recommended", + "custom_client_ip_header": "true-client-ip", + "domain_metadata": { + "environment": "development"} +}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -102,7 +116,14 @@ func main() { url := "https://{yourDomain}/api/v2/custom-domains" - payload := strings.NewReader("{ \n \"domain\": \"your.example-custom-domain.com\", \n \"type\": \"auth0_managed_certs\", \n \"tls_policy\": \"recommended\", \n \"custom_client_ip_header\": \"true-client-ip\", \n \"domain_metadata\": {\n \"environment\": \"development\"} \n}") + payload := strings.NewReader("{ + "domain": "your.example-custom-domain.com", + "type": "auth0_managed_certs", + "tls_policy": "recommended", + "custom_client_ip_header": "true-client-ip", + "domain_metadata": { + "environment": "development"} +}") req, _ := http.NewRequest("POST", url, payload) @@ -118,14 +139,25 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/custom-domains") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/custom-domains") .header("authorization", "Bearer {yourMgmtApiAccessToken}") .header("content-type", "application/json") .header("accept", "application/json") - .body("{ \n \"domain\": \"your.example-custom-domain.com\", \n \"type\": \"auth0_managed_certs\", \n \"tls_policy\": \"recommended\", \n \"custom_client_ip_header\": \"true-client-ip\", \n \"domain_metadata\": {\n \"environment\": \"development\"} \n}") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ + "domain": "your.example-custom-domain.com", + "type": "auth0_managed_certs", + "tls_policy": "recommended", + "custom_client_ip_header": "true-client-ip", + "domain_metadata": { + "environment": "development"} +}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -148,8 +180,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer {yourMgmtApiAccessToken}", @"content-type": @"application/json", @@ -179,8 +213,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/custom-domains", @@ -190,7 +226,14 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{ \n \"domain\": \"your.example-custom-domain.com\", \n \"type\": \"auth0_managed_certs\", \n \"tls_policy\": \"recommended\", \n \"custom_client_ip_header\": \"true-client-ip\", \n \"domain_metadata\": {\n \"environment\": \"development\"} \n}", + CURLOPT_POSTFIELDS => "{ + "domain": "your.example-custom-domain.com", + "type": "auth0_managed_certs", + "tls_policy": "recommended", + "custom_client_ip_header": "true-client-ip", + "domain_metadata": { + "environment": "development"} +}", CURLOPT_HTTPHEADER => [ "accept: application/json", "authorization: Bearer {yourMgmtApiAccessToken}", @@ -207,12 +250,21 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \n \"domain\": \"your.example-custom-domain.com\", \n \"type\": \"auth0_managed_certs\", \n \"tls_policy\": \"recommended\", \n \"custom_client_ip_header\": \"true-client-ip\", \n \"domain_metadata\": {\n \"environment\": \"development\"} \n}" +payload = "{ + "domain": "your.example-custom-domain.com", + "type": "auth0_managed_certs", + "tls_policy": "recommended", + "custom_client_ip_header": "true-client-ip", + "domain_metadata": { + "environment": "development"} +}" headers = { 'authorization': "Bearer {yourMgmtApiAccessToken}", @@ -225,8 +277,10 @@ conn.request("POST", "/{yourDomain}/api/v2/custom-domains", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -240,11 +294,20 @@ request = Net::HTTP::Post.new(url) request["authorization"] = 'Bearer {yourMgmtApiAccessToken}' request["content-type"] = 'application/json' request["accept"] = 'application/json' -request.body = "{ \n \"domain\": \"your.example-custom-domain.com\", \n \"type\": \"auth0_managed_certs\", \n \"tls_policy\": \"recommended\", \n \"custom_client_ip_header\": \"true-client-ip\", \n \"domain_metadata\": {\n \"environment\": \"development\"} \n}" +request.body = "{ + "domain": "your.example-custom-domain.com", + "type": "auth0_managed_certs", + "tls_policy": "recommended", + "custom_client_ip_header": "true-client-ip", + "domain_metadata": { + "environment": "development"} +}" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "authorization": "Bearer {yourMgmtApiAccessToken}", @@ -278,20 +341,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + If successful, you should see the following returned with the details of your new custom domain, including it's verification status. The `status` is initially returned as `pending`. @@ -318,11 +370,6 @@ If successful, you should see the following returned with the details of your ne } ``` - - - - - ## MCD features @@ -418,11 +465,6 @@ const auth0 = new ManagementClient({ })(); ``` - - - - - Sample response: The custom domain is passed in the header used to generate the ticket URL. ```json lines @@ -431,11 +473,6 @@ Sample response: The custom domain is passed in the header used to generate the } ``` - - - - - ##### Response messages When you provide the `auth0-custom-domain` HTTP header, the following additional response types are possible: @@ -516,11 +553,6 @@ exports.onExecutePostLogin = async (event, api) => { }; ``` - - - - - MCD GA will introduce a new custom domain Action object, which will include custom domain metadata. Your Action code will need to be updated at GA if you use the new object. diff --git a/main/docs/customize/email/manage-email-flow.mdx b/main/docs/customize/email/manage-email-flow.mdx index 11239ecd3..e9e7ed222 100644 --- a/main/docs/customize/email/manage-email-flow.mdx +++ b/main/docs/customize/email/manage-email-flow.mdx @@ -12,6 +12,8 @@ title: Customize Email Handling --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + The End of Life (EOL) date of Rules and Hooks will be **November 18, 2026**, and they are no longer available to new tenants created as of **October 16, 2023**. Existing tenants with active Hooks will retain Hooks product access through end of life. @@ -50,18 +52,24 @@ You can send verification emails in more than one way: The [Send an email address verification email endpoint](https://auth0.com/docs/api/management/v2#!/Jobs/post_verification_email) sends the user an email prompting them to verify their email address. -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/api/v2/jobs/verification-email' \ --header 'authorization: Bearer {yourMgmtApiAccessToken}' \ --header 'content-type: application/json' \ - --data '{ "user_id": "{userIdOfVerifyEmailRecipient}", "client_id": "{yourAppClientId}","identity": {"user_id": "5457edea1b8f22891a000004","provider": "google-oauth2"}, "organization_id": "{yourOrganizationId}" }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/jobs/verification-email"); + --data '{ "user_id": "{userIdOfVerifyEmailRecipient}", "client_id": "{yourAppClientId}","identity": {"user_id": "5457edea1b8f22891a000004","provider": "google-oauth2"}, "organization_id": "{yourOrganizationId}" }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/jobs/verification-email"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer {yourMgmtApiAccessToken}"); -request.AddParameter("application/json", "{ \"user_id\": \"{userIdOfVerifyEmailRecipient}\", \"client_id\": \"{yourAppClientId}\",\"identity\": {\"user_id\": \"5457edea1b8f22891a000004\",\"provider\": \"google-oauth2\"}, \"organization_id\": \"{yourOrganizationId}\" }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "user_id": "{userIdOfVerifyEmailRecipient}", "client_id": "{yourAppClientId}","identity": {"user_id": "5457edea1b8f22891a000004","provider": "google-oauth2"}, "organization_id": "{yourOrganizationId}" }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -74,7 +82,7 @@ func main() { url := "https://{yourDomain}/api/v2/jobs/verification-email" - payload := strings.NewReader("{ \"user_id\": \"{userIdOfVerifyEmailRecipient}\", \"client_id\": \"{yourAppClientId}\",\"identity\": {\"user_id\": \"5457edea1b8f22891a000004\",\"provider\": \"google-oauth2\"}, \"organization_id\": \"{yourOrganizationId}\" }") + payload := strings.NewReader("{ "user_id": "{userIdOfVerifyEmailRecipient}", "client_id": "{yourAppClientId}","identity": {"user_id": "5457edea1b8f22891a000004","provider": "google-oauth2"}, "organization_id": "{yourOrganizationId}" }") req, _ := http.NewRequest("POST", url, payload) @@ -89,13 +97,17 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/jobs/verification-email") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/jobs/verification-email") .header("content-type", "application/json") .header("authorization", "Bearer {yourMgmtApiAccessToken}") - .body("{ \"user_id\": \"{userIdOfVerifyEmailRecipient}\", \"client_id\": \"{yourAppClientId}\",\"identity\": {\"user_id\": \"5457edea1b8f22891a000004\",\"provider\": \"google-oauth2\"}, \"organization_id\": \"{yourOrganizationId}\" }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "user_id": "{userIdOfVerifyEmailRecipient}", "client_id": "{yourAppClientId}","identity": {"user_id": "5457edea1b8f22891a000004","provider": "google-oauth2"}, "organization_id": "{yourOrganizationId}" }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -116,8 +128,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer {yourMgmtApiAccessToken}" }; @@ -145,8 +159,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/jobs/verification-email", @@ -156,7 +172,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{ \"user_id\": \"{userIdOfVerifyEmailRecipient}\", \"client_id\": \"{yourAppClientId}\",\"identity\": {\"user_id\": \"5457edea1b8f22891a000004\",\"provider\": \"google-oauth2\"}, \"organization_id\": \"{yourOrganizationId}\" }", + CURLOPT_POSTFIELDS => "{ "user_id": "{userIdOfVerifyEmailRecipient}", "client_id": "{yourAppClientId}","identity": {"user_id": "5457edea1b8f22891a000004","provider": "google-oauth2"}, "organization_id": "{yourOrganizationId}" }", CURLOPT_HTTPHEADER => [ "authorization: Bearer {yourMgmtApiAccessToken}", "content-type: application/json" @@ -172,12 +188,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"user_id\": \"{userIdOfVerifyEmailRecipient}\", \"client_id\": \"{yourAppClientId}\",\"identity\": {\"user_id\": \"5457edea1b8f22891a000004\",\"provider\": \"google-oauth2\"}, \"organization_id\": \"{yourOrganizationId}\" }" +payload = "{ "user_id": "{userIdOfVerifyEmailRecipient}", "client_id": "{yourAppClientId}","identity": {"user_id": "5457edea1b8f22891a000004","provider": "google-oauth2"}, "organization_id": "{yourOrganizationId}" }" headers = { 'content-type': "application/json", @@ -189,8 +207,10 @@ conn.request("POST", "/{yourDomain}/api/v2/jobs/verification-email", payload, he res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -203,11 +223,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer {yourMgmtApiAccessToken}' -request.body = "{ \"user_id\": \"{userIdOfVerifyEmailRecipient}\", \"client_id\": \"{yourAppClientId}\",\"identity\": {\"user_id\": \"5457edea1b8f22891a000004\",\"provider\": \"google-oauth2\"}, \"organization_id\": \"{yourOrganizationId}\" }" +request.body = "{ "user_id": "{userIdOfVerifyEmailRecipient}", "client_id": "{yourAppClientId}","identity": {"user_id": "5457edea1b8f22891a000004","provider": "google-oauth2"}, "organization_id": "{yourOrganizationId}" }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -242,20 +264,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + @@ -297,11 +308,6 @@ function (user, context, callback) { } ``` - - - - - ### Require verified email for login @@ -318,11 +324,6 @@ function (user, context, callback) { } ``` - - - - - ### Custom redirects A custom redirect is useful when you want to direct users to certain URLs based on user attributes or on the tenant. The Auth0 Management API provides a [Create Email Verification Ticket endpoint](https://auth0.com/docs/api/management/v2/#!/Tickets/post_email_verification) that generates the verification link for each user. This endpoint allows you to specify the `result_url` to which users will be redirected after they have validated their email address by clicking the link in the verification email. @@ -365,11 +366,6 @@ function (user, context, callback) { } ``` - - - - - ## Password reset emails You can create a password change ticket using the Auth0 Management API [Create a Password Change Ticket](https://auth0.com/docs/api/management/v2/#!/Tickets/post_password_change) endpoint, and then send the password change ticket URL in an email to the user. When the user clicks the link, they will be prompted to reset their password through the Universal Login flow. diff --git a/main/docs/customize/hooks/create-hooks.mdx b/main/docs/customize/hooks/create-hooks.mdx index 8348ffd3e..3ffc3f883 100644 --- a/main/docs/customize/hooks/create-hooks.mdx +++ b/main/docs/customize/hooks/create-hooks.mdx @@ -12,6 +12,8 @@ title: Create Hooks --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + The End of Life (EOL) date of Rules and Hooks will be **November 18, 2026**, and they are no longer available to new tenants created as of **October 16, 2023**. Existing tenants with active Hooks will retain Hooks product access through end of life. @@ -59,20 +61,26 @@ Optionally, you can add secrets (such as Twilio Keys or database connection stri Make a `POST` call to the [Create a Hook endpoint](https://auth0.com/docs/api/management/v2/#!/Hooks/post_hooks). Be sure to replace `MGMT_API_ACCESS_TOKEN`, `HOOK_NAME`, `HOOK_SCRIPT`, and `EXTENSIBILITY_POINT_NAME` placeholder values with your Management API access token, Hook name, Hook script, and extensibility point name, respectively. -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/api/v2/hooks' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{ "name": "HOOK_NAME", "script": "HOOK_SCRIPT", "triggerId": "EXTENSIBILITY_POINT_NAME" }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/hooks"); + --data '{ "name": "HOOK_NAME", "script": "HOOK_SCRIPT", "triggerId": "EXTENSIBILITY_POINT_NAME" }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/hooks"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{ \"name\": \"HOOK_NAME\", \"script\": \"HOOK_SCRIPT\", \"triggerId\": \"EXTENSIBILITY_POINT_NAME\" }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "name": "HOOK_NAME", "script": "HOOK_SCRIPT", "triggerId": "EXTENSIBILITY_POINT_NAME" }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -85,7 +93,7 @@ func main() { url := "https://{yourDomain}/api/v2/hooks" - payload := strings.NewReader("{ \"name\": \"HOOK_NAME\", \"script\": \"HOOK_SCRIPT\", \"triggerId\": \"EXTENSIBILITY_POINT_NAME\" }") + payload := strings.NewReader("{ "name": "HOOK_NAME", "script": "HOOK_SCRIPT", "triggerId": "EXTENSIBILITY_POINT_NAME" }") req, _ := http.NewRequest("POST", url, payload) @@ -101,14 +109,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/hooks") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/hooks") .header("content-type", "application/json") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ \"name\": \"HOOK_NAME\", \"script\": \"HOOK_SCRIPT\", \"triggerId\": \"EXTENSIBILITY_POINT_NAME\" }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "name": "HOOK_NAME", "script": "HOOK_SCRIPT", "triggerId": "EXTENSIBILITY_POINT_NAME" }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -129,8 +141,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @@ -158,8 +172,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/hooks", @@ -169,7 +185,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{ \"name\": \"HOOK_NAME\", \"script\": \"HOOK_SCRIPT\", \"triggerId\": \"EXTENSIBILITY_POINT_NAME\" }", + CURLOPT_POSTFIELDS => "{ "name": "HOOK_NAME", "script": "HOOK_SCRIPT", "triggerId": "EXTENSIBILITY_POINT_NAME" }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "cache-control: no-cache", @@ -186,12 +202,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"name\": \"HOOK_NAME\", \"script\": \"HOOK_SCRIPT\", \"triggerId\": \"EXTENSIBILITY_POINT_NAME\" }" +payload = "{ "name": "HOOK_NAME", "script": "HOOK_SCRIPT", "triggerId": "EXTENSIBILITY_POINT_NAME" }" headers = { 'content-type': "application/json", @@ -204,12 +222,14 @@ conn.request("POST", "/{yourDomain}/api/v2/hooks", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `import http.client +print(data.decode("utf-8")) +``` +```ruby Ruby +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"name\": \"HOOK_NAME\", \"script\": \"HOOK_SCRIPT\", \"triggerId\": \"EXTENSIBILITY_POINT_NAME\" }" +payload = "{ "name": "HOOK_NAME", "script": "HOOK_SCRIPT", "triggerId": "EXTENSIBILITY_POINT_NAME" }" headers = { 'content-type': "application/json", @@ -222,8 +242,10 @@ conn.request("POST", "/{yourDomain}/api/v2/hooks", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample10 = `import Foundation +print(data.decode("utf-8")) +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -255,20 +277,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
diff --git a/main/docs/customize/hooks/delete-hooks.mdx b/main/docs/customize/hooks/delete-hooks.mdx index 4351d9eca..2e8c61306 100644 --- a/main/docs/customize/hooks/delete-hooks.mdx +++ b/main/docs/customize/hooks/delete-hooks.mdx @@ -11,6 +11,8 @@ title: Delete Hooks --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + The End of Life (EOL) date of Rules and Hooks will be **November 18, 2026**, and they are no longer available to new tenants created as of **October 16, 2023**. Existing tenants with active Hooks will retain Hooks product access through end of life. @@ -42,14 +44,20 @@ When you no longer need hooks, you can delete them using either the Dashboard or Make a `DELETE` call to the [Delete a Hook endpoint](https://auth0.com/docs/api/management/v2/#!/Hooks/delete_hooks_by_id). Be sure to replace `HOOK_ID` and `MGMT_API_ACCESS_TOKEN` placeholder values with your hook ID and Management API access token, respectively. -export const codeExample1 = `curl --request DELETE \ + +```bash cURL +curl --request DELETE \ --url 'https://{yourDomain}/api/v2/hooks/HOOK_ID' \ - --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/hooks/HOOK_ID"); + --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/hooks/HOOK_ID"); var request = new RestRequest(Method.DELETE); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -73,11 +81,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.delete("https://{yourDomain}/api/v2/hooks/HOOK_ID") +} +``` +```java Java +HttpResponse response = Unirest.delete("https://{yourDomain}/api/v2/hooks/HOOK_ID") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'DELETE', @@ -89,8 +101,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN" }; @@ -110,8 +124,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/hooks/HOOK_ID", @@ -135,8 +151,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -147,8 +165,10 @@ conn.request("DELETE", "/{yourDomain}/api/v2/hooks/HOOK_ID", headers=headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -162,8 +182,10 @@ request = Net::HTTP::Delete.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer MGMT_API_ACCESS_TOKEN"] @@ -183,20 +205,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
diff --git a/main/docs/customize/hooks/enable-disable-hooks.mdx b/main/docs/customize/hooks/enable-disable-hooks.mdx index 8439c3c55..2c9a4ff10 100644 --- a/main/docs/customize/hooks/enable-disable-hooks.mdx +++ b/main/docs/customize/hooks/enable-disable-hooks.mdx @@ -12,6 +12,8 @@ title: Enable/Disable Hooks --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + The End of Life (EOL) date of Rules and Hooks will be **November 18, 2026**, and they are no longer available to new tenants created as of **October 16, 2023**. Existing tenants with active Hooks will retain Hooks product access through end of life. @@ -60,20 +62,26 @@ A green dot will appear next to the name of any enabled Hooks. Make a `PATCH` call to the [Update a Hook endpoint](https://auth0.com/docs/api/management/v2/#!/Hooks/patch_hooks_by_id). Be sure to replace `HOOK_ID` and `MGMT_API_ACCESS_TOKEN` placeholder values with your Hook ID and Management API Access Token, respectively. -export const codeExample1 = `curl --request PATCH \ + +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/hooks/HOOK_ID' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{ "enabled": "true" }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/hooks/HOOK_ID"); + --data '{ "enabled": "true" }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/hooks/HOOK_ID"); var request = new RestRequest(Method.PATCH); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{ \"enabled\": \"true\" }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "enabled": "true" }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -86,7 +94,7 @@ func main() { url := "https://{yourDomain}/api/v2/hooks/HOOK_ID" - payload := strings.NewReader("{ \"enabled\": \"true\" }") + payload := strings.NewReader("{ "enabled": "true" }") req, _ := http.NewRequest("PATCH", url, payload) @@ -102,14 +110,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/hooks/HOOK_ID") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/hooks/HOOK_ID") .header("content-type", "application/json") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ \"enabled\": \"true\" }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "enabled": "true" }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -126,8 +138,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @@ -153,8 +167,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/hooks/HOOK_ID", @@ -164,7 +180,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{ \"enabled\": \"true\" }", + CURLOPT_POSTFIELDS => "{ "enabled": "true" }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "cache-control: no-cache", @@ -181,12 +197,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"enabled\": \"true\" }" +payload = "{ "enabled": "true" }" headers = { 'content-type': "application/json", @@ -199,8 +217,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/hooks/HOOK_ID", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -214,11 +234,13 @@ request = Net::HTTP::Patch.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ \"enabled\": \"true\" }" +request.body = "{ "enabled": "true" }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -246,20 +268,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
diff --git a/main/docs/customize/hooks/hook-secrets/create-hook-secrets.mdx b/main/docs/customize/hooks/hook-secrets/create-hook-secrets.mdx index 5739397ff..7c236d5d6 100644 --- a/main/docs/customize/hooks/hook-secrets/create-hook-secrets.mdx +++ b/main/docs/customize/hooks/hook-secrets/create-hook-secrets.mdx @@ -14,6 +14,8 @@ title: Create Hook Secrets --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + The End of Life (EOL) date of Rules and Hooks will be **November 18, 2026**, and they are no longer available to new tenants created as of **October 16, 2023**. Existing tenants with active Hooks will retain Hooks product access through end of life. @@ -55,20 +57,26 @@ You may create up to 20 secrets for any given Hook. Make a `POST` call to the [Add Hook Secrets endpoint](https://auth0.com/docs/api/management/v2/#!/Hooks/post_secrets). Be sure to replace `MGMT_API_ACCESS_TOKEN`, `HOOK_ID`, `HOOK_SECRET_KEY`, and `HOOK_SECRET_VALUE` placeholder values with your Management API Access Token, Hook ID, and Hook key-value pair(s), respectively. -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/api/v2/hooks/HOOK_ID/secrets' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{ [ "HOOK_SECRET_KEY", "HOOK_SECRET_VALUE" ], [ "HOOK_SECRET_KEY", "HOOK_SECRET_VALUE" ] }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/hooks/HOOK_ID/secrets"); + --data '{ [ "HOOK_SECRET_KEY", "HOOK_SECRET_VALUE" ], [ "HOOK_SECRET_KEY", "HOOK_SECRET_VALUE" ] }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/hooks/HOOK_ID/secrets"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{ [ \"HOOK_SECRET_KEY\", \"HOOK_SECRET_VALUE\" ], [ \"HOOK_SECRET_KEY\", \"HOOK_SECRET_VALUE\" ] }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ [ "HOOK_SECRET_KEY", "HOOK_SECRET_VALUE" ], [ "HOOK_SECRET_KEY", "HOOK_SECRET_VALUE" ] }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -81,7 +89,7 @@ func main() { url := "https://{yourDomain}/api/v2/hooks/HOOK_ID/secrets" - payload := strings.NewReader("{ [ \"HOOK_SECRET_KEY\", \"HOOK_SECRET_VALUE\" ], [ \"HOOK_SECRET_KEY\", \"HOOK_SECRET_VALUE\" ] }") + payload := strings.NewReader("{ [ "HOOK_SECRET_KEY", "HOOK_SECRET_VALUE" ], [ "HOOK_SECRET_KEY", "HOOK_SECRET_VALUE" ] }") req, _ := http.NewRequest("POST", url, payload) @@ -97,14 +105,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/hooks/HOOK_ID/secrets") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/hooks/HOOK_ID/secrets") .header("content-type", "application/json") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ [ \"HOOK_SECRET_KEY\", \"HOOK_SECRET_VALUE\" ], [ \"HOOK_SECRET_KEY\", \"HOOK_SECRET_VALUE\" ] }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ [ "HOOK_SECRET_KEY", "HOOK_SECRET_VALUE" ], [ "HOOK_SECRET_KEY", "HOOK_SECRET_VALUE" ] }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -121,8 +133,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @@ -147,8 +161,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/hooks/HOOK_ID/secrets", @@ -158,7 +174,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{ [ \"HOOK_SECRET_KEY\", \"HOOK_SECRET_VALUE\" ], [ \"HOOK_SECRET_KEY\", \"HOOK_SECRET_VALUE\" ] }", + CURLOPT_POSTFIELDS => "{ [ "HOOK_SECRET_KEY", "HOOK_SECRET_VALUE" ], [ "HOOK_SECRET_KEY", "HOOK_SECRET_VALUE" ] }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "cache-control: no-cache", @@ -175,12 +191,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ [ \"HOOK_SECRET_KEY\", \"HOOK_SECRET_VALUE\" ], [ \"HOOK_SECRET_KEY\", \"HOOK_SECRET_VALUE\" ] }" +payload = "{ [ "HOOK_SECRET_KEY", "HOOK_SECRET_VALUE" ], [ "HOOK_SECRET_KEY", "HOOK_SECRET_VALUE" ] }" headers = { 'content-type': "application/json", @@ -193,8 +211,10 @@ conn.request("POST", "/{yourDomain}/api/v2/hooks/HOOK_ID/secrets", payload, head res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -208,11 +228,13 @@ request = Net::HTTP::Post.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ [ \"HOOK_SECRET_KEY\", \"HOOK_SECRET_VALUE\" ], [ \"HOOK_SECRET_KEY\", \"HOOK_SECRET_VALUE\" ] }" +request.body = "{ [ "HOOK_SECRET_KEY", "HOOK_SECRET_VALUE" ], [ "HOOK_SECRET_KEY", "HOOK_SECRET_VALUE" ] }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -239,20 +261,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
diff --git a/main/docs/customize/hooks/hook-secrets/delete-hook-secrets.mdx b/main/docs/customize/hooks/hook-secrets/delete-hook-secrets.mdx index 184fa141f..ae5a103e4 100644 --- a/main/docs/customize/hooks/hook-secrets/delete-hook-secrets.mdx +++ b/main/docs/customize/hooks/hook-secrets/delete-hook-secrets.mdx @@ -14,6 +14,8 @@ title: Delete Hook Secrets --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + The End of Life (EOL) date of Rules and Hooks will be **November 18, 2026**, and they are no longer available to new tenants created as of **October 16, 2023**. Existing tenants with active Hooks will retain Hooks product access through end of life. @@ -48,16 +50,22 @@ Hook Secrets can also be imported and exported using the [Deploy Command-Line In Make a `DELETE` call to the [Delete Hook Secrets endpoint](https://auth0.com/docs/api/management/v2/#!/Hooks/delete_secrets). Be sure to replace `HOOK_ID`, `HOOK_SECRET_NAME`, and `MGMT_API_ACCESS_TOKEN` placeholder values with your Hook ID, your Hook Secret name(s), and Management API access token, respectively. -export const codeExample1 = `curl --request DELETE \ + +```bash cURL +curl --request DELETE \ --url 'https://{yourDomain}/api/v2/hooks/HOOK_ID/secrets' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ - --data '{ [ "HOOK_SECRET_NAME", "HOOK_SECRET_NAME" ] }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/hooks/HOOK_ID/secrets"); + --data '{ [ "HOOK_SECRET_NAME", "HOOK_SECRET_NAME" ] }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/hooks/HOOK_ID/secrets"); var request = new RestRequest(Method.DELETE); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); -request.AddParameter("undefined", "{ [ \"HOOK_SECRET_NAME\", \"HOOK_SECRET_NAME\" ] }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("undefined", "{ [ "HOOK_SECRET_NAME", "HOOK_SECRET_NAME" ] }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -70,7 +78,7 @@ func main() { url := "https://{yourDomain}/api/v2/hooks/HOOK_ID/secrets" - payload := strings.NewReader("{ [ \"HOOK_SECRET_NAME\", \"HOOK_SECRET_NAME\" ] }") + payload := strings.NewReader("{ [ "HOOK_SECRET_NAME", "HOOK_SECRET_NAME" ] }") req, _ := http.NewRequest("DELETE", url, payload) @@ -84,12 +92,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.delete("https://{yourDomain}/api/v2/hooks/HOOK_ID/secrets") +} +``` +```java Java +HttpResponse response = Unirest.delete("https://{yourDomain}/api/v2/hooks/HOOK_ID/secrets") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") - .body("{ [ \"HOOK_SECRET_NAME\", \"HOOK_SECRET_NAME\" ] }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ [ "HOOK_SECRET_NAME", "HOOK_SECRET_NAME" ] }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'DELETE', @@ -102,8 +114,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN" }; @@ -126,8 +140,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/hooks/HOOK_ID/secrets", @@ -137,7 +153,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "DELETE", - CURLOPT_POSTFIELDS => "{ [ \"HOOK_SECRET_NAME\", \"HOOK_SECRET_NAME\" ] }", + CURLOPT_POSTFIELDS => "{ [ "HOOK_SECRET_NAME", "HOOK_SECRET_NAME" ] }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN" ], @@ -152,12 +168,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ [ \"HOOK_SECRET_NAME\", \"HOOK_SECRET_NAME\" ] }" +payload = "{ [ "HOOK_SECRET_NAME", "HOOK_SECRET_NAME" ] }" headers = { 'authorization': "Bearer MGMT_API_ACCESS_TOKEN" } @@ -166,8 +184,10 @@ conn.request("DELETE", "/{yourDomain}/api/v2/hooks/HOOK_ID/secrets", payload, he res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -179,11 +199,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Delete.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' -request.body = "{ [ \"HOOK_SECRET_NAME\", \"HOOK_SECRET_NAME\" ] }" +request.body = "{ [ "HOOK_SECRET_NAME", "HOOK_SECRET_NAME" ] }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer MGMT_API_ACCESS_TOKEN"] @@ -206,20 +228,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
diff --git a/main/docs/customize/hooks/hook-secrets/update-hook-secrets.mdx b/main/docs/customize/hooks/hook-secrets/update-hook-secrets.mdx index 2077ef2cb..a4e8278a3 100644 --- a/main/docs/customize/hooks/hook-secrets/update-hook-secrets.mdx +++ b/main/docs/customize/hooks/hook-secrets/update-hook-secrets.mdx @@ -14,6 +14,8 @@ title: Update Hook Secrets --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + The End of Life (EOL) date of Rules and Hooks will be **November 18, 2026**, and they are no longer available to new tenants created as of **October 16, 2023**. Existing tenants with active Hooks will retain Hooks product access through end of life. @@ -49,20 +51,26 @@ Hook Secrets may also be imported and exported using the Deploy Command-Line Int Make a `PATCH` call to the [Update Hook Secrets endpoint](https://auth0.com/docs/api/management/v2/#!/Hooks/patch_secrets). Be sure to replace `HOOK_ID` and `MGMT_API_ACCESS_TOKEN` placeholder values with your hook ID and Management API Access Token, respectively. -export const codeExample1 = `curl --request PATCH \ + +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/hooks/HOOK_ID/secrets' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{ [ "HOOK_SECRET_KEY", "HOOK_SECRET_VALUE" ], [ "HOOK_SECRET_KEY", "HOOK_SECRET_VALUE" ] }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/hooks/HOOK_ID/secrets"); + --data '{ [ "HOOK_SECRET_KEY", "HOOK_SECRET_VALUE" ], [ "HOOK_SECRET_KEY", "HOOK_SECRET_VALUE" ] }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/hooks/HOOK_ID/secrets"); var request = new RestRequest(Method.PATCH); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{ [ \"HOOK_SECRET_KEY\", \"HOOK_SECRET_VALUE\" ], [ \"HOOK_SECRET_KEY\", \"HOOK_SECRET_VALUE\" ] }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ [ "HOOK_SECRET_KEY", "HOOK_SECRET_VALUE" ], [ "HOOK_SECRET_KEY", "HOOK_SECRET_VALUE" ] }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -75,7 +83,7 @@ func main() { url := "https://{yourDomain}/api/v2/hooks/HOOK_ID/secrets" - payload := strings.NewReader("{ [ \"HOOK_SECRET_KEY\", \"HOOK_SECRET_VALUE\" ], [ \"HOOK_SECRET_KEY\", \"HOOK_SECRET_VALUE\" ] }") + payload := strings.NewReader("{ [ "HOOK_SECRET_KEY", "HOOK_SECRET_VALUE" ], [ "HOOK_SECRET_KEY", "HOOK_SECRET_VALUE" ] }") req, _ := http.NewRequest("PATCH", url, payload) @@ -91,14 +99,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/hooks/HOOK_ID/secrets") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/hooks/HOOK_ID/secrets") .header("content-type", "application/json") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ [ \"HOOK_SECRET_KEY\", \"HOOK_SECRET_VALUE\" ], [ \"HOOK_SECRET_KEY\", \"HOOK_SECRET_VALUE\" ] }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ [ "HOOK_SECRET_KEY", "HOOK_SECRET_VALUE" ], [ "HOOK_SECRET_KEY", "HOOK_SECRET_VALUE" ] }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -115,8 +127,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @@ -141,8 +155,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/hooks/HOOK_ID/secrets", @@ -152,7 +168,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{ [ \"HOOK_SECRET_KEY\", \"HOOK_SECRET_VALUE\" ], [ \"HOOK_SECRET_KEY\", \"HOOK_SECRET_VALUE\" ] }", + CURLOPT_POSTFIELDS => "{ [ "HOOK_SECRET_KEY", "HOOK_SECRET_VALUE" ], [ "HOOK_SECRET_KEY", "HOOK_SECRET_VALUE" ] }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "cache-control: no-cache", @@ -169,12 +185,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ [ \"HOOK_SECRET_KEY\", \"HOOK_SECRET_VALUE\" ], [ \"HOOK_SECRET_KEY\", \"HOOK_SECRET_VALUE\" ] }" +payload = "{ [ "HOOK_SECRET_KEY", "HOOK_SECRET_VALUE" ], [ "HOOK_SECRET_KEY", "HOOK_SECRET_VALUE" ] }" headers = { 'content-type': "application/json", @@ -187,8 +205,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/hooks/HOOK_ID/secrets", payload, hea res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -202,11 +222,13 @@ request = Net::HTTP::Patch.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ [ \"HOOK_SECRET_KEY\", \"HOOK_SECRET_VALUE\" ], [ \"HOOK_SECRET_KEY\", \"HOOK_SECRET_VALUE\" ] }" +request.body = "{ [ "HOOK_SECRET_KEY", "HOOK_SECRET_VALUE" ], [ "HOOK_SECRET_KEY", "HOOK_SECRET_VALUE" ] }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -233,20 +255,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
diff --git a/main/docs/customize/hooks/hook-secrets/view-hook-secrets.mdx b/main/docs/customize/hooks/hook-secrets/view-hook-secrets.mdx index 134c67f67..823395d7e 100644 --- a/main/docs/customize/hooks/hook-secrets/view-hook-secrets.mdx +++ b/main/docs/customize/hooks/hook-secrets/view-hook-secrets.mdx @@ -12,6 +12,8 @@ title: View Hook Secrets --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + The End of Life (EOL) date of Rules and Hooks will be **November 18, 2026**, and they are no longer available to new tenants created as of **October 16, 2023**. Existing tenants with active Hooks will retain Hooks product access through end of life. @@ -45,14 +47,20 @@ All configured secrets for the selected Hook are listed. Make a `GET` call to the [Get Hook Secrets endpoint](https://auth0.com/docs/api/management/v2/#!/Hooks/get_secrets). Be sure to replace `HOOK_ID` and `MGMT_API_ACCESS_TOKEN` placeholder values with your Hook's ID and the Management API Access Token, respectively. -export const codeExample1 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/hooks/HOOK_ID/secrets' \ - --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/hooks/HOOK_ID/secrets"); + --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/hooks/HOOK_ID/secrets"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -76,11 +84,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/hooks/HOOK_ID/secrets") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/hooks/HOOK_ID/secrets") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -92,8 +104,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN" }; @@ -113,8 +127,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/hooks/HOOK_ID/secrets", @@ -138,8 +154,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -150,8 +168,10 @@ conn.request("GET", "/{yourDomain}/api/v2/hooks/HOOK_ID/secrets", headers=header res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -165,8 +185,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer MGMT_API_ACCESS_TOKEN"] @@ -186,20 +208,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
diff --git a/main/docs/customize/hooks/update-hooks.mdx b/main/docs/customize/hooks/update-hooks.mdx index edee0ecfb..ca6a5244d 100644 --- a/main/docs/customize/hooks/update-hooks.mdx +++ b/main/docs/customize/hooks/update-hooks.mdx @@ -12,6 +12,8 @@ title: Update Hooks --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + The End of Life (EOL) date of Rules and Hooks will be **November 18, 2026**, and they are no longer available to new tenants created as of **October 16, 2023**. Existing tenants with active Hooks will retain Hooks product access through end of life. @@ -63,20 +65,26 @@ Optionally, you can add secrets (such as Twilio Keys or database connection stri Make a `PATCH` call to the [Update a Hook endpoint](https://auth0.com/docs/api/management/v2/#!/Hooks/patch_hooks_by_id). Be sure to replace `HOOK_ID` and `MGMT_API_ACCESS_TOKEN` placeholder values with your Hook ID and Management API Access Token, respectively. -export const codeExample1 = `curl --request PATCH \ + +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/hooks/HOOK_ID' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{ "name": "HOOK_NAME", "script": "HOOK_SCRIPT", "enabled": "true" }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/hooks/HOOK_ID"); + --data '{ "name": "HOOK_NAME", "script": "HOOK_SCRIPT", "enabled": "true" }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/hooks/HOOK_ID"); var request = new RestRequest(Method.PATCH); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{ \"name\": \"HOOK_NAME\", \"script\": \"HOOK_SCRIPT\", \"enabled\": \"true\" }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "name": "HOOK_NAME", "script": "HOOK_SCRIPT", "enabled": "true" }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -89,7 +97,7 @@ func main() { url := "https://{yourDomain}/api/v2/hooks/HOOK_ID" - payload := strings.NewReader("{ \"name\": \"HOOK_NAME\", \"script\": \"HOOK_SCRIPT\", \"enabled\": \"true\" }") + payload := strings.NewReader("{ "name": "HOOK_NAME", "script": "HOOK_SCRIPT", "enabled": "true" }") req, _ := http.NewRequest("PATCH", url, payload) @@ -105,14 +113,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/hooks/HOOK_ID") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/hooks/HOOK_ID") .header("content-type", "application/json") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ \"name\": \"HOOK_NAME\", \"script\": \"HOOK_SCRIPT\", \"enabled\": \"true\" }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "name": "HOOK_NAME", "script": "HOOK_SCRIPT", "enabled": "true" }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -129,8 +141,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @@ -158,8 +172,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/hooks/HOOK_ID", @@ -169,7 +185,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{ \"name\": \"HOOK_NAME\", \"script\": \"HOOK_SCRIPT\", \"enabled\": \"true\" }", + CURLOPT_POSTFIELDS => "{ "name": "HOOK_NAME", "script": "HOOK_SCRIPT", "enabled": "true" }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "cache-control: no-cache", @@ -186,12 +202,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"name\": \"HOOK_NAME\", \"script\": \"HOOK_SCRIPT\", \"enabled\": \"true\" }" +payload = "{ "name": "HOOK_NAME", "script": "HOOK_SCRIPT", "enabled": "true" }" headers = { 'content-type': "application/json", @@ -204,8 +222,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/hooks/HOOK_ID", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -219,11 +239,13 @@ request = Net::HTTP::Patch.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ \"name\": \"HOOK_NAME\", \"script\": \"HOOK_SCRIPT\", \"enabled\": \"true\" }" +request.body = "{ "name": "HOOK_NAME", "script": "HOOK_SCRIPT", "enabled": "true" }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -255,20 +277,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
diff --git a/main/docs/customize/hooks/view-hooks.mdx b/main/docs/customize/hooks/view-hooks.mdx index e867dc4b6..605d9ff6a 100644 --- a/main/docs/customize/hooks/view-hooks.mdx +++ b/main/docs/customize/hooks/view-hooks.mdx @@ -12,6 +12,8 @@ title: View Hooks --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + The End of Life (EOL) date of Rules and Hooks will be **November 18, 2026**, and they are no longer available to new tenants created as of **October 16, 2023**. Existing tenants with active Hooks will retain Hooks product access through end of life. @@ -44,14 +46,20 @@ All configured hooks are listed by the extensibility point at which they are exe Make a `GET` call to the [Get Hooks endpoint](https://auth0.com/docs/api/management/v2/#!/Hooks/get_hooks). Be sure to replace `MGMT_API_ACCESS_TOKEN` placeholder value with your Management API access token. -export const codeExample1 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/hooks' \ - --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/hooks"); + --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/hooks"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -75,11 +83,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/hooks") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/hooks") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -91,8 +103,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN" }; @@ -112,8 +126,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/hooks", @@ -137,8 +153,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -149,8 +167,10 @@ conn.request("GET", "/{yourDomain}/api/v2/hooks", headers=headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -164,8 +184,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer MGMT_API_ACCESS_TOKEN"] @@ -185,20 +207,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
diff --git a/main/docs/customize/integrations/aws/aws-api-gateway-custom-authorizers.mdx b/main/docs/customize/integrations/aws/aws-api-gateway-custom-authorizers.mdx index 602d3c95d..60acae05b 100644 --- a/main/docs/customize/integrations/aws/aws-api-gateway-custom-authorizers.mdx +++ b/main/docs/customize/integrations/aws/aws-api-gateway-custom-authorizers.mdx @@ -11,6 +11,8 @@ title: Secure AWS API Gateway Endpoints Using Custom Authorizers --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + Secure AWS API Gateway endpoints using custom authorizers that accept Auth0-issued access tokens. To do this, you configure your API with API Gateway, create and configure your AWS Lambda functions (including the custom authorizers) to secure your API endpoints, and implement the authorization flow so that your users can retrieve the access tokens needed to gain access to your API from Auth0. To learn more, visit [AWS Lambda Overview](https://aws.amazon.com/lambda/) once you log into your [AWS API Gateway](https://aws.amazon.com/api-gateway/). @@ -520,7 +522,7 @@ To test your deployment, make a `GET` call to the **Invoke URL** you noted in th For details, see [Get Access Tokens](/docs/secure/tokens/access-tokens/get-access-tokens). - + ```bash cURL lines curl --request GET \ --url https://%7ByourInvokeUrl%7D/pets @@ -666,4 +668,4 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - \ No newline at end of file + \ No newline at end of file diff --git a/main/docs/customize/integrations/google-cloud-endpoints.mdx b/main/docs/customize/integrations/google-cloud-endpoints.mdx index 4125fdf12..b9a420268 100644 --- a/main/docs/customize/integrations/google-cloud-endpoints.mdx +++ b/main/docs/customize/integrations/google-cloud-endpoints.mdx @@ -10,6 +10,8 @@ title: Secure Google Cloud Endpoints with Auth0 --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + [Google Cloud Endpoints (GCE)](https://cloud.google.com/endpoints/) is an API management system providing features to help you create, maintain, and secure your APIs. GCE uses [OpenAPI](https://www.openapis.org/) to define your API's endpoints, input and output, errors, and security description. For more information on the OpenAPI spec, see the [OpenAPI Specification](https://github.com/OAI/OpenAPI-Specification) repository on GitHub. @@ -22,7 +24,7 @@ Before you begin you'll need a deployed GCE API. If you haven't already created The quickstart will walk you through creating a simple GCE API with a single endpoint, `/airportName`, that returns the name of an airport from its three-letter [IATA code](https://en.wikipedia.org/wiki/IATA_airport_code). - + ```bash cURL lines curl --request GET \ --url 'https://%7ByourGceProject%7D.appspot.com/airportName?iataCode=SFO' @@ -172,7 +174,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + ## Define the API in Auth0 @@ -345,7 +347,7 @@ cd endpoints-quickstart/scripts Once you've redeployed, call the API again with no security. - + ```bash cURL lines curl --request GET \ --url 'https://%7ByourGceProject%7D.appspot.com/airportName?iataCode=SFO' @@ -495,7 +497,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + You'll get the following response: @@ -524,7 +526,7 @@ Now go to the **Test** page of your Google Endpoints API definition on the [Auth Perform a `GET` request to your API with an Authorization Header of `Bearer {ACCESS_TOKEN}` to obtain authorized access: - + ```bash cURL lines curl --request GET \ --url 'https://%7ByourGceProject%7D.appspot.com/airportName?iataCode=SFO' \ @@ -692,6 +694,6 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + And that's it! \ No newline at end of file diff --git a/main/docs/customize/integrations/marketing-tool-integrations/marketo.mdx b/main/docs/customize/integrations/marketing-tool-integrations/marketo.mdx index c80e1d8b0..602ca9c3d 100644 --- a/main/docs/customize/integrations/marketing-tool-integrations/marketo.mdx +++ b/main/docs/customize/integrations/marketing-tool-integrations/marketo.mdx @@ -9,6 +9,9 @@ title: Export User Data to Marketo Marketo. 'twitter:title': Export User Data to Marketo --- + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + In this article, you’ll learn how to export user data in Auth0 to a CSV file then import it into Marketo using the [Bulk Leads endpoint](http://developers.marketo.com/rest-api/endpoint-reference/lead-database-endpoint-reference/#/Bulk_Leads) of the Marketo REST API. ## Create a user data file @@ -53,7 +56,7 @@ Before you get started, you can find more information by visiting [Marketo Docum To import the user data file to Marketo, perform a POST request to the [Bulk Leads endpoint](http://developers.marketo.com/rest-api/endpoint-reference/lead-database-endpoint-reference/#/Bulk_Leads). Set the content-type header of the request to `multipart/form-data` and include a `file` parameter with your exported CSV file as well as format parameter set to `csv`. For example: - + ```bash cURL lines curl --request POST \ --url https://marketo_rest_api_base_url/bulk/v1/leads.json \ @@ -305,7 +308,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + The response should look something like this: @@ -327,7 +330,7 @@ The response should look something like this: You can check the status of your import using the [Get Import Lead Status API](/docs/) and your import job's `batchId`. For example: - + ```bash cURL lines curl --request GET \ --url https://marketo_rest_api_base_url/bulk/v1/leads/batch/BATCH_ID.json \ @@ -494,7 +497,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + And the response: diff --git a/main/docs/customize/internationalization-and-localization/universal-login-internationalization.mdx b/main/docs/customize/internationalization-and-localization/universal-login-internationalization.mdx index 84dbdafb4..8fbf047c9 100644 --- a/main/docs/customize/internationalization-and-localization/universal-login-internationalization.mdx +++ b/main/docs/customize/internationalization-and-localization/universal-login-internationalization.mdx @@ -11,6 +11,8 @@ title: Universal Login Internationalization --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + ## Universal Login localization The Universal Login experience is localized to the following languages. Entries marked with an asterisk are read right to left. @@ -356,27 +358,28 @@ To add a language that's not listed above, use the response = Unirest.patch("https://{yourDomain}/api/v2/tenants/settings") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/tenants/settings") .header("content-type", "application/json") .header("authorization", "Bearer API2_ACCESS_TOKEN") - .body("{ \"enabled_locales\" : [ \"en\", \"es\"]}") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "enabled_locales" : [ "en", "es"]}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -423,8 +430,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer API2_ACCESS_TOKEN" }; @@ -449,8 +458,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/tenants/settings", @@ -460,7 +471,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{ \"enabled_locales\" : [ \"en\", \"es\"]}", + CURLOPT_POSTFIELDS => "{ "enabled_locales" : [ "en", "es"]}", CURLOPT_HTTPHEADER => [ "authorization: Bearer API2_ACCESS_TOKEN", "content-type: application/json" @@ -476,12 +487,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"enabled_locales\" : [ \"en\", \"es\"]}" +payload = "{ "enabled_locales" : [ "en", "es"]}" headers = { 'content-type': "application/json", @@ -493,8 +506,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/tenants/settings", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -507,11 +522,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Patch.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer API2_ACCESS_TOKEN' -request.body = "{ \"enabled_locales\" : [ \"en\", \"es\"]}" +request.body = "{ "enabled_locales" : [ "en", "es"]}" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -538,20 +555,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ### Right-to-left languages @@ -568,11 +574,6 @@ Right-to-left (RtL) language support allows your tenant to display Arabic (stand ``` - - - - - Go to [Tenant Settings > Advanced](https://manage.auth0.com/#/tenant/advanced) and ensure the toggle shown below is disabled, then test any RtL languages in a dev environment with a custom page template before using them in production. To learn more, read [Customize Universal Login Page Templates](/docs/customize/login-pages/universal-login/customize-templates). ![A photo of the right-to-left toggle in the Auth0 Tenant Settings.](/docs/images/screenshot.png) diff --git a/main/docs/customize/login-pages/custom-error-pages.mdx b/main/docs/customize/login-pages/custom-error-pages.mdx index 1c4c5fbe4..8e407d95d 100644 --- a/main/docs/customize/login-pages/custom-error-pages.mdx +++ b/main/docs/customize/login-pages/custom-error-pages.mdx @@ -12,6 +12,8 @@ title: Customize Error Pages --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + When an authorization error occurs, and your callback URL is valid, the Authorization Server returns the appropriate error and state parameters to your callback URL. If your callback URL is invalid, your application will display the [default Auth0 error page](/docs/authenticate/login/auth0-universal-login/error-pages). Your application may also display the default Auth0 error page for reasons other than an invalid callback URL, such as: @@ -80,18 +82,24 @@ Use the Dashboard to configure Auth0 to redirect users to a custom error page: Use the Management API [Update Tenant Settings](https://auth0.com/docs/api/management/v2/#!/Tenants/patch_settings) endpoint. Replace the `{mgmtApiAccessToken}` placeholder value with your Management API Access Token, and update the value of the `url` field in the JSON body to point to the location of the error page. -export const codeExample1 = `curl --request PATCH \ + +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/tenants/settings' \ --header 'authorization: Bearer {mgmtApiAccessToken}' \ --header 'content-type: application/json' \ - --data '{"error_page": {"html": "", "show_log_link":false, "url": "http://www.example.com"}}'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/tenants/settings"); + --data '{"error_page": {"html": "", "show_log_link":false, "url": "http://www.example.com"}}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/tenants/settings"); var request = new RestRequest(Method.PATCH); request.AddHeader("authorization", "Bearer {mgmtApiAccessToken}"); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\"error_page\": {\"html\": \"\", \"show_log_link\":false, \"url\": \"http://www.example.com\"}}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{"error_page": {"html": "", "show_log_link":false, "url": "http://www.example.com"}}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -104,7 +112,7 @@ func main() { url := "https://{yourDomain}/api/v2/tenants/settings" - payload := strings.NewReader("{\"error_page\": {\"html\": \"\", \"show_log_link\":false, \"url\": \"http://www.example.com\"}}") + payload := strings.NewReader("{"error_page": {"html": "", "show_log_link":false, "url": "http://www.example.com"}}") req, _ := http.NewRequest("PATCH", url, payload) @@ -119,13 +127,17 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/tenants/settings") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/tenants/settings") .header("authorization", "Bearer {mgmtApiAccessToken}") .header("content-type", "application/json") - .body("{\"error_page\": {\"html\": \"\", \"show_log_link\":false, \"url\": \"http://www.example.com\"}}") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{"error_page": {"html": "", "show_log_link":false, "url": "http://www.example.com"}}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -141,8 +153,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer {mgmtApiAccessToken}", @"content-type": @"application/json" }; @@ -167,8 +181,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/tenants/settings", @@ -178,7 +194,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{\"error_page\": {\"html\": \"\", \"show_log_link\":false, \"url\": \"http://www.example.com\"}}", + CURLOPT_POSTFIELDS => "{"error_page": {"html": "", "show_log_link":false, "url": "http://www.example.com"}}", CURLOPT_HTTPHEADER => [ "authorization: Bearer {mgmtApiAccessToken}", "content-type: application/json" @@ -194,12 +210,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"error_page\": {\"html\": \"\", \"show_log_link\":false, \"url\": \"http://www.example.com\"}}" +payload = "{"error_page": {"html": "", "show_log_link":false, "url": "http://www.example.com"}}" headers = { 'authorization': "Bearer {mgmtApiAccessToken}", @@ -211,8 +229,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/tenants/settings", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -225,11 +245,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Patch.new(url) request["authorization"] = 'Bearer {mgmtApiAccessToken}' request["content-type"] = 'application/json' -request.body = "{\"error_page\": {\"html\": \"\", \"show_log_link\":false, \"url\": \"http://www.example.com\"}}" +request.body = "{"error_page": {"html": "", "show_log_link":false, "url": "http://www.example.com"}}" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "authorization": "Bearer {mgmtApiAccessToken}", @@ -260,20 +282,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
@@ -316,7 +327,7 @@ You can use Liquid syntax to include the following variables: * `{error_description}` * `{tracking}` - + ```bash cURL lines curl --request PATCH \ --url https://login.auth0.com/api/v2/tenants/settings \ @@ -532,7 +543,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - +
diff --git a/main/docs/customize/login-pages/customize-consent-prompts.mdx b/main/docs/customize/login-pages/customize-consent-prompts.mdx index 4d46cba2c..068f0ccac 100644 --- a/main/docs/customize/login-pages/customize-consent-prompts.mdx +++ b/main/docs/customize/login-pages/customize-consent-prompts.mdx @@ -12,6 +12,8 @@ title: Customize Consent Prompts --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + When a third-party application requests scopes, users see a consent prompt. By default, this prompt uses the scope **name** to generate text and groups all scopes for a resource, displaying the resource's actions in a single line. If you require a specialized consent prompt, for example, parental consent, you need to build your own custom consent form. Be aware that laws vary according to country. @@ -31,20 +33,26 @@ This change is made at the tenant level, so it will affect consent prompts for a Set your tenant's **use_scope_descriptions_for_consent** flag to `true` by making the following API call: -export const codeExample1 = `curl --request PATCH \ + +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/tenants/settings' \ --header 'authorization: Bearer API_ACCESS_TOKEN' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{ "flags": { "use_scope_descriptions_for_consent": true } }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/tenants/settings"); + --data '{ "flags": { "use_scope_descriptions_for_consent": true } }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/tenants/settings"); var request = new RestRequest(Method.PATCH); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer API_ACCESS_TOKEN"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{ \"flags\": { \"use_scope_descriptions_for_consent\": true } }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "flags": { "use_scope_descriptions_for_consent": true } }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -57,7 +65,7 @@ func main() { url := "https://{yourDomain}/api/v2/tenants/settings" - payload := strings.NewReader("{ \"flags\": { \"use_scope_descriptions_for_consent\": true } }") + payload := strings.NewReader("{ "flags": { "use_scope_descriptions_for_consent": true } }") req, _ := http.NewRequest("PATCH", url, payload) @@ -73,14 +81,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/tenants/settings") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/tenants/settings") .header("content-type", "application/json") .header("authorization", "Bearer API_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ \"flags\": { \"use_scope_descriptions_for_consent\": true } }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "flags": { "use_scope_descriptions_for_consent": true } }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -97,8 +109,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer API_ACCESS_TOKEN", @@ -124,8 +138,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/tenants/settings", @@ -135,7 +151,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{ \"flags\": { \"use_scope_descriptions_for_consent\": true } }", + CURLOPT_POSTFIELDS => "{ "flags": { "use_scope_descriptions_for_consent": true } }", CURLOPT_HTTPHEADER => [ "authorization: Bearer API_ACCESS_TOKEN", "cache-control: no-cache", @@ -152,12 +168,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"flags\": { \"use_scope_descriptions_for_consent\": true } }" +payload = "{ "flags": { "use_scope_descriptions_for_consent": true } }" headers = { 'content-type': "application/json", @@ -170,8 +188,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/tenants/settings", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -185,11 +205,13 @@ request = Net::HTTP::Patch.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer API_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ \"flags\": { \"use_scope_descriptions_for_consent\": true } }" +request.body = "{ "flags": { "use_scope_descriptions_for_consent": true } }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -217,39 +239,34 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ## Use scope names to generate consent prompt text Set your tenant's **use_scope_descriptions_for_consent** flag to `false` by making the following API call: -export const codeExample11 = `curl --request PATCH \ + +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/tenants/settings' \ --header 'authorization: Bearer API_ACCESS_TOKEN' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{ "flags": { "use_scope_descriptions_for_consent": false } }'`; -export const codeExample12 = `var client = new RestClient("https://{yourDomain}/api/v2/tenants/settings"); + --data '{ "flags": { "use_scope_descriptions_for_consent": false } }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/tenants/settings"); var request = new RestRequest(Method.PATCH); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer API_ACCESS_TOKEN"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{ \"flags\": { \"use_scope_descriptions_for_consent\": false } }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample13 = `package main +request.AddParameter("application/json", "{ "flags": { "use_scope_descriptions_for_consent": false } }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -262,7 +279,7 @@ func main() { url := "https://{yourDomain}/api/v2/tenants/settings" - payload := strings.NewReader("{ \"flags\": { \"use_scope_descriptions_for_consent\": false } }") + payload := strings.NewReader("{ "flags": { "use_scope_descriptions_for_consent": false } }") req, _ := http.NewRequest("PATCH", url, payload) @@ -278,14 +295,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample14 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/tenants/settings") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/tenants/settings") .header("content-type", "application/json") .header("authorization", "Bearer API_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ \"flags\": { \"use_scope_descriptions_for_consent\": false } }") - .asString();`; -export const codeExample15 = `var axios = require("axios").default; + .body("{ "flags": { "use_scope_descriptions_for_consent": false } }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -302,8 +323,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample16 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer API_ACCESS_TOKEN", @@ -329,8 +352,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/tenants/settings", @@ -340,7 +365,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{ \"flags\": { \"use_scope_descriptions_for_consent\": false } }", + CURLOPT_POSTFIELDS => "{ "flags": { "use_scope_descriptions_for_consent": false } }", CURLOPT_HTTPHEADER => [ "authorization: Bearer API_ACCESS_TOKEN", "cache-control: no-cache", @@ -357,12 +382,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"flags\": { \"use_scope_descriptions_for_consent\": false } }" +payload = "{ "flags": { "use_scope_descriptions_for_consent": false } }" headers = { 'content-type': "application/json", @@ -375,8 +402,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/tenants/settings", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -390,11 +419,13 @@ request = Net::HTTP::Patch.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer API_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ \"flags\": { \"use_scope_descriptions_for_consent\": false } }" +request.body = "{ "flags": { "use_scope_descriptions_for_consent": false } }" response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -422,20 +453,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ## Learn more diff --git a/main/docs/customize/login-pages/universal-login/customize-signup-and-login-prompts/connection-switching.mdx b/main/docs/customize/login-pages/universal-login/customize-signup-and-login-prompts/connection-switching.mdx index 23c11a11b..ee5fd887f 100644 --- a/main/docs/customize/login-pages/universal-login/customize-signup-and-login-prompts/connection-switching.mdx +++ b/main/docs/customize/login-pages/universal-login/customize-signup-and-login-prompts/connection-switching.mdx @@ -12,6 +12,8 @@ title: Configure Flexible Connection Switching --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + Flexible connection switching is an optional feature that allows users to choose their method of authentication when logging in to an application. When implemented, your application's login screen presents users with the option to authenticate with either traditional database credentials or a passwordless connection. Users who select a [passwordless connection](/docs/authenticate/passwordless) receive a one-time password (OTP) through email or SMS that they can use to log in to your application. Flexible connection switching uses [custom Universal Login prompts](/docs/customize/login-pages/universal-login/customize-signup-and-login-prompts) to provide users with a more autonomous authentication experience. @@ -70,18 +72,24 @@ In the code samples below, ensure you replace the placeholders with the appropri You can configure the `signup-password` prompt using the [Set partials for a prompt](https://auth0.com/docs/api/management/v2/prompts/put-partials) endpoint: -export const codeExample1 = `curl --request PUT \ + +```bash cURL +curl --request PUT \ --url 'https://{yourDomain}/api/v2/prompts/signup-password/partials' \ --header 'authorization: Bearer {mgmtApiToken}' \ --header 'content-type: application/json' \ - --data '{"signup-password":{"form-footer-start":" Send a secure code by email "}}'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/prompts/signup-password/partials"); + --data '{"signup-password":{"form-footer-start":" Send a secure code by email "}}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/prompts/signup-password/partials"); var request = new RestRequest(Method.PUT); request.AddHeader("authorization", "Bearer {mgmtApiToken}"); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\"signup-password\":{\"form-footer-start\":\" Send a secure code by email \"}}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{"signup-password":{"form-footer-start":" Send a secure code by email "}}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -94,7 +102,7 @@ func main() { url := "https://{yourDomain}/api/v2/prompts/signup-password/partials" - payload := strings.NewReader("{\"signup-password\":{\"form-footer-start\":\"
\"}}") + payload := strings.NewReader("{"signup-password":{"form-footer-start":"
"}}") req, _ := http.NewRequest("PUT", url, payload) @@ -109,13 +117,17 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.put("https://{yourDomain}/api/v2/prompts/signup-password/partials") +} +``` +```java Java +HttpResponse response = Unirest.put("https://{yourDomain}/api/v2/prompts/signup-password/partials") .header("authorization", "Bearer {mgmtApiToken}") .header("content-type", "application/json") - .body("{\"signup-password\":{\"form-footer-start\":\" Send a secure code by email \"}}") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{"signup-password":{"form-footer-start":" Send a secure code by email "}}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PUT', @@ -132,12 +144,14 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer {mgmtApiToken}", @"content-type": @"application/json" }; -NSDictionary *parameters = @{ @"signup-password": @{ @"form-footer-start": @"
" } }; +NSDictionary *parameters = @{ @"signup-password": @{ @"form-footer-start": @"
" } }; NSData *postData = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:nil]; @@ -158,8 +172,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/prompts/signup-password/partials", @@ -169,7 +185,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PUT", - CURLOPT_POSTFIELDS => "{\"signup-password\":{\"form-footer-start\":\"
\"}}", + CURLOPT_POSTFIELDS => "{"signup-password":{"form-footer-start":"
"}}", CURLOPT_HTTPHEADER => [ "authorization: Bearer {mgmtApiToken}", "content-type: application/json" @@ -185,12 +201,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"signup-password\":{\"form-footer-start\":\"
\"}}" +payload = "{"signup-password":{"form-footer-start":"
"}}" headers = { 'authorization': "Bearer {mgmtApiToken}", @@ -202,8 +220,10 @@ conn.request("PUT", "/{yourDomain}/api/v2/prompts/signup-password/partials", pay res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -216,17 +236,19 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Put.new(url) request["authorization"] = 'Bearer {mgmtApiToken}' request["content-type"] = 'application/json' -request.body = "{\"signup-password\":{\"form-footer-start\":\"
\"}}" +request.body = "{"signup-password":{"form-footer-start":"
"}}" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "authorization": "Bearer {mgmtApiToken}", "content-type": "application/json" ] -let parameters = ["signup-password": ["form-footer-start": "
"]] as [String : Any] +let parameters = ["signup-password": ["form-footer-start": "
"]] as [String : Any] let postData = JSONSerialization.data(withJSONObject: parameters, options: []) @@ -247,20 +269,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
As a result, a **Send a secure code by email button** is added to the `signup-password` screen. When a user selects this button, it submits a form body containing the login state parameter and the name of the desired connection. @@ -270,18 +281,24 @@ For best results, configuring the login prompt for both password and passwordles You can configure the `login-password` prompt using the [Set partials for a prompt](https://auth0.com/docs/api/management/v2/prompts/put-partials) endpoint: -export const codeExample11 = `curl --request PUT \ + +```bash cURL +curl --request PUT \ --url 'https://{yourDomain}/api/v2/prompts/login-password/partials' \ --header 'authorization: Bearer {mgmtApiToken}' \ --header 'content-type: application/json' \ - --data '{"login-password":{"form-footer-start":" Send a secure code by email "}}'`; -export const codeExample12 = `var client = new RestClient("https://{yourDomain}/api/v2/prompts/login-password/partials"); + --data '{"login-password":{"form-footer-start":" Send a secure code by email "}}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/prompts/login-password/partials"); var request = new RestRequest(Method.PUT); request.AddHeader("authorization", "Bearer {mgmtApiToken}"); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\"login-password\":{\"form-footer-start\":\" Send a secure code by email \"}}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample13 = `package main +request.AddParameter("application/json", "{"login-password":{"form-footer-start":" Send a secure code by email "}}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -294,7 +311,7 @@ func main() { url := "https://{yourDomain}/api/v2/prompts/login-password/partials" - payload := strings.NewReader("{\"login-password\":{\"form-footer-start\":\"
\"}}") + payload := strings.NewReader("{"login-password":{"form-footer-start":"
"}}") req, _ := http.NewRequest("PUT", url, payload) @@ -310,13 +327,17 @@ func main() { fmt.Println(string(body)) }n(string(body)) -}`; -export const codeExample14 = `HttpResponse response = Unirest.put("https://{yourDomain}/api/v2/prompts/login-password/partials") +} +``` +```java Java +HttpResponse response = Unirest.put("https://{yourDomain}/api/v2/prompts/login-password/partials") .header("authorization", "Bearer {mgmtApiToken}") .header("content-type", "application/json") - .body("{\"login-password\":{\"form-footer-start\":\" Send a secure code by email \"}}") - .asString();`; -export const codeExample15 = `var axios = require("axios").default; + .body("{"login-password":{"form-footer-start":" Send a secure code by email "}}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PUT', @@ -324,7 +345,7 @@ var options = { headers: {authorization: 'Bearer {mgmtApiToken}', 'content-type': 'application/json'}, data: { 'login-password': { - 'form-footer-start': '
' + 'form-footer-start': '
' } } }; @@ -333,8 +354,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample16 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer {mgmtApiToken}", @"content-type": @"application/json" }; @@ -359,8 +382,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/prompts/login-password/partials", @@ -370,7 +395,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PUT", - CURLOPT_POSTFIELDS => "{\"login-password\":{\"form-footer-start\":\"
\"}}", + CURLOPT_POSTFIELDS => "{"login-password":{"form-footer-start":"
"}}", CURLOPT_HTTPHEADER => [ "authorization: Bearer {mgmtApiToken}", "content-type: application/json" @@ -386,12 +411,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"login-password\":{\"form-footer-start\":\"
\"}}" +payload = "{"login-password":{"form-footer-start":"
"}}" headers = { 'authorization': "Bearer {mgmtApiToken}", @@ -403,8 +430,10 @@ conn.request("PUT", "/{yourDomain}/api/v2/prompts/login-password/partials", payl res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -417,11 +446,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Put.new(url) request["authorization"] = 'Bearer {mgmtApiToken}' request["content-type"] = 'application/json' -request.body = "{\"login-password\":{\"form-footer-start\":\"
\"}}" +request.body = "{"login-password":{"form-footer-start":"
"}}" response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "authorization": "Bearer {mgmtApiToken}", @@ -448,37 +479,32 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
As a result, a **Send a secure code by email button** is added to the `login-password` screen. When a user selects this button, it submits a form body containing the login state parameter and the name of the desired connection. Similarly, you can configure the `login-passwordless` prompt using the [Set partials for a prompt](https://auth0.com/docs/api/management/v2/prompts/put-partials) endpoint: -export const codeExample21 = `curl --request PUT \ + +```bash cURL +curl --request PUT \ --url 'https://{yourDomain}/api/v2/prompts/login-passwordless/partials' \ --header 'authorization: Bearer {mgmtApiToken}' \ --header 'content-type: application/json' \ - --data '{"login-passwordless-email-code":{"form-footer-start":" Use Password Instead "}}'`; -export const codeExample22 = `var client = new RestClient("https://{yourDomain}/api/v2/prompts/login-passwordless/partials"); + --data '{"login-passwordless-email-code":{"form-footer-start":" Use Password Instead "}}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/prompts/login-passwordless/partials"); var request = new RestRequest(Method.PUT); request.AddHeader("authorization", "Bearer {mgmtApiToken}"); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\"login-passwordless-email-code\":{\"form-footer-start\":\" Use Password Instead \"}}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample23 = `package main +request.AddParameter("application/json", "{"login-passwordless-email-code":{"form-footer-start":" Use Password Instead "}}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -491,7 +517,7 @@ func main() { url := "https://{yourDomain}/api/v2/prompts/login-passwordless/partials" - payload := strings.NewReader("{\"login-passwordless-email-code\":{\"form-footer-start\":\"
\"}}") + payload := strings.NewReader("{"login-passwordless-email-code":{"form-footer-start":"
"}}") req, _ := http.NewRequest("PUT", url, payload) @@ -506,13 +532,17 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample24 = `HttpResponse response = Unirest.put("https://{yourDomain}/api/v2/prompts/login-passwordless/partials") +} +``` +```java Java +HttpResponse response = Unirest.put("https://{yourDomain}/api/v2/prompts/login-passwordless/partials") .header("authorization", "Bearer {mgmtApiToken}") .header("content-type", "application/json") - .body("{\"login-passwordless-email-code\":{\"form-footer-start\":\" Use Password Instead \"}}") - .asString();`; -export const codeExample25 = `var axios = require("axios").default; + .body("{"login-passwordless-email-code":{"form-footer-start":" Use Password Instead "}}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PUT', @@ -520,7 +550,7 @@ var options = { headers: {authorization: 'Bearer {mgmtApiToken}', 'content-type': 'application/json'}, data: { 'login-passwordless-email-code': { - 'form-footer-start': '
' + 'form-footer-start': '
' } } }; @@ -529,8 +559,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample26 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer {mgmtApiToken}", @"content-type": @"application/json" }; @@ -555,8 +587,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample27 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/prompts/login-passwordless/partials", @@ -566,7 +600,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PUT", - CURLOPT_POSTFIELDS => "{\"login-passwordless-email-code\":{\"form-footer-start\":\"
\"}}", + CURLOPT_POSTFIELDS => "{"login-passwordless-email-code":{"form-footer-start":"
"}}", CURLOPT_HTTPHEADER => [ "authorization: Bearer {mgmtApiToken}", "content-type: application/json" @@ -582,12 +616,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample28 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"login-passwordless-email-code\":{\"form-footer-start\":\"
\"}}" +payload = "{"login-passwordless-email-code":{"form-footer-start":"
"}}" headers = { 'authorization': "Bearer {mgmtApiToken}", @@ -599,8 +635,10 @@ conn.request("PUT", "/{yourDomain}/api/v2/prompts/login-passwordless/partials", res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample29 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -613,11 +651,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Put.new(url) request["authorization"] = 'Bearer {mgmtApiToken}' request["content-type"] = 'application/json' -request.body = "{\"login-passwordless-email-code\":{\"form-footer-start\":\"
\"}}" +request.body = "{"login-passwordless-email-code":{"form-footer-start":"
"}}" response = http.request(request) -puts response.read_body`; -export const codeExample30 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "authorization": "Bearer {mgmtApiToken}", @@ -644,17 +684,6 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - \ No newline at end of file +dataTask.resume() +``` +
\ No newline at end of file diff --git a/main/docs/customize/login-pages/universal-login/customize-signup-and-login-prompts/language-selection.mdx b/main/docs/customize/login-pages/universal-login/customize-signup-and-login-prompts/language-selection.mdx index 7e10d0ea0..7327b2c05 100644 --- a/main/docs/customize/login-pages/universal-login/customize-signup-and-login-prompts/language-selection.mdx +++ b/main/docs/customize/login-pages/universal-login/customize-signup-and-login-prompts/language-selection.mdx @@ -12,6 +12,8 @@ title: Configure Flexible Language Selection --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + Flexible language selection is an optional feature that allows users to select their preferred language on Universal Login prompts associated with your application, such as the login screen. You can configure this feature individually for different Universal Login prompts. After implementing this feature for a specific prompt, a language selection menu is added to the associated screen. Users can choose a preferred language from this menu to automatically render the prompt in that language. @@ -61,11 +63,6 @@ To get started, add the following script to your [Universal Login page template] ``` - - - - - This script enables Universal Login prompts to render a dynamic language selection menu. Users can access this menu to apply their preferred language to a configured prompt. To add this script to your page template, use the [Set Template for Universal Login](https://auth0.com/docs/api/management/v2/branding/put-universal-login) endpoint. @@ -76,17 +73,19 @@ Be aware that this call will **overwrite any existing configurations** you have -export const codeExample1 = `curl --request PUT \ + +```bash cURL +curl --request PUT \ --url 'https://{yourDomain}/api/v2/branding/templates/universal-login' \ --header 'authorization: Bearer MANAGEMENT_API_TOKEN' \ --header 'content-type: text/html' \ --data ' {%- auth0:head -%} -{%- auth0:widget -%} +{%- auth0:widget -%} '`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/branding/templates/universal-login"); +' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/branding/templates/universal-login"); var request = new RestRequest(Method.PUT); request.AddHeader("content-type", "text/html"); request.AddHeader("authorization", "Bearer MANAGEMENT_API_TOKEN"); request.AddParameter("text/html", " -\n\n{%- auth0:head -%}\n{%- auth0:widget -%}\n", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main + +{%- auth0:head -%} +{%- auth0:widget -%} +", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -119,7 +125,25 @@ func main() { url := "https://{yourDomain}/api/v2/branding/templates/universal-login" - payload := strings.NewReader("\n\n{%- auth0:head -%}\n{%- auth0:widget -%}\n") + payload := strings.NewReader(" + +{%- auth0:head -%} +{%- auth0:widget -%} +") req, _ := http.NewRequest("PUT", url, payload) @@ -134,27 +158,69 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.put("https://{yourDomain}/api/v2/branding/templates/universal-login") +} +``` +```java Java +HttpResponse response = Unirest.put("https://{yourDomain}/api/v2/branding/templates/universal-login") .header("content-type", "text/html") .header("authorization", "Bearer MANAGEMENT_API_TOKEN") - .body("\n\n{%- auth0:head -%}\n{%- auth0:widget -%}\n") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body(" + +{%- auth0:head -%} +{%- auth0:widget -%} +") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PUT', url: 'https://{yourDomain}/api/v2/branding/templates/universal-login', headers: {'content-type': 'text/html', authorization: 'Bearer MANAGEMENT_API_TOKEN'}, - data: '\n\n{%- auth0:head -%}\n{%- auth0:widget -%}\n' + data: ' + +{%- auth0:head -%} +{%- auth0:widget -%} +' }; axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"text/html", @"authorization": @"Bearer MANAGEMENT_API_TOKEN" }; @@ -196,8 +262,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/branding/templates/universal-login", @@ -207,7 +275,25 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PUT", - CURLOPT_POSTFIELDS => "\n\n{%- auth0:head -%}\n{%- auth0:widget -%}\n", + CURLOPT_POSTFIELDS => " + +{%- auth0:head -%} +{%- auth0:widget -%} +", CURLOPT_HTTPHEADER => [ "authorization: Bearer MANAGEMENT_API_TOKEN", "content-type: text/html" @@ -223,12 +309,32 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "\n\n{%- auth0:head -%}\n{%- auth0:widget -%}\n" +payload = " + +{%- auth0:head -%} +{%- auth0:widget -%} +" headers = { 'content-type': "text/html", @@ -240,8 +346,10 @@ conn.request("PUT", "/{yourDomain}/api/v2/branding/templates/universal-login", p res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -254,11 +362,31 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Put.new(url) request["content-type"] = 'text/html' request["authorization"] = 'Bearer MANAGEMENT_API_TOKEN' -request.body = "\n\n{%- auth0:head -%}\n{%- auth0:widget -%}\n" +request.body = " + +{%- auth0:head -%} +{%- auth0:widget -%} +" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "text/html", @@ -302,20 +430,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ### Configure individual Universal Login prompts @@ -360,28 +477,37 @@ In the code samples below, ensure you replace the placeholders with the appropri - To add language selection to the `signup` prompt, use the [Set partials for a prompt](https://auth0.com/docs/api/management/v2/prompts/put-partials) endpoint: -export const codeExample11 = `curl --request PUT \ + +```bash cURL +curl --request PUT \ --url 'https://{yourDomain}/api/v2/prompts/signup/partials' \ --header 'authorization: Bearer {mgmtApiToken}' \ --header 'content-type: application/json' \ --data '{ "signup": { - "form-content-start": "
" + "form-content-start": "
" } -}'`; -export const codeExample12 = `var client = new RestClient("https://{yourDomain}/api/v2/prompts/signup/partials"); +}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/prompts/signup/partials"); var request = new RestRequest(Method.PUT); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer {mgmtApiToken}"); -request.AddParameter("application/json", "{\n \"signup\": {\n \"form-content-start\": \"
\"\n }\n}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample13 = `package main +request.AddParameter("application/json", "{ + "signup": { + "form-content-start": "
" + } +}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -394,7 +520,11 @@ func main() { url := "https://{yourDomain}/api/v2/prompts/signup/partials" - payload := strings.NewReader("{\n \"signup\": {\n \"form-content-start\": \"
\"\n }\n}") + payload := strings.NewReader("{ + "signup": { + "form-content-start": "
" + } +}") req, _ := http.NewRequest("PUT", url, payload) @@ -409,13 +539,21 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample14 = `HttpResponse response = Unirest.put("https://{yourDomain}/api/v2/prompts/signup/partials") +} +``` +```java Java +HttpResponse response = Unirest.put("https://{yourDomain}/api/v2/prompts/signup/partials") .header("content-type", "application/json") .header("authorization", "Bearer {mgmtApiToken}") - .body("{\n \"signup\": {\n \"form-content-start\": \"
\"\n }\n}") - .asString();`; -export const codeExample15 = `var axios = require("axios").default; + .body("{ + "signup": { + "form-content-start": "
" + } +}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PUT', @@ -432,12 +570,14 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample16 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer {mgmtApiToken}" }; -NSDictionary *parameters = @{ @"signup": @{ @"form-content-start": @"
" } }; +NSDictionary *parameters = @{ @"signup": @{ @"form-content-start": @"
" } }; NSData *postData = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:nil]; @@ -458,8 +598,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/prompts/signup/partials", @@ -469,7 +611,11 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PUT", - CURLOPT_POSTFIELDS => "{\n \"signup\": {\n \"form-content-start\": \"
\"\n }\n}", + CURLOPT_POSTFIELDS => "{ + "signup": { + "form-content-start": "
" + } +}", CURLOPT_HTTPHEADER => [ "authorization: Bearer {mgmtApiToken}", "content-type: application/json" @@ -485,12 +631,18 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\n \"signup\": {\n \"form-content-start\": \"
\"\n }\n}" +payload = "{ + "signup": { + "form-content-start": "
" + } +}" headers = { 'content-type': "application/json", @@ -502,8 +654,10 @@ conn.request("PUT", "/{yourDomain}/api/v2/prompts/signup/partials", payload, hea res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -516,17 +670,23 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Put.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer {mgmtApiToken}' -request.body = "{\n \"signup\": {\n \"form-content-start\": \"
\"\n }\n}" +request.body = "{ + "signup": { + "form-content-start": "
" + } +}" response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", "authorization": "Bearer {mgmtApiToken}" ] -let parameters = ["signup": ["form-content-start": "
"]] as [String : Any] +let parameters = ["signup": ["form-content-start": "
"]] as [String : Any] let postData = JSONSerialization.data(withJSONObject: parameters, options: []) @@ -547,20 +707,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
@@ -568,22 +717,32 @@ dataTask.resume()`; To add language selection to the `login-id` prompt, use the [Set partials for a prompt](https://auth0.com/docs/api/management/v2/prompts/put-partials) endpoint: -export const codeExample21 = `curl --request PUT \ + +```bash cURL +curl --request PUT \ --url 'https://{yourDomain}/api/v2/prompts/login-id/partials' \ --header 'authorization: Bearer {mgmtApiToken}' \ --header 'content-type: application/json' \ --data '{ "login-id": { - "form-content-start": "
" + "form-content-start": "
" } -}'`; -export const codeExample22 = `var client = new RestClient("https://{yourDomain}/api/v2/prompts/login-id/partials"); +}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/prompts/login-id/partials"); var request = new RestRequest(Method.PUT); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer {mgmtApiToken}"); -request.AddParameter("application/json", "{\n \"login-id\": {\n \"form-content-start\": \"
\"\n }\n}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample23 = `package main +request.AddParameter("application/json", "{ + "login-id": { + "form-content-start": "
" + } +}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -596,7 +755,11 @@ func main() { url := "https://{yourDomain}/api/v2/prompts/login-id/partials" - payload := strings.NewReader("{\n \"login-id\": {\n \"form-content-start\": \"
\"\n }\n}") + payload := strings.NewReader("{ + "login-id": { + "form-content-start": "
" + } +}") req, _ := http.NewRequest("PUT", url, payload) @@ -611,13 +774,21 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample24 = `HttpResponse response = Unirest.put("https://{yourDomain}/api/v2/prompts/login-id/partials") +} +``` +```java Java +HttpResponse response = Unirest.put("https://{yourDomain}/api/v2/prompts/login-id/partials") .header("content-type", "application/json") .header("authorization", "Bearer {mgmtApiToken}") - .body("{\n \"login-id\": {\n \"form-content-start\": \"
\"\n }\n}") - .asString();`; -export const codeExample25 = `var axios = require("axios").default; + .body("{ + "login-id": { + "form-content-start": "
" + } +}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PUT', @@ -634,12 +805,14 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample26 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer {mgmtApiToken}" }; -NSDictionary *parameters = @{ @"login-id": @{ @"form-content-start": @"
" } }; +NSDictionary *parameters = @{ @"login-id": @{ @"form-content-start": @"
" } }; NSData *postData = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:nil]; @@ -660,8 +833,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample27 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/prompts/login-id/partials", @@ -671,7 +846,11 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PUT", - CURLOPT_POSTFIELDS => "{\n \"login-id\": {\n \"form-content-start\": \"
\"\n }\n}", + CURLOPT_POSTFIELDS => "{ + "login-id": { + "form-content-start": "
" + } +}", CURLOPT_HTTPHEADER => [ "authorization: Bearer {mgmtApiToken}", "content-type: application/json" @@ -687,12 +866,18 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample28 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\n \"login-id\": {\n \"form-content-start\": \"
\"\n }\n}" +payload = "{ + "login-id": { + "form-content-start": "
" + } +}" headers = { 'content-type': "application/json", @@ -704,8 +889,10 @@ conn.request("PUT", "/{yourDomain}/api/v2/prompts/login-id/partials", payload, h res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample29 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -718,17 +905,23 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Put.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer {mgmtApiToken}' -request.body = "{\n \"login-id\": {\n \"form-content-start\": \"
\"\n }\n}" +request.body = "{ + "login-id": { + "form-content-start": "
" + } +}" response = http.request(request) -puts response.read_body`; -export const codeExample30 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", "authorization": "Bearer {mgmtApiToken}" ] -let parameters = ["login-id": ["form-content-start": "
"]] as [String : Any] +let parameters = ["login-id": ["form-content-start": "
"]] as [String : Any] let postData = JSONSerialization.data(withJSONObject: parameters, options: []) @@ -749,20 +942,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
@@ -770,22 +952,32 @@ dataTask.resume()`; To add language selection to the `login-passwordless-email-code` prompt, use the [Set partials for a prompt](https://auth0.com/docs/api/management/v2/prompts/put-partials) endpoint: -export const codeExample31 = `curl --request PUT \ + +```bash cURL +curl --request PUT \ --url 'https://{yourDomain}/api/v2/prompts/login-passwordless/partials' \ --header 'authorization: Bearer {mgmtApiToken}' \ --header 'content-type: application/json' \ --data '{ "login-passwordless-email-code": { - "form-content-start": "
" + "form-content-start": "
" } -}'`; -export const codeExample32 = `var client = new RestClient("https://{yourDomain}/api/v2/prompts/login-passwordless/partials"); +}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/prompts/login-passwordless/partials"); var request = new RestRequest(Method.PUT); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer {mgmtApiToken}"); -request.AddParameter("application/json", "{\n \"login-passwordless-email-code\": {\n \"form-content-start\": \"
\"\n }\n}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample33 = `package main +request.AddParameter("application/json", "{ + "login-passwordless-email-code": { + "form-content-start": "
" + } +}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -798,7 +990,11 @@ func main() { url := "https://{yourDomain}/api/v2/prompts/login-passwordless/partials" - payload := strings.NewReader("{\n \"login-passwordless-email-code\": {\n \"form-content-start\": \"
\"\n }\n}") + payload := strings.NewReader("{ + "login-passwordless-email-code": { + "form-content-start": "
" + } +}") req, _ := http.NewRequest("PUT", url, payload) @@ -813,13 +1009,21 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample34 = `HttpResponse response = Unirest.put("https://{yourDomain}/api/v2/prompts/login-passwordless/partials") +} +``` +```java Java +HttpResponse response = Unirest.put("https://{yourDomain}/api/v2/prompts/login-passwordless/partials") .header("content-type", "application/json") .header("authorization", "Bearer {mgmtApiToken}") - .body("{\n \"login-passwordless-email-code\": {\n \"form-content-start\": \"
\"\n }\n}") - .asString();`; -export const codeExample35 = `var axios = require("axios").default; + .body("{ + "login-passwordless-email-code": { + "form-content-start": "
" + } +}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PUT', @@ -836,12 +1040,14 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample36 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer {mgmtApiToken}" }; -NSDictionary *parameters = @{ @"login-passwordless-email-code": @{ @"form-content-start": @"
" } }; +NSDictionary *parameters = @{ @"login-passwordless-email-code": @{ @"form-content-start": @"
" } }; NSData *postData = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:nil]; @@ -862,8 +1068,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample37 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/prompts/login-passwordless/partials", @@ -873,7 +1081,11 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PUT", - CURLOPT_POSTFIELDS => "{\n \"login-passwordless-email-code\": {\n \"form-content-start\": \"
\"\n }\n}", + CURLOPT_POSTFIELDS => "{ + "login-passwordless-email-code": { + "form-content-start": "
" + } +}", CURLOPT_HTTPHEADER => [ "authorization: Bearer {mgmtApiToken}", "content-type: application/json" @@ -889,12 +1101,18 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample38 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\n \"login-passwordless-email-code\": {\n \"form-content-start\": \"
\"\n }\n}" +payload = "{ + "login-passwordless-email-code": { + "form-content-start": "
" + } +}" headers = { 'content-type': "application/json", @@ -906,8 +1124,10 @@ conn.request("PUT", "/{yourDomain}/api/v2/prompts/login-passwordless/partials", res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample39 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -920,17 +1140,23 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Put.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer {mgmtApiToken}' -request.body = "{\n \"login-passwordless-email-code\": {\n \"form-content-start\": \"
\"\n }\n}" +request.body = "{ + "login-passwordless-email-code": { + "form-content-start": "
" + } +}" response = http.request(request) -puts response.read_body`; -export const codeExample40 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", "authorization": "Bearer {mgmtApiToken}" ] -let parameters = ["login-passwordless-email-code": ["form-content-start": "
"]] as [String : Any] +let parameters = ["login-passwordless-email-code": ["form-content-start": "
"]] as [String : Any] let postData = JSONSerialization.data(withJSONObject: parameters, options: []) @@ -951,20 +1177,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
\ No newline at end of file diff --git a/main/docs/customize/login-pages/universal-login/customize-templates.mdx b/main/docs/customize/login-pages/universal-login/customize-templates.mdx index 1adab5ac0..032a4e34e 100644 --- a/main/docs/customize/login-pages/universal-login/customize-templates.mdx +++ b/main/docs/customize/login-pages/universal-login/customize-templates.mdx @@ -12,6 +12,8 @@ title: Customize Universal Login Page Templates --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + You can customize Universal Login pages by providing a page template created with the [Liquid template language](https://shopify.github.io/liquid/basics/introduction/). With page templates, you can define the content displayed around Universal Login prompts, such as the login box or an MFA challenge. As the same page template is used for all login flow pages, this method of customization allows you to easily implement a consistent, branded experience for users. To use customized page templates, you must configure a [Custom Domain](/docs/customize/custom-domains) for your tenant. Further, you can only update Universal Login page templates with the [Management API](https://auth0.com/docs/api/management/v2). @@ -74,11 +76,6 @@ The following example demonstrates the simplest Universal Login page template yo ``` - - - - - If you use Storybook to view your template, be aware that the ` ``` - - - - - This script enables Universal Login prompts to render a dynamic language selection menu. Users can access this menu to apply their preferred language to a configured prompt. To add this script to your page template, use the [Set Template for Universal Login](https://auth0.com/docs/api/management/v2/branding/put-universal-login) endpoint. @@ -76,17 +73,19 @@ Be aware that this call will **overwrite any existing configurations** you have -export const codeExample1 = `curl --request PUT \ + +```bash cURL +curl --request PUT \ --url 'https://{yourDomain}/api/v2/branding/templates/universal-login' \ --header 'authorization: Bearer MANAGEMENT_API_TOKEN' \ --header 'content-type: text/html' \ --data ' {%- auth0:head -%} -{%- auth0:widget -%} +{%- auth0:widget -%} '`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/branding/templates/universal-login"); +' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/branding/templates/universal-login"); var request = new RestRequest(Method.PUT); request.AddHeader("content-type", "text/html"); request.AddHeader("authorization", "Bearer MANAGEMENT_API_TOKEN"); request.AddParameter("text/html", " -\n\n{%- auth0:head -%}\n{%- auth0:widget -%}\n", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main + +{%- auth0:head -%} +{%- auth0:widget -%} +", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -119,7 +125,25 @@ func main() { url := "https://{yourDomain}/api/v2/branding/templates/universal-login" - payload := strings.NewReader("\n\n{%- auth0:head -%}\n{%- auth0:widget -%}\n") + payload := strings.NewReader(" + +{%- auth0:head -%} +{%- auth0:widget -%} +") req, _ := http.NewRequest("PUT", url, payload) @@ -134,27 +158,69 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.put("https://{yourDomain}/api/v2/branding/templates/universal-login") +} +``` +```java Java +HttpResponse response = Unirest.put("https://{yourDomain}/api/v2/branding/templates/universal-login") .header("content-type", "text/html") .header("authorization", "Bearer MANAGEMENT_API_TOKEN") - .body("\n\n{%- auth0:head -%}\n{%- auth0:widget -%}\n") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body(" + +{%- auth0:head -%} +{%- auth0:widget -%} +") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PUT', url: 'https://{yourDomain}/api/v2/branding/templates/universal-login', headers: {'content-type': 'text/html', authorization: 'Bearer MANAGEMENT_API_TOKEN'}, - data: '\n\n{%- auth0:head -%}\n{%- auth0:widget -%}\n' + data: ' + +{%- auth0:head -%} +{%- auth0:widget -%} +' }; axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"text/html", @"authorization": @"Bearer MANAGEMENT_API_TOKEN" }; @@ -196,8 +262,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/branding/templates/universal-login", @@ -207,7 +275,25 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PUT", - CURLOPT_POSTFIELDS => "\n\n{%- auth0:head -%}\n{%- auth0:widget -%}\n", + CURLOPT_POSTFIELDS => " + +{%- auth0:head -%} +{%- auth0:widget -%} +", CURLOPT_HTTPHEADER => [ "authorization: Bearer MANAGEMENT_API_TOKEN", "content-type: text/html" @@ -223,12 +309,32 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "\n\n{%- auth0:head -%}\n{%- auth0:widget -%}\n" +payload = " + +{%- auth0:head -%} +{%- auth0:widget -%} +" headers = { 'content-type': "text/html", @@ -240,8 +346,10 @@ conn.request("PUT", "/{yourDomain}/api/v2/branding/templates/universal-login", p res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -254,11 +362,31 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Put.new(url) request["content-type"] = 'text/html' request["authorization"] = 'Bearer MANAGEMENT_API_TOKEN' -request.body = "\n\n{%- auth0:head -%}\n{%- auth0:widget -%}\n" +request.body = " + +{%- auth0:head -%} +{%- auth0:widget -%} +" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "text/html", @@ -302,20 +430,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ### Configure individual Universal Login prompts @@ -360,28 +477,37 @@ In the code samples below, ensure you replace the placeholders with the appropri - To add language selection to the `signup` prompt, use the [Set partials for a prompt](https://auth0.com/docs/api/management/v2/prompts/put-partials) endpoint: -export const codeExample11 = `curl --request PUT \ + +```bash cURL +curl --request PUT \ --url 'https://{yourDomain}/api/v2/prompts/signup/partials' \ --header 'authorization: Bearer {mgmtApiToken}' \ --header 'content-type: application/json' \ --data '{ "signup": { - "form-content-start": "
" + "form-content-start": "
" } -}'`; -export const codeExample12 = `var client = new RestClient("https://{yourDomain}/api/v2/prompts/signup/partials"); +}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/prompts/signup/partials"); var request = new RestRequest(Method.PUT); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer {mgmtApiToken}"); -request.AddParameter("application/json", "{\n \"signup\": {\n \"form-content-start\": \"
\"\n }\n}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample13 = `package main +request.AddParameter("application/json", "{ + "signup": { + "form-content-start": "
" + } +}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -394,7 +520,11 @@ func main() { url := "https://{yourDomain}/api/v2/prompts/signup/partials" - payload := strings.NewReader("{\n \"signup\": {\n \"form-content-start\": \"
\"\n }\n}") + payload := strings.NewReader("{ + "signup": { + "form-content-start": "
" + } +}") req, _ := http.NewRequest("PUT", url, payload) @@ -409,13 +539,21 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample14 = `HttpResponse response = Unirest.put("https://{yourDomain}/api/v2/prompts/signup/partials") +} +``` +```java Java +HttpResponse response = Unirest.put("https://{yourDomain}/api/v2/prompts/signup/partials") .header("content-type", "application/json") .header("authorization", "Bearer {mgmtApiToken}") - .body("{\n \"signup\": {\n \"form-content-start\": \"
\"\n }\n}") - .asString();`; -export const codeExample15 = `var axios = require("axios").default; + .body("{ + "signup": { + "form-content-start": "
" + } +}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PUT', @@ -432,12 +570,14 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample16 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer {mgmtApiToken}" }; -NSDictionary *parameters = @{ @"signup": @{ @"form-content-start": @"
" } }; +NSDictionary *parameters = @{ @"signup": @{ @"form-content-start": @"
" } }; NSData *postData = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:nil]; @@ -458,8 +598,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/prompts/signup/partials", @@ -469,7 +611,11 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PUT", - CURLOPT_POSTFIELDS => "{\n \"signup\": {\n \"form-content-start\": \"
\"\n }\n}", + CURLOPT_POSTFIELDS => "{ + "signup": { + "form-content-start": "
" + } +}", CURLOPT_HTTPHEADER => [ "authorization: Bearer {mgmtApiToken}", "content-type: application/json" @@ -485,12 +631,18 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\n \"signup\": {\n \"form-content-start\": \"
\"\n }\n}" +payload = "{ + "signup": { + "form-content-start": "
" + } +}" headers = { 'content-type': "application/json", @@ -502,8 +654,10 @@ conn.request("PUT", "/{yourDomain}/api/v2/prompts/signup/partials", payload, hea res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -516,17 +670,23 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Put.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer {mgmtApiToken}' -request.body = "{\n \"signup\": {\n \"form-content-start\": \"
\"\n }\n}" +request.body = "{ + "signup": { + "form-content-start": "
" + } +}" response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", "authorization": "Bearer {mgmtApiToken}" ] -let parameters = ["signup": ["form-content-start": "
"]] as [String : Any] +let parameters = ["signup": ["form-content-start": "
"]] as [String : Any] let postData = JSONSerialization.data(withJSONObject: parameters, options: []) @@ -547,20 +707,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
@@ -568,22 +717,32 @@ dataTask.resume()`; To add language selection to the `login-id` prompt, use the [Set partials for a prompt](/docs/fr-ca/api/management/v2/prompts/put-partials) endpoint: -export const codeExample21 = `curl --request PUT \ + +```bash cURL +curl --request PUT \ --url 'https://{yourDomain}/api/v2/prompts/login-id/partials' \ --header 'authorization: Bearer {mgmtApiToken}' \ --header 'content-type: application/json' \ --data '{ "login-id": { - "form-content-start": "
" + "form-content-start": "
" } -}'`; -export const codeExample22 = `var client = new RestClient("https://{yourDomain}/api/v2/prompts/login-id/partials"); +}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/prompts/login-id/partials"); var request = new RestRequest(Method.PUT); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer {mgmtApiToken}"); -request.AddParameter("application/json", "{\n \"login-id\": {\n \"form-content-start\": \"
\"\n }\n}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample23 = `package main +request.AddParameter("application/json", "{ + "login-id": { + "form-content-start": "
" + } +}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -596,7 +755,11 @@ func main() { url := "https://{yourDomain}/api/v2/prompts/login-id/partials" - payload := strings.NewReader("{\n \"login-id\": {\n \"form-content-start\": \"
\"\n }\n}") + payload := strings.NewReader("{ + "login-id": { + "form-content-start": "
" + } +}") req, _ := http.NewRequest("PUT", url, payload) @@ -611,13 +774,21 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample24 = `HttpResponse response = Unirest.put("https://{yourDomain}/api/v2/prompts/login-id/partials") +} +``` +```java Java +HttpResponse response = Unirest.put("https://{yourDomain}/api/v2/prompts/login-id/partials") .header("content-type", "application/json") .header("authorization", "Bearer {mgmtApiToken}") - .body("{\n \"login-id\": {\n \"form-content-start\": \"
\"\n }\n}") - .asString();`; -export const codeExample25 = `var axios = require("axios").default; + .body("{ + "login-id": { + "form-content-start": "
" + } +}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PUT', @@ -634,12 +805,14 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample26 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer {mgmtApiToken}" }; -NSDictionary *parameters = @{ @"login-id": @{ @"form-content-start": @"
" } }; +NSDictionary *parameters = @{ @"login-id": @{ @"form-content-start": @"
" } }; NSData *postData = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:nil]; @@ -660,8 +833,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample27 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/prompts/login-id/partials", @@ -671,7 +846,11 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PUT", - CURLOPT_POSTFIELDS => "{\n \"login-id\": {\n \"form-content-start\": \"
\"\n }\n}", + CURLOPT_POSTFIELDS => "{ + "login-id": { + "form-content-start": "
" + } +}", CURLOPT_HTTPHEADER => [ "authorization: Bearer {mgmtApiToken}", "content-type: application/json" @@ -687,12 +866,18 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample28 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\n \"login-id\": {\n \"form-content-start\": \"
\"\n }\n}" +payload = "{ + "login-id": { + "form-content-start": "
" + } +}" headers = { 'content-type': "application/json", @@ -704,8 +889,10 @@ conn.request("PUT", "/{yourDomain}/api/v2/prompts/login-id/partials", payload, h res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample29 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -718,17 +905,23 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Put.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer {mgmtApiToken}' -request.body = "{\n \"login-id\": {\n \"form-content-start\": \"
\"\n }\n}" +request.body = "{ + "login-id": { + "form-content-start": "
" + } +}" response = http.request(request) -puts response.read_body`; -export const codeExample30 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", "authorization": "Bearer {mgmtApiToken}" ] -let parameters = ["login-id": ["form-content-start": "
"]] as [String : Any] +let parameters = ["login-id": ["form-content-start": "
"]] as [String : Any] let postData = JSONSerialization.data(withJSONObject: parameters, options: []) @@ -749,20 +942,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
@@ -770,22 +952,32 @@ dataTask.resume()`; To add language selection to the `login-passwordless-email-code` prompt, use the [Set partials for a prompt](/docs/fr-ca/api/management/v2/prompts/put-partials) endpoint: -export const codeExample31 = `curl --request PUT \ + +```bash cURL +curl --request PUT \ --url 'https://{yourDomain}/api/v2/prompts/login-passwordless/partials' \ --header 'authorization: Bearer {mgmtApiToken}' \ --header 'content-type: application/json' \ --data '{ "login-passwordless-email-code": { - "form-content-start": "
" + "form-content-start": "
" } -}'`; -export const codeExample32 = `var client = new RestClient("https://{yourDomain}/api/v2/prompts/login-passwordless/partials"); +}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/prompts/login-passwordless/partials"); var request = new RestRequest(Method.PUT); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer {mgmtApiToken}"); -request.AddParameter("application/json", "{\n \"login-passwordless-email-code\": {\n \"form-content-start\": \"
\"\n }\n}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample33 = `package main +request.AddParameter("application/json", "{ + "login-passwordless-email-code": { + "form-content-start": "
" + } +}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -798,7 +990,11 @@ func main() { url := "https://{yourDomain}/api/v2/prompts/login-passwordless/partials" - payload := strings.NewReader("{\n \"login-passwordless-email-code\": {\n \"form-content-start\": \"
\"\n }\n}") + payload := strings.NewReader("{ + "login-passwordless-email-code": { + "form-content-start": "
" + } +}") req, _ := http.NewRequest("PUT", url, payload) @@ -813,13 +1009,21 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample34 = `HttpResponse response = Unirest.put("https://{yourDomain}/api/v2/prompts/login-passwordless/partials") +} +``` +```java Java +HttpResponse response = Unirest.put("https://{yourDomain}/api/v2/prompts/login-passwordless/partials") .header("content-type", "application/json") .header("authorization", "Bearer {mgmtApiToken}") - .body("{\n \"login-passwordless-email-code\": {\n \"form-content-start\": \"
\"\n }\n}") - .asString();`; -export const codeExample35 = `var axios = require("axios").default; + .body("{ + "login-passwordless-email-code": { + "form-content-start": "
" + } +}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PUT', @@ -836,12 +1040,14 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample36 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer {mgmtApiToken}" }; -NSDictionary *parameters = @{ @"login-passwordless-email-code": @{ @"form-content-start": @"
" } }; +NSDictionary *parameters = @{ @"login-passwordless-email-code": @{ @"form-content-start": @"
" } }; NSData *postData = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:nil]; @@ -862,8 +1068,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample37 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/prompts/login-passwordless/partials", @@ -873,7 +1081,11 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PUT", - CURLOPT_POSTFIELDS => "{\n \"login-passwordless-email-code\": {\n \"form-content-start\": \"
\"\n }\n}", + CURLOPT_POSTFIELDS => "{ + "login-passwordless-email-code": { + "form-content-start": "
" + } +}", CURLOPT_HTTPHEADER => [ "authorization: Bearer {mgmtApiToken}", "content-type: application/json" @@ -889,12 +1101,18 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample38 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\n \"login-passwordless-email-code\": {\n \"form-content-start\": \"
\"\n }\n}" +payload = "{ + "login-passwordless-email-code": { + "form-content-start": "
" + } +}" headers = { 'content-type': "application/json", @@ -906,8 +1124,10 @@ conn.request("PUT", "/{yourDomain}/api/v2/prompts/login-passwordless/partials", res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample39 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -920,17 +1140,23 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Put.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer {mgmtApiToken}' -request.body = "{\n \"login-passwordless-email-code\": {\n \"form-content-start\": \"
\"\n }\n}" +request.body = "{ + "login-passwordless-email-code": { + "form-content-start": "
" + } +}" response = http.request(request) -puts response.read_body`; -export const codeExample40 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", "authorization": "Bearer {mgmtApiToken}" ] -let parameters = ["login-passwordless-email-code": ["form-content-start": "
"]] as [String : Any] +let parameters = ["login-passwordless-email-code": ["form-content-start": "
"]] as [String : Any] let postData = JSONSerialization.data(withJSONObject: parameters, options: []) @@ -951,20 +1177,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
diff --git a/main/docs/fr-ca/customize/login-pages/universal-login/customize-templates.mdx b/main/docs/fr-ca/customize/login-pages/universal-login/customize-templates.mdx index b7bd5f34e..d948befdc 100644 --- a/main/docs/fr-ca/customize/login-pages/universal-login/customize-templates.mdx +++ b/main/docs/fr-ca/customize/login-pages/universal-login/customize-templates.mdx @@ -10,6 +10,7 @@ permalink: "customize-templates" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Vous pouvez personnaliser les pages de connexion universelle en fournissant un modèle de page créé avec le [langage de modèle Liquid](https://shopify.github.io/liquid/basics/introduction/). Avec les modèles de page, vous pouvez définir le contenu affiché autour des invites de connexion universelle, telles que la boîte de connexion ou un défi MFA. Comme le même modèle de page est utilisé pour toutes les pages de flux de connexion, cette méthode de personnalisation vous permet de mettre en œuvre facilement une expérience cohérente et reflétant votre marque pour les utilisateurs. @@ -355,7 +356,7 @@ accordion.expand_all/accordion.collapse_all -## Écran: redeem-ticket](/docs/images/ +## Écran: redeem-ticket ![capture d’écran de référence pour redeem-ticket (échanger un billet)](/images/fr-ca/cdy7uua7fh8z/7H4DS8I8fnlUgtS4ttpMyK/90006ee36032cc1ee3d9674fe6bcf575/redeem-ticket.png) @@ -1419,7 +1420,7 @@ accordion.expand_all/accordion.collapse_all -## Écran : login-passwordless-email-code](/docs/images/ +## Écran : login-passwordless-email-code ![capture d’écran de référence pour code de connexion par courriel sans mot de passe](/images/fr-ca/cdy7uua7fh8z/6zazshkUI5sdFDd2Fgbo6w/0193e17673250b5293d9581e34316c20/login-passwordless-email-code.png) @@ -1477,7 +1478,7 @@ accordion.expand_all/accordion.collapse_all
-## Écran : login-passwordless-email-link](/docs/images/ +## Écran : login-passwordless-email-link ![Capture d’écran de référence du lien de connexion par courriel sans mot de passe](/images/fr-ca/cdy7uua7fh8z/7EcEUmoEPC6GVgJjNyTugr/e160cb40af3a0c748ba1f9fe2307488b/login-passwordless-email-link.png) @@ -1511,7 +1512,7 @@ accordion.expand_all/accordion.collapse_all -## Écran : login-passwordless-sms-otp](/docs/images/ +## Écran : login-passwordless-sms-otp ![Capture d’écran de référence OTP par SMS pour connexion sans mot de passe](/images/fr-ca/cdy7uua7fh8z/5dk4vZpc06UojLdnelUInO/f5fb02e0adeeceaa1b8ce6eef8151bc2/login-passwordless-sms-otp.png) @@ -1647,7 +1648,7 @@ accordion.expand_all/accordion.collapse_all -## Écran : logout](/docs/images/ +## Écran : logout ![capture d’écran de référence pour déconnexion](/images/fr-ca/cdy7uua7fh8z/2lXg143oKAF4OlIilbwDCK/d770603ba5203adff07cf4e23e4fcbbb/logout.png) @@ -1693,7 +1694,7 @@ accordion.expand_all/accordion.collapse_all -## Écran : mfa-detect-browser-capabilities](/docs/images/ +## Écran : mfa-detect-browser-capabilities ![Capture d’écran de référence pour détection des capacités du navigateur pour MFA](/images/fr-ca/cdy7uua7fh8z/2D7DbdMRJ7SdwxEzOYYsLX/595c1436aaa38ed342137c4a5227f4b0/mfa-detect-browser-capabilities.png) @@ -6098,7 +6099,7 @@ Le modèle suivant affiche la boîte de connexion à gauche et une image à droi {% endif %} -```](/docs/images/ +``` ![Boîte Universal Login (Connexion universelle) et exemple de présentation d’adresse électronique/mot de passe et pieds de page](/images/fr-ca/cdy7uua7fh8z/7F2LIZ4qVdGqMUNnj66wcP/29ef92e679fffcf83a35cdcc156390d2/Login_Screen_-_Background_-_FR.png) @@ -6117,19 +6118,25 @@ Pour définir le modèle de page, vous devez utiliser la Management API. Vous de Pour définir le modèle, vous devez utiliser le point de terminaison suivant : -export const codeExample1 = `curl --request PUT \ + +```bash cURL +curl --request PUT \ --url 'https://{yourDomain}/api/v2/branding/templates/universal-login' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'content-type: text/html' \ - --data '{%- auth0:head -%}{%- auth0:widget -%}'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/branding/templates/universal-login"); + --data '{%- auth0:head -%}{%- auth0:widget -%}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/branding/templates/universal-login"); var request = new RestRequest(Method.PUT); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("content-type", "text/html"); request.AddParameter("text/html", " {%- auth0:head -%}{%- auth0:widget -%}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -6157,13 +6164,17 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.put("https://{yourDomain}/api/v2/branding/templates/universal-login") +} +``` +```java Java +HttpResponse response = Unirest.put("https://{yourDomain}/api/v2/branding/templates/universal-login") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("content-type", "text/html") .body("{%- auth0:head -%}{%- auth0:widget -%}") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PUT', @@ -6176,8 +6187,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @"content-type": @"text/html" }; @@ -6201,8 +6214,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/branding/templates/universal-login", @@ -6228,8 +6243,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -6245,8 +6262,10 @@ conn.request("PUT", "/{yourDomain}/api/v2/branding/templates/universal-login", p res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -6262,8 +6281,10 @@ request["content-type"] = 'text/html' request.body = "{%- auth0:head -%}{%- auth0:widget -%}" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "authorization": "Bearer MGMT_API_ACCESS_TOKEN", @@ -6289,31 +6310,26 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + Pour récupérer le modèle, vous devez utiliser le point de terminaison suivant : -export const codeExample11 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/branding/templates/universal-login' \ - --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN'`; -export const codeExample12 = `var client = new RestClient("https://{yourDomain}/api/v2/branding/templates/universal-login"); + --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/branding/templates/universal-login"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); -IRestResponse response = client.Execute(request);`; -export const codeExample13 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -6337,11 +6353,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample14 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/branding/templates/universal-login") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/branding/templates/universal-login") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") - .asString();`; -export const codeExample15 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -6353,8 +6373,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample16 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN" }; @@ -6374,8 +6396,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/branding/templates/universal-login", @@ -6399,8 +6423,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -6411,8 +6437,10 @@ conn.request("GET", "/{yourDomain}/api/v2/branding/templates/universal-login", h res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -6426,8 +6454,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer MGMT_API_ACCESS_TOKEN"] @@ -6447,31 +6477,26 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + Pour supprimer le modèle, vous devez utiliser le point de terminaison suivant : -export const codeExample21 = `curl --request DELETE \ + +```bash cURL +curl --request DELETE \ --url 'https://{yourDomain}/api/v2/branding/templates/universal-login' \ - --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN'`; -export const codeExample22 = `var client = new RestClient("https://{yourDomain}/api/v2/branding/templates/universal-login"); + --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/branding/templates/universal-login"); var request = new RestRequest(Method.DELETE); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); -IRestResponse response = client.Execute(request);`; -export const codeExample23 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -6495,11 +6520,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample24 = `HttpResponse response = Unirest.delete("https://{yourDomain}/api/v2/branding/templates/universal-login") +} +``` +```java Java +HttpResponse response = Unirest.delete("https://{yourDomain}/api/v2/branding/templates/universal-login") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") - .asString();`; -export const codeExample25 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'DELETE', @@ -6511,8 +6540,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample26 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN" }; @@ -6532,8 +6563,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample27 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/branding/templates/universal-login", @@ -6557,8 +6590,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample28 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -6569,8 +6604,10 @@ conn.request("DELETE", "/{yourDomain}/api/v2/branding/templates/universal-login" res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample29 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -6584,8 +6621,10 @@ request = Net::HTTP::Delete.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' response = http.request(request) -puts response.read_body`; -export const codeExample30 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer MGMT_API_ACCESS_TOKEN"] @@ -6605,20 +6644,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + La taille maximale du modèle de page est de 100 Ko. Si cette taille n’est pas suffisante, envisagez de déplacer les fichiers images/css en dehors du code du modèle de page. diff --git a/main/docs/fr-ca/customize/login-pages/universal-login/customize-text-elements.mdx b/main/docs/fr-ca/customize/login-pages/universal-login/customize-text-elements.mdx index cd81fc978..aa5c4b9c0 100644 --- a/main/docs/fr-ca/customize/login-pages/universal-login/customize-text-elements.mdx +++ b/main/docs/fr-ca/customize/login-pages/universal-login/customize-text-elements.mdx @@ -10,6 +10,7 @@ permalink: "customize-text-elements" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; La Connexion universelle consiste en un ensemble de pages qui facilitent plusieurs actions liées au compte, telles que la connexion, l’enrôlement des facteurs d’authentification multifacteur (MFA) ou la réinitialisation des mots de passe. Auth0 fournit le texte de ces pages en plusieurs langues. @@ -53,18 +54,24 @@ Vous pouvez utiliser Management API pour personnaliser les invites pour le texte Vous pourriez configurer le composant de texte `description` de l’invite `login` (connexion) sur l’écran de `connexion` pour `se connecter au site Web d’ACME` en appelant le point de terminaison [Set custom text for a specific prompt](https://auth0.com/docs/api/management/v2#!/Prompts/put_custom_text_by_language) (Définir un texte personnalisé pour une invite donnée) de Management API de la façon suivante : -export const codeExample1 = `curl --request PUT \ + +```bash cURL +curl --request PUT \ --url 'https://{yourDomain}/api/v2/prompts/login/custom-text/en' \ --header 'authorization: Bearer {yourMgmtApiAccessToken}' \ --header 'content-type: application/json' \ - --data '{ "login": { "description": "Login to ACME'\''s Website" } }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/prompts/login/custom-text/en"); + --data '{ "login": { "description": "Login to ACME'''s Website" } }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/prompts/login/custom-text/en"); var request = new RestRequest(Method.PUT); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer {yourMgmtApiAccessToken}"); -request.AddParameter("application/json", "{ \"login\": { \"description\": \"Login to ACME's Website\" } }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "login": { "description": "Login to ACME's Website" } }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -77,7 +84,7 @@ func main() { url := "https://{yourDomain}/api/v2/prompts/login/custom-text/en" - payload := strings.NewReader("{ \"login\": { \"description\": \"Login to ACME's Website\" } }") + payload := strings.NewReader("{ "login": { "description": "Login to ACME's Website" } }") req, _ := http.NewRequest("PUT", url, payload) @@ -92,13 +99,17 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.put("https://{yourDomain}/api/v2/prompts/login/custom-text/en") +} +``` +```java Java +HttpResponse response = Unirest.put("https://{yourDomain}/api/v2/prompts/login/custom-text/en") .header("content-type", "application/json") .header("authorization", "Bearer {yourMgmtApiAccessToken}") - .body("{ \"login\": { \"description\": \"Login to ACME's Website\" } }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "login": { "description": "Login to ACME's Website" } }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PUT', @@ -107,15 +118,17 @@ var options = { 'content-type': 'application/json', authorization: 'Bearer {yourMgmtApiAccessToken}' }, - data: {login: {description: 'Login to ACME\'s Website'}} + data: {login: {description: 'Login to ACME's Website'}} }; axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer {yourMgmtApiAccessToken}" }; @@ -140,8 +153,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/prompts/login/custom-text/en", @@ -151,7 +166,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PUT", - CURLOPT_POSTFIELDS => "{ \"login\": { \"description\": \"Login to ACME's Website\" } }", + CURLOPT_POSTFIELDS => "{ "login": { "description": "Login to ACME's Website" } }", CURLOPT_HTTPHEADER => [ "authorization: Bearer {yourMgmtApiAccessToken}", "content-type: application/json" @@ -167,12 +182,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"login\": { \"description\": \"Login to ACME's Website\" } }" +payload = "{ "login": { "description": "Login to ACME's Website" } }" headers = { 'content-type': "application/json", @@ -184,8 +201,10 @@ conn.request("PUT", "/{yourDomain}/api/v2/prompts/login/custom-text/en", payload res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -198,11 +217,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Put.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer {yourMgmtApiAccessToken}' -request.body = "{ \"login\": { \"description\": \"Login to ACME's Website\" } }" +request.body = "{ "login": { "description": "Login to ACME's Website" } }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -229,37 +250,32 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + #### Supprimer un texte personnalisé pour une invite Si vous voulez supprimer tout texte personnalisé pour une invite, appelez le point de terminaison [Set custom text for a specific prompt](https://auth0.com/docs/api/management/v2#!/Prompts/put_custom_text_by_language) (Définir un texte personnalisé pour une invite donnéée) de Management API en indiquant un objet vide (`{})` comme paramètre du `corps` : -export const codeExample11 = `curl --request PUT \ + +```bash cURL +curl --request PUT \ --url 'https://{yourDomain}/api/v2/prompts/login/custom-text/en' \ --header 'authorization: Bearer {yourMgmtApiAccessToken}' \ --header 'content-type: application/json' \ - --data '{}'`; -export const codeExample12 = `var client = new RestClient("https://{yourDomain}/api/v2/prompts/login/custom-text/en"); + --data '{}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/prompts/login/custom-text/en"); var request = new RestRequest(Method.PUT); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer {yourMgmtApiAccessToken}"); request.AddParameter("application/json", "{}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample13 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -287,13 +303,17 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample14 = `HttpResponse response = Unirest.put("https://{yourDomain}/api/v2/prompts/login/custom-text/en") +} +``` +```java Java +HttpResponse response = Unirest.put("https://{yourDomain}/api/v2/prompts/login/custom-text/en") .header("content-type", "application/json") .header("authorization", "Bearer {yourMgmtApiAccessToken}") .body("{}") - .asString();`; -export const codeExample15 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PUT', @@ -309,8 +329,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample16 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer {yourMgmtApiAccessToken}" }; @@ -335,8 +357,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/prompts/login/custom-text/en", @@ -362,8 +386,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -379,8 +405,10 @@ conn.request("PUT", "/{yourDomain}/api/v2/prompts/login/custom-text/en", payload res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -396,8 +424,10 @@ request["authorization"] = 'Bearer {yourMgmtApiAccessToken}' request.body = "{}" response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -424,20 +454,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + diff --git a/main/docs/fr-ca/customize/rules/create-rules.mdx b/main/docs/fr-ca/customize/rules/create-rules.mdx index 1d10db6d7..cd3bc1aa0 100644 --- a/main/docs/fr-ca/customize/rules/create-rules.mdx +++ b/main/docs/fr-ca/customize/rules/create-rules.mdx @@ -10,6 +10,7 @@ permalink: "create-rules" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; @@ -56,7 +57,7 @@ Si vous prévoyez d’utiliser des variables globales dans votre règle, veillez ![Dashboard - Auth Pipeline - Rules ](/images/fr-ca/cdy7uua7fh8z/4OiSXzc5fYgPagHdOGbfvj/a589bdf811df66658fe21c509aed610c/Dashboard_-_Auth_Pipeline_-_Rules.png) -2. Sélectionnez un modèle de règle.](/docs/images/ +2. Sélectionnez un modèle de règle. ![Dashboard - Auth Pipeline - Rules - Template](/images/fr-ca/cdy7uua7fh8z/6IydSSjg2oQrdSzErcTYtN/d17348a98c597a74b2989c298764b9e1/dashboard-rules-create_choose-template.png) @@ -69,20 +70,26 @@ Si vous prévoyez d’utiliser des variables globales dans votre règle, veillez Faites un appel `POST` au point de terminaison [Créer une règle](/docs/fr-ca/api/management/v2#!/Rules/post_rules). Assurez-vous de remplacer les valeurs fictives `MGMT_API_ACCESS_TOKEN`, `RULE_NAME`, `RULE_SCRIPT`, `RULE_ORDER`, and `RULE_ENABLED` avec votre jeton d’accès au Management API, le nom de la règle, le script de la règle, le numéro d’ordre de la règle et la valeur activée de la règle, respectivement. -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/api/v2/rules' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{ "name": "RULE_NAME", "script": "RULE_SCRIPT" }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/rules"); + --data '{ "name": "RULE_NAME", "script": "RULE_SCRIPT" }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/rules"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{ \"name\": \"RULE_NAME\", \"script\": \"RULE_SCRIPT\" }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "name": "RULE_NAME", "script": "RULE_SCRIPT" }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -95,7 +102,7 @@ func main() { url := "https://{yourDomain}/api/v2/rules" - payload := strings.NewReader("{ \"name\": \"RULE_NAME\", \"script\": \"RULE_SCRIPT\" }") + payload := strings.NewReader("{ "name": "RULE_NAME", "script": "RULE_SCRIPT" }") req, _ := http.NewRequest("POST", url, payload) @@ -111,14 +118,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/rules") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/rules") .header("content-type", "application/json") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ \"name\": \"RULE_NAME\", \"script\": \"RULE_SCRIPT\" }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "name": "RULE_NAME", "script": "RULE_SCRIPT" }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -135,8 +146,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @@ -163,8 +176,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/rules", @@ -174,7 +189,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{ \"name\": \"RULE_NAME\", \"script\": \"RULE_SCRIPT\" }", + CURLOPT_POSTFIELDS => "{ "name": "RULE_NAME", "script": "RULE_SCRIPT" }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "cache-control: no-cache", @@ -191,12 +206,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"name\": \"RULE_NAME\", \"script\": \"RULE_SCRIPT\" }" +payload = "{ "name": "RULE_NAME", "script": "RULE_SCRIPT" }" headers = { 'content-type': "application/json", @@ -209,8 +226,10 @@ conn.request("POST", "/{yourDomain}/api/v2/rules", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -224,11 +243,13 @@ request = Net::HTTP::Post.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ \"name\": \"RULE_NAME\", \"script\": \"RULE_SCRIPT\" }" +request.body = "{ "name": "RULE_NAME", "script": "RULE_SCRIPT" }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -259,20 +280,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + diff --git a/main/docs/fr-ca/get-started/apis/add-api-permissions.mdx b/main/docs/fr-ca/get-started/apis/add-api-permissions.mdx index 0002a4e0a..c777edd0d 100644 --- a/main/docs/fr-ca/get-started/apis/add-api-permissions.mdx +++ b/main/docs/fr-ca/get-started/apis/add-api-permissions.mdx @@ -10,6 +10,7 @@ permalink: "add-api-permissions" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Vous pouvez ajouter des autorisations à une API à l’aide d’Auth0 Dashboard ou de response = Unirest.patch("https://{yourDomain}/api/v2/resource-servers/API_ID") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/resource-servers/API_ID") .header("content-type", "application/json") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ \"scopes\": [ { \"value\": \"PERMISSION_NAME\", \"description\": \"PERMISSION_DESC\" }, { \"value\": \"PERMISSION_NAME\", \"description\": \"PERMISSION_DESC\" } ] }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "scopes": [ { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" }, { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" } ] }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -114,8 +125,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @@ -141,8 +154,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/resource-servers/API_ID", @@ -152,7 +167,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{ \"scopes\": [ { \"value\": \"PERMISSION_NAME\", \"description\": \"PERMISSION_DESC\" }, { \"value\": \"PERMISSION_NAME\", \"description\": \"PERMISSION_DESC\" } ] }", + CURLOPT_POSTFIELDS => "{ "scopes": [ { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" }, { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" } ] }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "cache-control: no-cache", @@ -169,12 +184,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"scopes\": [ { \"value\": \"PERMISSION_NAME\", \"description\": \"PERMISSION_DESC\" }, { \"value\": \"PERMISSION_NAME\", \"description\": \"PERMISSION_DESC\" } ] }" +payload = "{ "scopes": [ { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" }, { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" } ] }" headers = { 'content-type': "application/json", @@ -187,8 +204,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/resource-servers/API_ID", payload, h res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -202,11 +221,13 @@ request = Net::HTTP::Patch.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ \"scopes\": [ { \"value\": \"PERMISSION_NAME\", \"description\": \"PERMISSION_DESC\" }, { \"value\": \"PERMISSION_NAME\", \"description\": \"PERMISSION_DESC\" } ] }" +request.body = "{ "scopes": [ { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" }, { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" } ] }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -243,21 +264,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - - +dataTask.resume() +``` + diff --git a/main/docs/fr-ca/get-started/apis/delete-api-permissions.mdx b/main/docs/fr-ca/get-started/apis/delete-api-permissions.mdx index cb6e1dcbc..63b44cc75 100644 --- a/main/docs/fr-ca/get-started/apis/delete-api-permissions.mdx +++ b/main/docs/fr-ca/get-started/apis/delete-api-permissions.mdx @@ -10,6 +10,7 @@ permalink: "delete-api-permissions" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Vous pouvez supprimer les autorisations d’une API à l’aide d’Auth0 Dashboard ou de Management API. @@ -19,7 +20,7 @@ Vous pouvez supprimer les autorisations d’une API à l’aide d’Auth0 Dash ![Liste des API d’applications Dashboard](/images/fr-ca/cdy7uua7fh8z/3rhmhghYZDSi6YWHRA5yMQ/29b5fc5ca1dcedd82e9e7fff1fc8ecc8/2025-02-27_10-28-06.png) -2. Rendez-vous dans l’onglet **Autorisations** et cliquez sur l’icône de la corbeille à côté de l’autorisation que vous souhaitez supprimer, puis confirmez.](/docs/images/ +2. Rendez-vous dans l’onglet **Autorisations** et cliquez sur l’icône de la corbeille à côté de l’autorisation que vous souhaitez supprimer, puis confirmez. ![Dashboard (Tableau de bord) - Add API Permissions (Ajouter des permissions API) - API Define Permissions Screen (Écran de définition des permissions API)](/images/fr-ca/cdy7uua7fh8z/32Pb185OFs2mC6z2fmunEw/efe280485cc016d4396588dad02bfad5/2025-02-27_10-14-21.png) @@ -27,20 +28,26 @@ Vous pouvez supprimer les autorisations d’une API à l’aide d’Auth0 Dash Faites un appel PATCH au [point de terminaison Mise à jour du serveur de ressources](https://auth0.com/docs/api/management/v2#!/Resource_Servers/patch_resource_servers_by_id) en incluant toutes les autorisations que vous souhaitez conserver et en excluant toutes celles que vous souhaitez supprimer. Remplacez les valeurs des placeholders `API_ID`, `MGMT_API_ACCESS_TOKEN`, `PERMISSION_NAME` et `PERMISSION_DESC` par l’identifiant de l’API, le jeton d’accès à Management API, le ou les nom de l’autorisation et la ou les descriptions de l’autorisation, respectivement. -export const codeExample1 = `curl --request PATCH \ + +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/resource-servers/API_ID' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{ "scopes": [ { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" }, { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" } ] }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/resource-servers/API_ID"); + --data '{ "scopes": [ { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" }, { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" } ] }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/resource-servers/API_ID"); var request = new RestRequest(Method.PATCH); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{ \"scopes\": [ { \"value\": \"PERMISSION_NAME\", \"description\": \"PERMISSION_DESC\" }, { \"value\": \"PERMISSION_NAME\", \"description\": \"PERMISSION_DESC\" } ] }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "scopes": [ { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" }, { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" } ] }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -53,7 +60,7 @@ func main() { url := "https://{yourDomain}/api/v2/resource-servers/API_ID" - payload := strings.NewReader("{ \"scopes\": [ { \"value\": \"PERMISSION_NAME\", \"description\": \"PERMISSION_DESC\" }, { \"value\": \"PERMISSION_NAME\", \"description\": \"PERMISSION_DESC\" } ] }") + payload := strings.NewReader("{ "scopes": [ { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" }, { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" } ] }") req, _ := http.NewRequest("PATCH", url, payload) @@ -69,14 +76,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/resource-servers/API_ID") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/resource-servers/API_ID") .header("content-type", "application/json") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ \"scopes\": [ { \"value\": \"PERMISSION_NAME\", \"description\": \"PERMISSION_DESC\" }, { \"value\": \"PERMISSION_NAME\", \"description\": \"PERMISSION_DESC\" } ] }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "scopes": [ { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" }, { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" } ] }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -98,8 +109,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @@ -125,8 +138,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/resource-servers/API_ID", @@ -136,7 +151,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{ \"scopes\": [ { \"value\": \"PERMISSION_NAME\", \"description\": \"PERMISSION_DESC\" }, { \"value\": \"PERMISSION_NAME\", \"description\": \"PERMISSION_DESC\" } ] }", + CURLOPT_POSTFIELDS => "{ "scopes": [ { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" }, { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" } ] }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "cache-control: no-cache", @@ -153,12 +168,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"scopes\": [ { \"value\": \"PERMISSION_NAME\", \"description\": \"PERMISSION_DESC\" }, { \"value\": \"PERMISSION_NAME\", \"description\": \"PERMISSION_DESC\" } ] }" +payload = "{ "scopes": [ { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" }, { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" } ] }" headers = { 'content-type': "application/json", @@ -171,8 +188,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/resource-servers/API_ID", payload, h res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -186,11 +205,13 @@ request = Net::HTTP::Patch.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ \"scopes\": [ { \"value\": \"PERMISSION_NAME\", \"description\": \"PERMISSION_DESC\" }, { \"value\": \"PERMISSION_NAME\", \"description\": \"PERMISSION_DESC\" } ] }" +request.body = "{ "scopes": [ { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" }, { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" } ] }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -227,21 +248,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - - +dataTask.resume() +``` +
diff --git a/main/docs/fr-ca/get-started/apis/enable-role-based-access-control-for-apis.mdx b/main/docs/fr-ca/get-started/apis/enable-role-based-access-control-for-apis.mdx index 63128a620..587b323a9 100644 --- a/main/docs/fr-ca/get-started/apis/enable-role-based-access-control-for-apis.mdx +++ b/main/docs/fr-ca/get-started/apis/enable-role-based-access-control-for-apis.mdx @@ -10,6 +10,7 @@ permalink: "enable-role-based-access-control-for-apis" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Vous pouvez activer le [contrôle d'accès basé sur les rôles (RBAC)](/docs/fr-ca/manage-users/access-control/rbac) à l’aide de Auth0 Dashboard ou de response = Unirest.patch("https://{yourDomain}/api/v2/resource-servers/API_ID") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/resource-servers/API_ID") .header("content-type", "application/json") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ \"enforce_policies\": \"true\", \"token_dialect\": \"TOKEN_DIALECT\" }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "enforce_policies": "true", "token_dialect": "TOKEN_DIALECT" }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -111,8 +122,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @@ -139,8 +152,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/resource-servers/API_ID", @@ -150,7 +165,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{ \"enforce_policies\": \"true\", \"token_dialect\": \"TOKEN_DIALECT\" }", + CURLOPT_POSTFIELDS => "{ "enforce_policies": "true", "token_dialect": "TOKEN_DIALECT" }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "cache-control: no-cache", @@ -167,12 +182,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"enforce_policies\": \"true\", \"token_dialect\": \"TOKEN_DIALECT\" }" +payload = "{ "enforce_policies": "true", "token_dialect": "TOKEN_DIALECT" }" headers = { 'content-type': "application/json", @@ -185,8 +202,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/resource-servers/API_ID", payload, h res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -200,11 +219,13 @@ request = Net::HTTP::Patch.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ \"enforce_policies\": \"true\", \"token_dialect\": \"TOKEN_DIALECT\" }" +request.body = "{ "enforce_policies": "true", "token_dialect": "TOKEN_DIALECT" }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -235,20 +256,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + Remplacez les valeurs `API_ID`, `MGMT_API_ACCESS_TOKEN` et `TOKEN_DIALECT` par leurs valeurs respectives, comme indiqué dans le tableau suivant : diff --git a/main/docs/fr-ca/get-started/apis/set-logical-api.mdx b/main/docs/fr-ca/get-started/apis/set-logical-api.mdx index 22f04f108..546a3b795 100644 --- a/main/docs/fr-ca/get-started/apis/set-logical-api.mdx +++ b/main/docs/fr-ca/get-started/apis/set-logical-api.mdx @@ -88,15 +88,15 @@ Pour en savoir plus sur les flux d’autorisation, consultez [Flux d’authentif -](/docs/images/ + ![Example application sign in page](/images/fr-ca/cdy7uua7fh8z/1ogYIaeDdyGL3Qo511m6Sh/5ab97c1535b2b62523a367594d44d66f/home.png) -](/docs/images/ + 2. Votre serveur d’autorisation Auth0 redirige l’utilisateur vers la page de connexion, où l’utilisateur s’authentifie en utilisant l’une des options de connexion configurées. ![Lock login page](/images/fr-ca/cdy7uua7fh8z/6z6aA5nfA1uwOyx8srhvvI/2435a0909cfe44a57bef3ff27ef24e5b/lock.png) -](/docs/images/ + 3. Si c’est la première fois que l’utilisateur passe par ce flux, il voit une invite de consentement listant les autorisatoins qu’Auth0 donnera à l’application Web monopage. Dans ce cas, on demande à l’utilisateur de donner son consentement pour que l’application puisse accéder à ses contacts et à son calendrier. ![Example application Lock Consent screen](/images/fr-ca/cdy7uua7fh8z/1te4FYRbu0aFcdohdXY2Rv/116bed5515eb2114c39374fb0a258912/consent-screen.png) @@ -117,7 +117,7 @@ Pour en savoir plus sur les flux d’autorisation, consultez [Flux d’authentif -](/docs/images/ + Dans notre exemple, après avoir réussi à vous connecter, vous verrez des boutons qui vous permettront d’appeler l’une ou l’autre de vos API à l’aide du jeton d’accès obtenu auprès de l’API logique. ![Example application user authorized screen](/images/fr-ca/cdy7uua7fh8z/2pGWG5Wa7U1tBPhAJZ7Bat/7e194066560605cc842f20624b80d958/apis.png) diff --git a/main/docs/fr-ca/get-started/applications/confidential-and-public-applications/update-application-ownership.mdx b/main/docs/fr-ca/get-started/applications/confidential-and-public-applications/update-application-ownership.mdx index 673450003..1c38dc220 100644 --- a/main/docs/fr-ca/get-started/applications/confidential-and-public-applications/update-application-ownership.mdx +++ b/main/docs/fr-ca/get-started/applications/confidential-and-public-applications/update-application-ownership.mdx @@ -10,26 +10,33 @@ permalink: "update-application-ownership" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Vous pouvez utiliser l’Auth0 Management API pour mettre à jour la propriété d’une application, ce qui vous permettra de spécifier si une application est enregistrée avec Auth0 comme application première partie ou comme application tierce partie. Effectuez une requête `PATCH` au point de terminaison [Mettre à jour un client](/docs/fr-ca/api/management/v2#!/Clients/patch_clients_by_id). Assurez-vous de remplacer les valeurs des espaces réservés `{yourClientId}`, `{yourMgmtApiAccessToken}`, et `{ownershipBoolean}` avec les valeurs de votre ID client, votre jeton d’accès à Management API, et un booléen représentant la propriété de l’application, respectivement. -export const codeExample1 = `curl --request PATCH \ + +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/clients/%7ByourClientId%7D' \ --header 'authorization: Bearer {yourMgmtApiAccessToken}' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{ "is_first_party": "{ownershipBoolean}" }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/clients/%7ByourClientId%7D"); + --data '{ "is_first_party": "{ownershipBoolean}" }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/clients/%7ByourClientId%7D"); var request = new RestRequest(Method.PATCH); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer {yourMgmtApiAccessToken}"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{ \"is_first_party\": \"{ownershipBoolean}\" }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "is_first_party": "{ownershipBoolean}" }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -42,7 +49,7 @@ func main() { url := "https://{yourDomain}/api/v2/clients/%7ByourClientId%7D" - payload := strings.NewReader("{ \"is_first_party\": \"{ownershipBoolean}\" }") + payload := strings.NewReader("{ "is_first_party": "{ownershipBoolean}" }") req, _ := http.NewRequest("PATCH", url, payload) @@ -58,14 +65,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/clients/%7ByourClientId%7D") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/clients/%7ByourClientId%7D") .header("content-type", "application/json") .header("authorization", "Bearer {yourMgmtApiAccessToken}") .header("cache-control", "no-cache") - .body("{ \"is_first_party\": \"{ownershipBoolean}\" }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "is_first_party": "{ownershipBoolean}" }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -82,8 +93,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer {yourMgmtApiAccessToken}", @@ -109,8 +122,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/clients/%7ByourClientId%7D", @@ -120,7 +135,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{ \"is_first_party\": \"{ownershipBoolean}\" }", + CURLOPT_POSTFIELDS => "{ "is_first_party": "{ownershipBoolean}" }", CURLOPT_HTTPHEADER => [ "authorization: Bearer {yourMgmtApiAccessToken}", "cache-control: no-cache", @@ -137,12 +152,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"is_first_party\": \"{ownershipBoolean}\" }" +payload = "{ "is_first_party": "{ownershipBoolean}" }" headers = { 'content-type': "application/json", @@ -155,8 +172,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/clients/%7ByourClientId%7D", payload res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -170,11 +189,13 @@ request = Net::HTTP::Patch.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer {yourMgmtApiAccessToken}' request["cache-control"] = 'no-cache' -request.body = "{ \"is_first_party\": \"{ownershipBoolean}\" }" +request.body = "{ "is_first_party": "{ownershipBoolean}" }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -202,20 +223,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
diff --git a/main/docs/fr-ca/get-started/applications/confidential-and-public-applications/user-consent-and-third-party-applications.mdx b/main/docs/fr-ca/get-started/applications/confidential-and-public-applications/user-consent-and-third-party-applications.mdx index 6f652ad92..40e501bec 100644 --- a/main/docs/fr-ca/get-started/applications/confidential-and-public-applications/user-consent-and-third-party-applications.mdx +++ b/main/docs/fr-ca/get-started/applications/confidential-and-public-applications/user-consent-and-third-party-applications.mdx @@ -10,6 +10,7 @@ permalink: "user-consent-and-third-party-applications" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Le pipeline d’authentification conforme à l’[OIDC](/docs/fr-ca/authenticate/protocols/openid-connect-protocol) prend charge la définition des serveurs de ressources (tels que les API) en tant qu’entités distinctes des applications. Cela vous permet de découpler les API des applications qui les consomment, et vous permet également de définir des [applications tierces](/docs/fr-ca/get-started/applications/confidential-and-public-applications/first-party-and-third-party-applications) permettant à des tiers d’accéder en toute sécurité à des ressources protégées derrière votre API. @@ -30,7 +31,7 @@ client_id=some_third_party_client &state=... ``` -Le dialogue de consentement de l’utilisateur s’affiche :](/docs/images/ +Le dialogue de consentement de l’utilisateur s’affiche : ![Authorization (Autorisation) - User consent and applications (Applications et consentement utilisateur) - consent-dialog (Dialogue de consentement)](/images/fr-ca/cdy7uua7fh8z/5Cz3aZKw8RRVlMkc5Zl6x7/04e3b4f29cf44e23d39d96c1cf84e10e/2025-02-28_14-56-45.png) @@ -50,20 +51,26 @@ Si vous souhaitez afficher le champ **Description** à la place, vous pouvez le Pour définir l’indicateur **use_scope_descriptions_for_consent** vous devrez faire la requête appropriée à l’API : -export const codeExample1 = `curl --request PATCH \ + +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/tenants/settings' \ --header 'authorization: Bearer API2_ACCESS_TOKEN' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{ "flags": { "use_scope_descriptions_for_consent": true } }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/tenants/settings"); + --data '{ "flags": { "use_scope_descriptions_for_consent": true } }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/tenants/settings"); var request = new RestRequest(Method.PATCH); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer API2_ACCESS_TOKEN"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{ \"flags\": { \"use_scope_descriptions_for_consent\": true } }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "flags": { "use_scope_descriptions_for_consent": true } }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -76,7 +83,7 @@ func main() { url := "https://{yourDomain}/api/v2/tenants/settings" - payload := strings.NewReader("{ \"flags\": { \"use_scope_descriptions_for_consent\": true } }") + payload := strings.NewReader("{ "flags": { "use_scope_descriptions_for_consent": true } }") req, _ := http.NewRequest("PATCH", url, payload) @@ -92,14 +99,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/tenants/settings") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/tenants/settings") .header("content-type", "application/json") .header("authorization", "Bearer API2_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ \"flags\": { \"use_scope_descriptions_for_consent\": true } }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "flags": { "use_scope_descriptions_for_consent": true } }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -116,8 +127,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer API2_ACCESS_TOKEN", @@ -143,8 +156,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/tenants/settings", @@ -154,7 +169,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{ \"flags\": { \"use_scope_descriptions_for_consent\": true } }", + CURLOPT_POSTFIELDS => "{ "flags": { "use_scope_descriptions_for_consent": true } }", CURLOPT_HTTPHEADER => [ "authorization: Bearer API2_ACCESS_TOKEN", "cache-control: no-cache", @@ -171,12 +186,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"flags\": { \"use_scope_descriptions_for_consent\": true } }" +payload = "{ "flags": { "use_scope_descriptions_for_consent": true } }" headers = { 'content-type': "application/json", @@ -189,8 +206,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/tenants/settings", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -204,11 +223,13 @@ request = Net::HTTP::Patch.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer API2_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ \"flags\": { \"use_scope_descriptions_for_consent\": true } }" +request.body = "{ "flags": { "use_scope_descriptions_for_consent": true } }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -236,20 +257,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ## Traiter les autorisations rejetées diff --git a/main/docs/fr-ca/get-started/applications/confidential-and-public-applications/view-application-ownership.mdx b/main/docs/fr-ca/get-started/applications/confidential-and-public-applications/view-application-ownership.mdx index c355c09e5..eb76479e2 100644 --- a/main/docs/fr-ca/get-started/applications/confidential-and-public-applications/view-application-ownership.mdx +++ b/main/docs/fr-ca/get-started/applications/confidential-and-public-applications/view-application-ownership.mdx @@ -10,6 +10,7 @@ permalink: "view-application-ownership" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Vous pouvez utiliser Management API Auth0 pour vérifier si une application est enregistrée avec Auth0 comme application première partie ou comme application tierce partie. @@ -17,14 +18,20 @@ Effectuez une requête `GET` au point de terminaison [Récupérer un client](/do et `{yourMgmtApiAccessToken}` avec votre ID client et votre jeton d’accès de Management API, respectivement. -export const codeExample1 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/clients/%7ByourClientId%7D?fields=is_first_party&include_fields=true' \ - --header 'authorization: Bearer {yourMgmtApiAccessToken}'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/clients/%7ByourClientId%7D?fields=is_first_party&include_fields=true"); + --header 'authorization: Bearer {yourMgmtApiAccessToken}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/clients/%7ByourClientId%7D?fields=is_first_party&include_fields=true"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer {yourMgmtApiAccessToken}"); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -48,11 +55,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/clients/%7ByourClientId%7D?fields=is_first_party&include_fields=true") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/clients/%7ByourClientId%7D?fields=is_first_party&include_fields=true") .header("authorization", "Bearer {yourMgmtApiAccessToken}") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -65,8 +76,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer {yourMgmtApiAccessToken}" }; @@ -86,8 +99,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/clients/%7ByourClientId%7D?fields=is_first_party&include_fields=true", @@ -111,8 +126,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -123,8 +140,10 @@ conn.request("GET", "/{yourDomain}/api/v2/clients/%7ByourClientId%7D?fields=is_f res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -138,8 +157,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer {yourMgmtApiAccessToken}' response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer {yourMgmtApiAccessToken}"] @@ -159,20 +180,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
diff --git a/main/docs/fr-ca/get-started/applications/configure-jar.mdx b/main/docs/fr-ca/get-started/applications/configure-jar.mdx index 26b308cd7..84e6e35ac 100644 --- a/main/docs/fr-ca/get-started/applications/configure-jar.mdx +++ b/main/docs/fr-ca/get-started/applications/configure-jar.mdx @@ -48,7 +48,7 @@ Utilisez Auth0 Dashboard pour configurer votre application afin qu’elle utilis ![Dashboard > Application > Settings > Assign Existing Credentials](/images/fr-ca/cdy7uua7fh8z/HQHhFWTtdfNa5TnZ1dwx6/76bce36d82d24a38eeb0ae617f34b36e/Existing_Creds_-_French.png) -6. Vous aurez également la possibilité d’attribuer un nouvel identiifant.](/docs/images/ +6. Vous aurez également la possibilité d’attribuer un nouvel identiifant. ![Auth0 Dashboard > Applications > Settings > Assign New Credentials](/images/fr-ca/cdy7uua7fh8z/7JfsCBwytWO6Q7hUvdtSwJ/45b2bd194982fc08c87ecae761cfd340/New_Creds_-_French.png) diff --git a/main/docs/fr-ca/get-started/applications/dynamic-client-registration.mdx b/main/docs/fr-ca/get-started/applications/dynamic-client-registration.mdx index b596d2d30..641f6ef31 100644 --- a/main/docs/fr-ca/get-started/applications/dynamic-client-registration.mdx +++ b/main/docs/fr-ca/get-started/applications/dynamic-client-registration.mdx @@ -10,6 +10,7 @@ permalink: "dynamic-client-registration" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Vous pouvez enregistrer dynamiquement des applications tierces pour votre locataire. Cette fonctionnalité est basée sur la spécification [Enregistrement dynamique du client OpenID Connect](https://openid.net/specs/openid-connect-registration-1_0.html). @@ -28,20 +29,26 @@ Pour ce faire, accédez à [Dashboard > Settings (Paramètres) > Advanced (Avanc Vous pouvez également mettre à jour cet indicateur en utilisant le point de terminaison de Management API [`/Tenant/patch_settings`](/docs/fr-ca/api/management/v2#!/Tenants/patch_settings). -export const codeExample1 = `curl --request PATCH \ + +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/tenants/settings' \ --header 'authorization: Bearer API2_ACCESS_TOKEN' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{ "flags": { "enable_dynamic_client_registration": true } }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/tenants/settings"); + --data '{ "flags": { "enable_dynamic_client_registration": true } }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/tenants/settings"); var request = new RestRequest(Method.PATCH); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer API2_ACCESS_TOKEN"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{ \"flags\": { \"enable_dynamic_client_registration\": true } }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "flags": { "enable_dynamic_client_registration": true } }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -54,7 +61,7 @@ func main() { url := "https://{yourDomain}/api/v2/tenants/settings" - payload := strings.NewReader("{ \"flags\": { \"enable_dynamic_client_registration\": true } }") + payload := strings.NewReader("{ "flags": { "enable_dynamic_client_registration": true } }") req, _ := http.NewRequest("PATCH", url, payload) @@ -70,14 +77,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/tenants/settings") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/tenants/settings") .header("content-type", "application/json") .header("authorization", "Bearer API2_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ \"flags\": { \"enable_dynamic_client_registration\": true } }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "flags": { "enable_dynamic_client_registration": true } }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -94,8 +105,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer API2_ACCESS_TOKEN", @@ -121,8 +134,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/tenants/settings", @@ -132,7 +147,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{ \"flags\": { \"enable_dynamic_client_registration\": true } }", + CURLOPT_POSTFIELDS => "{ "flags": { "enable_dynamic_client_registration": true } }", CURLOPT_HTTPHEADER => [ "authorization: Bearer API2_ACCESS_TOKEN", "cache-control: no-cache", @@ -149,12 +164,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"flags\": { \"enable_dynamic_client_registration\": true } }" +payload = "{ "flags": { "enable_dynamic_client_registration": true } }" headers = { 'content-type': "application/json", @@ -167,8 +184,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/tenants/settings", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -182,11 +201,13 @@ request = Net::HTTP::Patch.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer API2_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ \"flags\": { \"enable_dynamic_client_registration\": true } }" +request.body = "{ "flags": { "enable_dynamic_client_registration": true } }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -214,20 +235,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + Vous devez mettre à jour `API2_ACCESS_TOKEN` avec un jeton valide avec la permission `update:tenant_settings`. Pour en savoir plus, lisez [Jetons d’accès à Management API](/docs/fr-ca/secure/tokens/access-tokens/management-api-access-tokens). @@ -241,16 +251,22 @@ Pour enregistrer dynamiquement une application avec Auth0, vous devez envoyer un Pour créer une application portant le nom `Mon application dynamique` et les URL de rappel `https://application.example.com/callback` et `https://application.example.com/callback2`, utilisez l’extrait de code suivant : -export const codeExample11 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oidc/register' \ --header 'content-type: application/json' \ - --data '{"client_name":"My Dynamic Application","redirect_uris": ["https://application.example.com/callback", "https://application.example.com/callback2"]}'`; -export const codeExample12 = `var client = new RestClient("https://{yourDomain}/oidc/register"); + --data '{"client_name":"My Dynamic Application","redirect_uris": ["https://application.example.com/callback", "https://application.example.com/callback2"]}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oidc/register"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\"client_name\":\"My Dynamic Application\",\"redirect_uris\": [\"https://application.example.com/callback\", \"https://application.example.com/callback2\"]}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample13 = `package main +request.AddParameter("application/json", "{"client_name":"My Dynamic Application","redirect_uris": ["https://application.example.com/callback", "https://application.example.com/callback2"]}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -263,7 +279,7 @@ func main() { url := "https://{yourDomain}/oidc/register" - payload := strings.NewReader("{\"client_name\":\"My Dynamic Application\",\"redirect_uris\": [\"https://application.example.com/callback\", \"https://application.example.com/callback2\"]}") + payload := strings.NewReader("{"client_name":"My Dynamic Application","redirect_uris": ["https://application.example.com/callback", "https://application.example.com/callback2"]}") req, _ := http.NewRequest("POST", url, payload) @@ -277,12 +293,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample14 = `HttpResponse response = Unirest.post("https://{yourDomain}/oidc/register") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oidc/register") .header("content-type", "application/json") - .body("{\"client_name\":\"My Dynamic Application\",\"redirect_uris\": [\"https://application.example.com/callback\", \"https://application.example.com/callback2\"]}") - .asString();`; -export const codeExample15 = `var axios = require("axios").default; + .body("{"client_name":"My Dynamic Application","redirect_uris": ["https://application.example.com/callback", "https://application.example.com/callback2"]}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -301,8 +321,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample16 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json" }; NSDictionary *parameters = @{ @"client_name": @"My Dynamic Application", @@ -327,8 +349,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oidc/register", CURLOPT_RETURNTRANSFER => true, @@ -337,7 +361,7 @@ CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", -CURLOPT_POSTFIELDS => "{\"client_name\":\"My Dynamic Application\",\"redirect_uris\": [\"https://application.example.com/callback\", \"https://application.example.com/callback2\"]}", +CURLOPT_POSTFIELDS => "{"client_name":"My Dynamic Application","redirect_uris": ["https://application.example.com/callback", "https://application.example.com/callback2"]}", CURLOPT_HTTPHEADER => [ "content-type: application/json" ], @@ -349,16 +373,20 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"client_name\":\"My Dynamic Application\",\"redirect_uris\": [\"https://application.example.com/callback\", \"https://application.example.com/callback2\"]}" +payload = "{"client_name":"My Dynamic Application","redirect_uris": ["https://application.example.com/callback", "https://application.example.com/callback2"]}" headers = { 'content-type': "application/json" } conn.request("POST", "/{yourDomain}/oidc/register", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' url = URI("https://{yourDomain}/oidc/register") @@ -367,10 +395,12 @@ http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["content-type"] = 'application/json' -request.body = "{\"client_name\":\"My Dynamic Application\",\"redirect_uris\": [\"https://application.example.com/callback\", \"https://application.example.com/callback2\"]}" +request.body = "{"client_name":"My Dynamic Application","redirect_uris": ["https://application.example.com/callback", "https://application.example.com/callback2"]}" response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/json"] let parameters = [ "client_name": "My Dynamic Application", @@ -392,20 +422,9 @@ let httpResponse = response as? HTTPURLResponse print(httpResponse) } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + Où : diff --git a/main/docs/fr-ca/get-started/applications/remove-applications.mdx b/main/docs/fr-ca/get-started/applications/remove-applications.mdx index cb31dd09a..fb8750876 100644 --- a/main/docs/fr-ca/get-started/applications/remove-applications.mdx +++ b/main/docs/fr-ca/get-started/applications/remove-applications.mdx @@ -10,6 +10,7 @@ permalink: "remove-applications" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Vous pouvez supprimer une application à partir de l’Auth0 Dashboard ou de Management API. Une fois confirmée, cette opération ne peut être annulée. @@ -27,14 +28,20 @@ Principal produit d’Auth0 pour configurer vos services." cta="Voir le glossair Faites une requête `DELETE` aux points de terminaison [`/Clients/delete_clients_by_id`](/docs/fr-ca/api/management/v2#!/Clients/delete_clients_by_id). Assurez-vous de remplacer les valeurs des espaces réservés `YOUR_CLIENT_ID` et `MGMT_API_ACCESS_TOKEN` avec votre ID client et votre jeton d’accès de Management API, respectivement. -export const codeExample1 = `curl --request DELETE \ + +```bash cURL +curl --request DELETE \ --url 'https://{yourDomain}/api/v2/clients/%7ByourClientId%7D' \ - --header 'authorization: Bearer {yourMgmtApiToken}'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/clients/%7ByourClientId%7D"); + --header 'authorization: Bearer {yourMgmtApiToken}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/clients/%7ByourClientId%7D"); var request = new RestRequest(Method.DELETE); request.AddHeader("authorization", "Bearer {yourMgmtApiToken}"); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -58,11 +65,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.delete("https://{yourDomain}/api/v2/clients/%7ByourClientId%7D") +} +``` +```java Java +HttpResponse response = Unirest.delete("https://{yourDomain}/api/v2/clients/%7ByourClientId%7D") .header("authorization", "Bearer {yourMgmtApiToken}") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'DELETE', @@ -74,8 +85,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer {yourMgmtApiToken}" }; @@ -95,8 +108,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/clients/%7ByourClientId%7D", @@ -120,8 +135,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -132,8 +149,10 @@ conn.request("DELETE", "/{yourDomain}/api/v2/clients/%7ByourClientId%7D", header res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -147,8 +166,10 @@ request = Net::HTTP::Delete.new(url) request["authorization"] = 'Bearer {yourMgmtApiToken}' response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer {yourMgmtApiToken}"] @@ -168,20 +189,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
diff --git a/main/docs/fr-ca/get-started/applications/rotate-client-secret.mdx b/main/docs/fr-ca/get-started/applications/rotate-client-secret.mdx index cfb30c6e3..4bbf4d1c0 100644 --- a/main/docs/fr-ca/get-started/applications/rotate-client-secret.mdx +++ b/main/docs/fr-ca/get-started/applications/rotate-client-secret.mdx @@ -10,6 +10,7 @@ permalink: "rotate-client-secret" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Vous pouvez modifier le secret client d’une application à l’aide de l’Auth0 Dashboard ou du + +``` +```obj-c Obj-C + #import NSDictionary *headers = @{ @"authorization": @"Bearer {yourMgmtApiAccessToken}" }; @@ -121,8 +134,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request } }]; [dataTask resume]; -`; -export const codeExample7 = ` $curl = curl_init(); + +``` +```php PHP + $curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/clients/%7ByourClientId%7D/rotate-secret", @@ -147,8 +162,10 @@ if ($err) { } else { echo $response; } -`; -export const codeExample8 = ` import http.client + +``` +```python Python + import http.client conn = http.client.HTTPSConnection("") @@ -161,8 +178,10 @@ res = conn.getresponse() data = res.read() print(data.decode("utf-8")) -`; -export const codeExample9 = ` require 'uri' + +``` +```ruby Ruby + require 'uri' require 'net/http' require 'openssl' url = URI("https://{yourDomain}/api/v2/clients/%7ByourClientId%7D/rotate-secret") @@ -173,8 +192,10 @@ request = Net::HTTP::Post.new(url) request["authorization"] = 'Bearer {yourMgmtApiAccessToken}' response = http.request(request) puts response.read_body -`; -export const codeExample10 = ` import Foundation + +``` +```swift Swift + import Foundation let headers = ["authorization": "Bearer {yourMgmtApiAccessToken}"] @@ -195,20 +216,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: }) dataTask.resume() -`; - - - - - - - - - - - - - + +``` +
diff --git a/main/docs/fr-ca/get-started/applications/update-grant-types.mdx b/main/docs/fr-ca/get-started/applications/update-grant-types.mdx index c61c2cf8c..1b6cc10f7 100644 --- a/main/docs/fr-ca/get-started/applications/update-grant-types.mdx +++ b/main/docs/fr-ca/get-started/applications/update-grant-types.mdx @@ -10,6 +10,7 @@ permalink: "update-grant-types" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Vous pouvez changer les types d’autorisation d’une application à l’aide du Auth0 Dashboard (Tableau de bord Auth0) ou de +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/clients/%7ByourClientId%7D' \ --header 'authorization: Bearer {yourMgmtApiAccessToken}' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{ "grant_types": "{grantTypes}" }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/clients/%7ByourClientId%7D"); + --data '{ "grant_types": "{grantTypes}" }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/clients/%7ByourClientId%7D"); var request = new RestRequest(Method.PATCH); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer {yourMgmtApiAccessToken}"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{ \"grant_types\": \"{grantTypes}\" }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "grant_types": "{grantTypes}" }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -56,7 +63,7 @@ func main() { url := "https://{yourDomain}/api/v2/clients/%7ByourClientId%7D" - payload := strings.NewReader("{ \"grant_types\": \"{grantTypes}\" }") + payload := strings.NewReader("{ "grant_types": "{grantTypes}" }") req, _ := http.NewRequest("PATCH", url, payload) @@ -72,14 +79,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/clients/%7ByourClientId%7D") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/clients/%7ByourClientId%7D") .header("content-type", "application/json") .header("authorization", "Bearer {yourMgmtApiAccessToken}") .header("cache-control", "no-cache") - .body("{ \"grant_types\": \"{grantTypes}\" }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "grant_types": "{grantTypes}" }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -96,8 +107,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer {yourMgmtApiAccessToken}", @@ -123,8 +136,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/clients/%7ByourClientId%7D", @@ -134,7 +149,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{ \"grant_types\": \"{grantTypes}\" }", + CURLOPT_POSTFIELDS => "{ "grant_types": "{grantTypes}" }", CURLOPT_HTTPHEADER => [ "authorization: Bearer {yourMgmtApiAccessToken}", "cache-control: no-cache", @@ -151,12 +166,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"grant_types\": \"{grantTypes}\" }" +payload = "{ "grant_types": "{grantTypes}" }" headers = { 'content-type': "application/json", @@ -169,8 +186,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/clients/%7ByourClientId%7D", payload res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -184,11 +203,13 @@ request = Net::HTTP::Patch.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer {yourMgmtApiAccessToken}' request["cache-control"] = 'no-cache' -request.body = "{ \"grant_types\": \"{grantTypes}\" }" +request.body = "{ "grant_types": "{grantTypes}" }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -216,20 +237,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
diff --git a/main/docs/fr-ca/get-started/architecture-scenarios/mobile-api/part-3.mdx b/main/docs/fr-ca/get-started/architecture-scenarios/mobile-api/part-3.mdx index edcb07c90..77d2a1935 100644 --- a/main/docs/fr-ca/get-started/architecture-scenarios/mobile-api/part-3.mdx +++ b/main/docs/fr-ca/get-started/architecture-scenarios/mobile-api/part-3.mdx @@ -10,6 +10,7 @@ permalink: "part-3" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Dans cette section, nous verrons comment nous pouvons mettre en œuvre une API pour notre scénario. @@ -154,20 +155,26 @@ Location: https://{yourDomain}/callback?code=AUTHORIZATION_CODE`; Ensuite vous pouvez échanger le `authorization_code` de la réponse pour un jeton d’accès qui peut être utilisé pour appeler votre API. Réalisez une demande `POST` à l’[URL du jeton](/docs/fr-ca/api/authentication#authorization-code-pkce-) incluant les données suivantes : -export const codeExample3 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=authorization_code \ --data 'client_id={yourClientId}' \ --data code_verified=YOUR_GENERATED_CODE_VERIFIER \ --data code=YOUR_AUTHORIZATION_CODE \ - --data 'redirect_uri=https://{https://yourApp/callback}'`; -export const codeExample4 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data 'redirect_uri=https://{https://yourApp/callback}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=authorization_code&client_id={yourClientId}&code_verified=YOUR_GENERATED_CODE_VERIFIER&code=YOUR_AUTHORIZATION_CODE&redirect_uri=https%3A%2F%2F{https://yourApp/callback}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample5 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -194,12 +201,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample6 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=authorization_code&client_id={yourClientId}&code_verified=YOUR_GENERATED_CODE_VERIFIER&code=YOUR_AUTHORIZATION_CODE&redirect_uri=https%3A%2F%2F{https://yourApp/callback}") - .asString();`; -export const codeExample7 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -218,8 +229,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample8 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -246,8 +259,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample9 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -272,8 +287,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample10 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -286,8 +303,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample11 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -302,8 +321,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=authorization_code&client_id={yourClientId}&code_verified=YOUR_GENERATED_CODE_VERIFIER&code=YOUR_AUTHORIZATION_CODE&redirect_uri=https%3A%2F%2F{https://yourApp/callback}" response = http.request(request) -puts response.read_body`; -export const codeExample12 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -330,20 +351,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
@@ -444,14 +454,20 @@ Un [Jeton d’actualisation](https://auth0.com/docs/tokens/concepts/refresh-tok Votre demande devrait comprendre : -export const codeExample13 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ - --header 'content-type: application/x-www-form-urlencoded'`; -export const codeExample14 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --header 'content-type: application/x-www-form-urlencoded' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); -IRestResponse response = client.Execute(request);`; -export const codeExample15 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -475,11 +491,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample16 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") - .asString();`; -export const codeExample17 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -491,8 +511,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample18 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -515,8 +537,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample19 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -540,8 +564,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample20 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -552,8 +578,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", headers=headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample21 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -567,8 +595,10 @@ request = Net::HTTP::Post.new(url) request["content-type"] = 'application/x-www-form-urlencoded' response = http.request(request) -puts response.read_body`; -export const codeExample22 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -591,20 +621,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
diff --git a/main/docs/fr-ca/get-started/authentication-and-authorization-flow/authorization-code-flow-with-pkce/add-login-using-the-authorization-code-flow-with-pkce.mdx b/main/docs/fr-ca/get-started/authentication-and-authorization-flow/authorization-code-flow-with-pkce/add-login-using-the-authorization-code-flow-with-pkce.mdx index d4b2331c7..7cb35caab 100644 --- a/main/docs/fr-ca/get-started/authentication-and-authorization-flow/authorization-code-flow-with-pkce/add-login-using-the-authorization-code-flow-with-pkce.mdx +++ b/main/docs/fr-ca/get-started/authentication-and-authorization-flow/authorization-code-flow-with-pkce/add-login-using-the-authorization-code-flow-with-pkce.mdx @@ -10,6 +10,7 @@ permalink: "add-login-using-the-authorization-code-flow-with-pkce" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Vous pouvez ajouter une connexion à votre application native, mobile ou à page unique en utilisant le flux de code d’autorisation avec PKCE. Pour savoir comment fonctionne le flux et pourquoi vous devriez l’utiliser, consultez [Flux de code d’autorisation avec Proof Key for Code Exchange (PKCE)](/docs/fr-ca/get-started/authentication-and-authorization-flow/authorization-code-flow-with-pkce). Pour apprendre à appeler votre API à partir d’une application native, mobile ou à page unique, consultez [Appeler votre API en utilisant le flux de code d’autorisation avec PKCE](/docs/fr-ca/get-started/authentication-and-authorization-flow/authorization-code-flow-with-pkce/call-your-api-using-the-authorization-code-flow-with-pkce). @@ -277,20 +278,26 @@ Maintenant que vous avez un code d’authentification, vous pouvez l’échanger ### Exemple d’URL « POST to token » -export const codeExample3 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=authorization_code \ --data 'client_id={yourClientId}' \ --data 'code_verifier={yourGeneratedCodeVerifier}' \ --data 'code={yourAuthorizationCode}' \ - --data 'redirect_uri={https://yourApp/callback}'`; -export const codeExample4 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data 'redirect_uri={https://yourApp/callback}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=authorization_code&client_id={yourClientId}&code_verifier=%7ByourGeneratedCodeVerifier%7D&code=%7ByourAuthorizationCode%7D&redirect_uri={https://yourApp/callback}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample5 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -317,12 +324,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample6 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=authorization_code&client_id={yourClientId}&code_verifier=%7ByourGeneratedCodeVerifier%7D&code=%7ByourAuthorizationCode%7D&redirect_uri={https://yourApp/callback}") - .asString();`; -export const codeExample7 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -341,8 +352,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample8 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -369,8 +382,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample9 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -395,8 +410,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample10 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -409,8 +426,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample11 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -425,8 +444,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=authorization_code&client_id={yourClientId}&code_verifier=%7ByourGeneratedCodeVerifier%7D&code=%7ByourAuthorizationCode%7D&redirect_uri={https://yourApp/callback}" response = http.request(request) -puts response.read_body`; -export const codeExample12 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -453,20 +474,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ### Paramètres diff --git a/main/docs/fr-ca/get-started/authentication-and-authorization-flow/authorization-code-flow-with-pkce/call-your-api-using-the-authorization-code-flow-with-pkce.mdx b/main/docs/fr-ca/get-started/authentication-and-authorization-flow/authorization-code-flow-with-pkce/call-your-api-using-the-authorization-code-flow-with-pkce.mdx index 1bae9f030..ad9d907ce 100644 --- a/main/docs/fr-ca/get-started/authentication-and-authorization-flow/authorization-code-flow-with-pkce/call-your-api-using-the-authorization-code-flow-with-pkce.mdx +++ b/main/docs/fr-ca/get-started/authentication-and-authorization-flow/authorization-code-flow-with-pkce/call-your-api-using-the-authorization-code-flow-with-pkce.mdx @@ -10,6 +10,7 @@ permalink: "call-your-api-using-the-authorization-code-flow-with-pkce" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; @@ -295,20 +296,26 @@ Maintenant que vous avez un code d’authentification, vous pouvez l’échanger #### Exemple de POSR à une URL de jeton -export const codeExample3 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=authorization_code \ --data 'client_id={yourClientId}' \ --data 'code_verifier={yourGeneratedCodeVerifier}' \ --data 'code={yourAuthorizationCode}' \ - --data 'redirect_uri={https://yourApp/callback}'`; -export const codeExample4 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data 'redirect_uri={https://yourApp/callback}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=authorization_code&client_id={yourClientId}&code_verifier=%7ByourGeneratedCodeVerifier%7D&code=%7ByourAuthorizationCode%7D&redirect_uri={https://yourApp/callback}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample5 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -335,12 +342,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample6 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=authorization_code&client_id={yourClientId}&code_verifier=%7ByourGeneratedCodeVerifier%7D&code=%7ByourAuthorizationCode%7D&redirect_uri={https://yourApp/callback}") - .asString();`; -export const codeExample7 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -359,8 +370,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample8 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -387,8 +400,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample9 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -413,8 +428,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample10 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -427,8 +444,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample11 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -443,8 +462,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=authorization_code&client_id={yourClientId}&code_verifier=%7ByourGeneratedCodeVerifier%7D&code=%7ByourAuthorizationCode%7D&redirect_uri={https://yourApp/callback}" response = http.request(request) -puts response.read_body`; -export const codeExample12 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -471,20 +492,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ##### Paramètres @@ -554,7 +564,7 @@ Les jetons d’actualisation doivent être stockés en toute sécurité car ils Pour appeler votre API à partir d’une application native/communication entre machines (M2M), l’application doit transmettre le jeton d’accès récupéré en tant que jeton du porteur dans l’en-tête Authorization (Autorisation) de votre requête HTTP. - + ```bash cURL lines curl --request GET \ --url https://myapi.com/api \ @@ -734,7 +744,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + ### Jetons d’actualisation @@ -749,18 +759,24 @@ Pour actualiser votre jeton, effectuez une requête `POST` au point de terminais #### Exemple de POSR à une URL de jeton -export const codeExample13 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=refresh_token \ --data 'client_id={yourClientId}' \ - --data 'refresh_token={yourRefreshToken}'`; -export const codeExample14 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data 'refresh_token={yourRefreshToken}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=refresh_token&client_id={yourClientId}&refresh_token=%7ByourRefreshToken%7D", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample15 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -787,12 +803,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample16 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=refresh_token&client_id={yourClientId}&refresh_token=%7ByourRefreshToken%7D") - .asString();`; -export const codeExample17 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -809,8 +829,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample18 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -835,8 +857,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample19 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -861,8 +885,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample20 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -875,8 +901,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample21 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -891,8 +919,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=refresh_token&client_id={yourClientId}&refresh_token=%7ByourRefreshToken%7D" response = http.request(request) -puts response.read_body`; -export const codeExample22 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -917,20 +947,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ##### Paramètres diff --git a/main/docs/fr-ca/get-started/authentication-and-authorization-flow/authorization-code-flow/add-login-auth-code-flow.mdx b/main/docs/fr-ca/get-started/authentication-and-authorization-flow/authorization-code-flow/add-login-auth-code-flow.mdx index 65f51d074..874ad5bc7 100644 --- a/main/docs/fr-ca/get-started/authentication-and-authorization-flow/authorization-code-flow/add-login-auth-code-flow.mdx +++ b/main/docs/fr-ca/get-started/authentication-and-authorization-flow/authorization-code-flow/add-login-auth-code-flow.mdx @@ -10,6 +10,7 @@ permalink: "add-login-auth-code-flow" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Vous pouvez ajouter une connexion à votre application Web classique à l’aide du Flux de code d’autorisation. Pour savoir comment fonctionne le flux et pourquoi vous devriez l’utiliser, lisez [Flux du code d’autorisation](/docs/fr-ca/get-started/authentication-and-authorization-flow/authorization-code-flow). Pour appeler votre API à partir d’une application Web ordinaire, lisez [Appeler votre API à l’aide du flux de code d’autorisation](/docs/fr-ca/get-started/authentication-and-authorization-flow/authorization-code-flow/call-your-api-using-the-authorization-code-flow). @@ -127,20 +128,26 @@ Maintenant que vous avez un code d’authentification, vous pouvez l’échanger ### Exemple d’URL « POST to token » -export const codeExample3 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=authorization_code \ --data 'client_id={yourClientId}' \ --data 'client_secret={yourClientSecret}' \ --data 'code=yourAuthorizationCode}' \ - --data 'redirect_uri={https://yourApp/callback}'`; -export const codeExample4 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data 'redirect_uri={https://yourApp/callback}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=authorization_code&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&code=yourAuthorizationCode%7D&redirect_uri={https://yourApp/callback}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample5 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -167,12 +174,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample6 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=authorization_code&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&code=yourAuthorizationCode%7D&redirect_uri={https://yourApp/callback}") - .asString();`; -export const codeExample7 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -191,8 +202,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample8 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -219,8 +232,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample9 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -245,8 +260,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample10 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -259,8 +276,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample11 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -275,8 +294,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=authorization_code&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&code=yourAuthorizationCode%7D&redirect_uri={https://yourApp/callback}" response = http.request(request) -puts response.read_body`; -export const codeExample12 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -303,20 +324,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ### Paramètres diff --git a/main/docs/fr-ca/get-started/authentication-and-authorization-flow/authorization-code-flow/call-your-api-using-the-authorization-code-flow.mdx b/main/docs/fr-ca/get-started/authentication-and-authorization-flow/authorization-code-flow/call-your-api-using-the-authorization-code-flow.mdx index abb2ea6bc..cccc9cbb4 100644 --- a/main/docs/fr-ca/get-started/authentication-and-authorization-flow/authorization-code-flow/call-your-api-using-the-authorization-code-flow.mdx +++ b/main/docs/fr-ca/get-started/authentication-and-authorization-flow/authorization-code-flow/call-your-api-using-the-authorization-code-flow.mdx @@ -10,6 +10,7 @@ permalink: "call-your-api-using-the-authorization-code-flow" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; @@ -144,20 +145,26 @@ Maintenant que vous avez un code d’authentification, vous pouvez l’échanger #### Exemple d’un POST à une URL de jeton -export const codeExample3 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=authorization_code \ --data 'client_id={yourClientId}' \ --data 'client_secret={yourClientSecret}' \ --data 'code=yourAuthorizationCode}' \ - --data 'redirect_uri={https://yourApp/callback}'`; -export const codeExample4 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data 'redirect_uri={https://yourApp/callback}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=authorization_code&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&code=yourAuthorizationCode%7D&redirect_uri={https://yourApp/callback}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample5 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -184,12 +191,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample6 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=authorization_code&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&code=yourAuthorizationCode%7D&redirect_uri={https://yourApp/callback}") - .asString();`; -export const codeExample7 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -208,8 +219,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample8 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -236,8 +249,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample9 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -262,16 +277,20 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample10 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") payload = "grant_type=authorization_code&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&code=yourAuthorizationCode%7D&redirect_uri={https://yourApp/callback}" headers = { 'content-type': "application/x-www-form-urlencoded" } conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample11 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -286,8 +305,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=authorization_code&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&code=yourAuthorizationCode%7D&redirect_uri={https://yourApp/callback}" response = http.request(request) -puts response.read_body`; -export const codeExample12 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -314,20 +335,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ##### Paramètres @@ -398,7 +408,7 @@ Les jetons d’actualisation doivent être stockés en toute sécurité car ils Pour appeler votre API à partir d’une application web ordinaire, l’application doit transmettre le jeton d’accès récupéré en tant que jeton du porteur dans l’en-tête Authorization (Autorisation) de votre requête HTTP. - + ```bash cURL lines curl --request GET \ --url https://myapi.com/api \ @@ -577,7 +587,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + @@ -594,18 +604,24 @@ Pour actualiser votre jeton, effectuez une requête `POST` au point de terminais ##### Exemple de requête POST à une URL de jeton -export const codeExample13 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=refresh_token \ --data 'client_id={yourClientId}' \ - --data 'refresh_token={yourRefreshToken}'`; -export const codeExample14 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data 'refresh_token={yourRefreshToken}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=refresh_token&client_id={yourClientId}&refresh_token=%7ByourRefreshToken%7D", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample15 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -632,12 +648,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample16 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=refresh_token&client_id={yourClientId}&refresh_token=%7ByourRefreshToken%7D") - .asString();`; -export const codeExample17 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -654,8 +674,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample18 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -680,8 +702,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample19 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -706,16 +730,20 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample20 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") payload = "grant_type=refresh_token&client_id={yourClientId}&refresh_token=%7ByourRefreshToken%7D" headers = { 'content-type': "application/x-www-form-urlencoded" } conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample21 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' url = URI("https://{yourDomain}/oauth/token") @@ -726,8 +754,10 @@ request = Net::HTTP::Post.new(url) request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=refresh_token&client_id={yourClientId}&refresh_token=%7ByourRefreshToken%7D" response = http.request(request) -puts response.read_body`; -export const codeExample22 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -752,20 +782,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ###### Paramètres diff --git a/main/docs/fr-ca/get-started/authentication-and-authorization-flow/client-credentials-flow/call-your-api-using-the-client-credentials-flow.mdx b/main/docs/fr-ca/get-started/authentication-and-authorization-flow/client-credentials-flow/call-your-api-using-the-client-credentials-flow.mdx index 72cc46eff..77f865128 100644 --- a/main/docs/fr-ca/get-started/authentication-and-authorization-flow/client-credentials-flow/call-your-api-using-the-client-credentials-flow.mdx +++ b/main/docs/fr-ca/get-started/authentication-and-authorization-flow/client-credentials-flow/call-your-api-using-the-client-credentials-flow.mdx @@ -10,6 +10,7 @@ permalink: "call-your-api-using-the-client-credentials-flow" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; @@ -47,19 +48,25 @@ Pour accéder à votre API, vous devez demander un jeton d’accès. Pour ce fai #### Exemple de POST à une URL de jeton -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=client_credentials \ --data client_id=YOUR_CLIENT_ID \ --data client_secret=YOUR_CLIENT_SECRET \ - --data audience=YOUR_API_IDENTIFIER`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data audience=YOUR_API_IDENTIFIER +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&audience=YOUR_API_IDENTIFIER", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -86,12 +93,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&audience=YOUR_API_IDENTIFIER") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -109,8 +120,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -137,8 +150,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request } }]; [dataTask resume]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -163,8 +178,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -177,8 +194,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -193,8 +212,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&audience=YOUR_API_IDENTIFIER" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -220,20 +241,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ##### Paramètres @@ -289,7 +299,7 @@ Validez vos jetons avant de les enregistrer. Pour en savoir plus, lisez [Valider Pour appeler votre API à partir de l’application machine-machine (M2M), l’application doit transmettre le jeton d’accès récupéré en tant que jeton du porteur dans l’en-tête Authorization de votre requête HTTP. - + ```bash cURL lines curl --request GET \ --url https://myapi.com/api \ @@ -469,7 +479,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + ### Exemples de cas d’utilisation diff --git a/main/docs/fr-ca/get-started/authentication-and-authorization-flow/client-credentials-flow/customize-tokens-using-hooks-with-client-credentials-flow.mdx b/main/docs/fr-ca/get-started/authentication-and-authorization-flow/client-credentials-flow/customize-tokens-using-hooks-with-client-credentials-flow.mdx index a1e9314e2..5ae717e94 100644 --- a/main/docs/fr-ca/get-started/authentication-and-authorization-flow/client-credentials-flow/customize-tokens-using-hooks-with-client-credentials-flow.mdx +++ b/main/docs/fr-ca/get-started/authentication-and-authorization-flow/client-credentials-flow/customize-tokens-using-hooks-with-client-credentials-flow.mdx @@ -10,6 +10,7 @@ permalink: "customize-tokens-using-hooks-with-client-credentials-flow" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; @@ -94,19 +95,25 @@ Pour tester le hook que vous venez de créer, vous devez exécuter un échange d Pour obtenir un jeton, effectuez un appel `POST` au [point de terminaison du Flux des identifiants client](/docs/fr-ca/api/authentication#client-credentials-flow) Assurez-vous de remplacer les valeurs d’espace réservé CLIENT_ID, CLIENT_SECRET et API_IDENTIFIER par l’ID client de votre application, le secret client de votre application et l’identifiant de votre API, respectivement. Vous pouvez trouver l’ID client et le secret client dans les paramètres de votre [Application](https://manage.auth0.com/#/applications) et l’identifiant API dans les paramètres de votre [API](https://manage.auth0.com/#/apis). -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=client_credentials \ --data 'client_id={yourClientId}' \ --data client_secret=YOUR_CLIENT_SECRET \ - --data audience=YOUR_API_IDENTIFIER`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data audience=YOUR_API_IDENTIFIER +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=client_credentials&client_id={yourClientId}&client_secret=YOUR_CLIENT_SECRET&audience=YOUR_API_IDENTIFIER", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -133,12 +140,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=client_credentials&client_id={yourClientId}&client_secret=YOUR_CLIENT_SECRET&audience=YOUR_API_IDENTIFIER") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -156,8 +167,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -183,8 +196,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -209,8 +224,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -223,8 +240,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -239,8 +258,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=client_credentials&client_id={yourClientId}&client_secret=YOUR_CLIENT_SECRET&audience=YOUR_API_IDENTIFIER" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -266,20 +287,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + Une réponse réussie comprendra : diff --git a/main/docs/fr-ca/get-started/authentication-and-authorization-flow/device-authorization-flow/call-your-api-using-the-device-authorization-flow.mdx b/main/docs/fr-ca/get-started/authentication-and-authorization-flow/device-authorization-flow/call-your-api-using-the-device-authorization-flow.mdx index 180a14fb8..62e4c2518 100644 --- a/main/docs/fr-ca/get-started/authentication-and-authorization-flow/device-authorization-flow/call-your-api-using-the-device-authorization-flow.mdx +++ b/main/docs/fr-ca/get-started/authentication-and-authorization-flow/device-authorization-flow/call-your-api-using-the-device-authorization-flow.mdx @@ -10,6 +10,7 @@ permalink: "call-your-api-using-the-device-authorization-flow" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; @@ -61,18 +62,24 @@ Pour obtenir le code de l’appareil, votre application doit demander un code à #### Exemple POST vers l’URL de code d’appareil -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/device/code' \ --header 'content-type: application/x-www-form-urlencoded' \ --data 'client_id={yourClientId}' \ --data 'scope={scope}' \ - --data 'audience={audience}'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/oauth/device/code"); + --data 'audience={audience}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/device/code"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "client_id={yourClientId}&scope=%7Bscope%7D&audience=%7Baudience%7D", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -99,12 +106,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/device/code") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/device/code") .header("content-type", "application/x-www-form-urlencoded") .body("client_id={yourClientId}&scope=%7Bscope%7D&audience=%7Baudience%7D") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -117,8 +128,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -143,8 +156,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/device/code", @@ -169,8 +184,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -183,8 +200,10 @@ conn.request("POST", "/{yourDomain}/oauth/device/code", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -199,8 +218,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "client_id={yourClientId}&scope=%7Bscope%7D&audience=%7Baudience%7D" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -225,20 +246,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ##### Paramètres du code d’appareil @@ -333,25 +343,31 @@ Lorsque vous créez une interface de ligne de commande, vous pouvez ignorer cett ### Demander des jetons -](/docs/images/ + Pendant que vous attendez que l’utilisateur active l’appareil, commencez à interroger l’URL de jeton pour demander un jeton d’accès. En utilisant l’intervalle d’interrogation (`interval`) extrait de l’étape précédente, vous devrez `POST` sur [l’URL de jeton](/docs/fr-ca/api/authentication#device-auth) en l’envoyant avec le `device_code`. Pour éviter des erreurs dues à la latence du réseau, vous devez commencer à compter chaque intervalle après la réception de la réponse de la dernière demande d’interrogation. #### Exemple de demande POST de jeton vers l’URL de jeton. -export const codeExample11 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=urn:ietf:params:oauth:grant-type:device_code \ --data 'device_code={yourDeviceCode}' \ - --data 'client_id={yourClientId}'`; -export const codeExample12 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data 'client_id={yourClientId}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Adevice_code&device_code=%7ByourDeviceCode%7D&client_id={yourClientId}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample13 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -378,12 +394,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample14 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Adevice_code&device_code=%7ByourDeviceCode%7D&client_id={yourClientId}") - .asString();`; -export const codeExample15 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -400,8 +420,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample16 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -426,8 +448,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -452,8 +476,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -466,8 +492,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -482,8 +510,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Adevice_code&device_code=%7ByourDeviceCode%7D&client_id={yourClientId}" response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -508,20 +538,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ##### Paramètres de demande de jeton @@ -675,7 +694,7 @@ Les jetons d’actualisation doivent être stockés en toute sécurité car ils Pour appeler votre API, l’application doit transmettre le jeton d’accès récupéré en tant que jeton du porteur dans l’en-tête d’autorisation de votre requête HTTP. - + ```bash cURL lines curl --request GET \ --url https://myapi.com/api \ @@ -855,7 +874,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + ### Jetons d’actualisation @@ -870,19 +889,25 @@ Pour actualiser votre jeton, effectuez une requête `POST` au point de terminais #### Exemple de jeton d’actualisation POST vers l’URL de jeton. -export const codeExample21 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=refresh_token \ --data 'client_id={yourClientId}' \ --data 'client_secret={yourClientSecret}' \ - --data 'refresh_token={yourRefreshToken}'`; -export const codeExample22 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data 'refresh_token={yourRefreshToken}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=refresh_token&client_id={yourClientId}&client_secret={yourClientSecret}&refresh_token=%7ByourRefreshToken%7D", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample23 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -909,12 +934,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample24 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=refresh_token&client_id={yourClientId}&client_secret={yourClientSecret}&refresh_token=%7ByourRefreshToken%7D") - .asString();`; -export const codeExample25 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -932,8 +961,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample26 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -959,8 +990,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample27 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -985,8 +1018,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample28 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -999,8 +1034,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample29 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -1015,8 +1052,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=refresh_token&client_id={yourClientId}&client_secret={yourClientSecret}&refresh_token=%7ByourRefreshToken%7D" response = http.request(request) -puts response.read_body`; -export const codeExample30 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -1042,20 +1081,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ##### Paramètres de requête de jeton d’actualisation diff --git a/main/docs/fr-ca/get-started/authentication-and-authorization-flow/hybrid-flow/call-api-hybrid-flow.mdx b/main/docs/fr-ca/get-started/authentication-and-authorization-flow/hybrid-flow/call-api-hybrid-flow.mdx index fa6cb48d1..aaa3b5077 100644 --- a/main/docs/fr-ca/get-started/authentication-and-authorization-flow/hybrid-flow/call-api-hybrid-flow.mdx +++ b/main/docs/fr-ca/get-started/authentication-and-authorization-flow/hybrid-flow/call-api-hybrid-flow.mdx @@ -10,6 +10,7 @@ permalink: "call-api-hybrid-flow" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; @@ -217,20 +218,26 @@ Le jeton d’accès que vous recevez à cette étape est celui que vous devez ut #### Exemple de POST à une URL de jeton -export const codeExample3 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=authorization_code \ --data 'client_id={yourClientId}' \ --data 'client_secret={yourClientSecret}' \ --data 'code=yourAuthorizationCode}' \ - --data 'redirect_uri={https://yourApp/callback}'`; -export const codeExample4 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data 'redirect_uri={https://yourApp/callback}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=authorization_code&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&code=yourAuthorizationCode%7D&redirect_uri={https://yourApp/callback}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample5 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -257,12 +264,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample6 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=authorization_code&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&code=yourAuthorizationCode%7D&redirect_uri={https://yourApp/callback}") - .asString();`; -export const codeExample7 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -281,8 +292,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample8 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -309,8 +322,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample9 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -335,8 +350,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample10 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -349,8 +366,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample11 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -365,8 +384,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=authorization_code&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&code=yourAuthorizationCode%7D&redirect_uri={https://yourApp/callback}" response = http.request(request) -puts response.read_body`; -export const codeExample12 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -393,20 +414,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ##### Paramètres @@ -475,7 +485,7 @@ Les jetons d’actualisation doivent être stockés en toute sécurité car ils Pour appeler votre API à partir d’une application Web standard (ou de cas similaires dans lesquels les informations d’identification de l’application peuvent être stockées en toute sécurité), l’application doit transmettre le jeton d’accès récupéré en tant que jeton du porteur dans l’en-tête d’autorisation de votre requête HTTP. - + ```bash cURL lines curl --request GET \ --url https://myapi.com/api \ @@ -655,7 +665,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + ### Jetons d’actualisation @@ -670,18 +680,24 @@ Pour actualiser votre jeton, effectuez une requête `POST` au point de terminais #### Exemple de POST à une URL de jeton -export const codeExample13 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=refresh_token \ --data 'client_id={yourClientId}' \ - --data 'refresh_token={yourRefreshToken}'`; -export const codeExample14 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data 'refresh_token={yourRefreshToken}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=refresh_token&client_id={yourClientId}&refresh_token=%7ByourRefreshToken%7D", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample15 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -708,12 +724,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample16 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=refresh_token&client_id={yourClientId}&refresh_token=%7ByourRefreshToken%7D") - .asString();`; -export const codeExample17 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -730,8 +750,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample18 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -756,8 +778,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample19 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -782,8 +806,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample20 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -796,8 +822,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample21 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -812,8 +840,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=refresh_token&client_id={yourClientId}&refresh_token=%7ByourRefreshToken%7D" response = http.request(request) -puts response.read_body`; -export const codeExample22 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -838,20 +868,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ##### Paramètres diff --git a/main/docs/fr-ca/get-started/authentication-and-authorization-flow/resource-owner-password-flow/call-your-api-using-resource-owner-password-flow.mdx b/main/docs/fr-ca/get-started/authentication-and-authorization-flow/resource-owner-password-flow/call-your-api-using-resource-owner-password-flow.mdx index 273e1fbac..0084ac1cf 100644 --- a/main/docs/fr-ca/get-started/authentication-and-authorization-flow/resource-owner-password-flow/call-your-api-using-resource-owner-password-flow.mdx +++ b/main/docs/fr-ca/get-started/authentication-and-authorization-flow/resource-owner-password-flow/call-your-api-using-resource-owner-password-flow.mdx @@ -10,6 +10,7 @@ permalink: "call-your-api-using-resource-owner-password-flow" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; @@ -74,7 +75,9 @@ Pour appeler votre API, vous devez d’abord obtenir les identifiants de l’uti #### Exemple d’un POST à une URL de jeton -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=password \ @@ -83,13 +86,17 @@ export const codeExample1 = `curl --request POST \ --data 'audience={yourApiIdentifier}' \ --data scope=read:sample \ --data 'client_id={yourClientId}' \ - --data 'client_secret={yourClientSecret}'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data 'client_secret={yourClientSecret}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=password&username=%7Busername%7D&password=%7Bpassword%7D&audience=%7ByourApiIdentifier%7D&scope=read%3Asample&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -116,12 +123,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=password&username=%7Busername%7D&password=%7Bpassword%7D&audience=%7ByourApiIdentifier%7D&scope=read%3Asample&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -142,8 +153,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -172,8 +185,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -198,8 +213,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -212,8 +229,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -228,8 +247,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=password&username=%7Busername%7D&password=%7Bpassword%7D&audience=%7ByourApiIdentifier%7D&scope=read%3Asample&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -258,20 +279,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ##### Paramètres @@ -363,7 +373,7 @@ Si vous avez besoin des informations de l’utilisateur, incluez la permission ` Pour appeler votre API, l’application doit transmettre le jeton d’accès récupéré en tant que jeton du porteur dans l’en-tête d’autorisation de votre requête HTTP. - + ```bash cURL lines curl --request GET \ --url https://myapi.com/api \ @@ -543,7 +553,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + ### Jetons d’actualisation @@ -558,18 +568,24 @@ Pour actualiser votre jeton, effectuez une requête `POST` au point de terminais #### Exemple d’un POST à une URL de jeton -export const codeExample11 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=refresh_token \ --data 'client_id={yourClientId}' \ - --data 'refresh_token={yourRefreshToken}'`; -export const codeExample12 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data 'refresh_token={yourRefreshToken}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=refresh_token&client_id={yourClientId}&refresh_token=%7ByourRefreshToken%7D", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample13 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -596,12 +612,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample14 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=refresh_token&client_id={yourClientId}&refresh_token=%7ByourRefreshToken%7D") - .asString();`; -export const codeExample15 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -618,8 +638,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample16 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -644,8 +666,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -670,8 +694,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -684,8 +710,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -700,8 +728,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=refresh_token&client_id={yourClientId}&refresh_token=%7ByourRefreshToken%7D" response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -726,20 +756,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ##### Paramètres diff --git a/main/docs/fr-ca/get-started/onboarding/self-service-m2m.mdx b/main/docs/fr-ca/get-started/onboarding/self-service-m2m.mdx index 4895d3fc4..da7da6e1d 100644 --- a/main/docs/fr-ca/get-started/onboarding/self-service-m2m.mdx +++ b/main/docs/fr-ca/get-started/onboarding/self-service-m2m.mdx @@ -10,6 +10,7 @@ permalink: "self-service-m2m" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Si votre cas d’utilisation s’adresse à une audience non interactive comme des API ou des serveurs dorsaux, vous serez intégré avec une configuration machine-machine (M2M). @@ -174,7 +175,7 @@ Si vous créez votre API dans Dashboard, Auth0 génère automatiquement une appl . 3. Passez à la vue **API**, puis localisez l’API que vous souhaitez activer pour cette application. 4. Activez la bascule **Authorize (Autoriser)**, puis sélectionnez le bouton fléché à droite pour développer la carte. -5. Sélectionnez **Update (Mise à jour)**.](/docs/images/ +5. Sélectionnez **Update (Mise à jour)**. ![Dashboard > Applications > APIs](/images/fr-ca/cdy7uua7fh8z/6L2R46XVdYw1kifRfMifRz/edee29a7ba67ba10f2ced2543f6ef581/Timesheet_API_Config.png) @@ -240,19 +241,25 @@ Auth0 prend en charge d’autres méthodes d’authentification client en plus d Une demande au point de terminaison `/oauth/token` doit être similaire à l’exemple ci-dessous : -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=client_credentials \ --data client_id=YOUR_CLIENT_ID \ --data client_secret=YOUR_CLIENT_SECRET \ - --data audience=YOUR_API_IDENTIFIER`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data audience=YOUR_API_IDENTIFIER +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&audience=YOUR_API_IDENTIFIER", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -279,12 +286,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&audience=YOUR_API_IDENTIFIER") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -302,8 +313,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -329,8 +342,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -355,8 +370,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -369,8 +386,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -385,8 +404,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&audience=YOUR_API_IDENTIFIER" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -412,20 +433,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + La réponse devrait être similaire à l’exemple ci-dessous : diff --git a/main/docs/fr-ca/get-started/tenant-settings/signing-keys/revoke-signing-keys.mdx b/main/docs/fr-ca/get-started/tenant-settings/signing-keys/revoke-signing-keys.mdx index 91a8d866f..8ce18cdee 100644 --- a/main/docs/fr-ca/get-started/tenant-settings/signing-keys/revoke-signing-keys.mdx +++ b/main/docs/fr-ca/get-started/tenant-settings/signing-keys/revoke-signing-keys.mdx @@ -10,6 +10,7 @@ permalink: "revoke-signing-keys" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Vous pouvez révoquer la clé de connexion de l’application ou de l’API de votre locataire en utilisant Auth0 Dashboard ou Management API. La clé de connexion est utilisée pour signer les jetons d’ID, les jetons d’accès, les assertions SAML et les assertions + +``` +```obj-c Obj-C + #import NSDictionary *headers = @{ @"authorization": @"Bearer {yourMgmtApiAccessToken}" }; @@ -127,8 +140,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request } }]; [dataTask resume]; -`; -export const codeExample7 = ` $curl = curl_init(); + +``` +```php PHP + $curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/keys/signing/%7ByourKeyId%7D/revoke", @@ -153,8 +168,10 @@ echo "cURL Error #:" . $err; } else { echo $response; } -`; -export const codeExample8 = ` import http.client + +``` +```python Python + import http.client conn = http.client.HTTPSConnection("") @@ -166,8 +183,10 @@ res = conn.getresponse() data = res.read() print(data.decode("utf-8")) -`; -export const codeExample9 = ` require 'uri' + +``` +```ruby Ruby + require 'uri' require 'net/http' require 'openssl' @@ -182,8 +201,10 @@ request["authorization"] = 'Bearer {yourMgmtApiAccessToken}' response = http.request(request) puts response.read_body -`; -export const codeExample10 = ` import Foundation + +``` +```swift Swift + import Foundation let headers = ["authorization": "Bearer {yourMgmtApiAccessToken}"] @@ -204,20 +225,9 @@ if (error != nil) { }) dataTask.resume() -`; - - - - - - - - - - - - - + +``` +
diff --git a/main/docs/fr-ca/get-started/tenant-settings/signing-keys/rotate-signing-keys.mdx b/main/docs/fr-ca/get-started/tenant-settings/signing-keys/rotate-signing-keys.mdx index 7f1ac666a..4e7f2539b 100644 --- a/main/docs/fr-ca/get-started/tenant-settings/signing-keys/rotate-signing-keys.mdx +++ b/main/docs/fr-ca/get-started/tenant-settings/signing-keys/rotate-signing-keys.mdx @@ -10,6 +10,7 @@ permalink: "rotate-signing-keys" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Vous pouvez faire pivoter manuellement et périodiquement une clé de connexion afin de modifier la clé Web JSON (JWK) utilisée par les applications et les API pour valider les jetons. Si votre application ou API **ne** permet pas ce changement de clé et tente d’utiliser une clé de connexion expirée pour vérifier un jeton, la demande d’authentification échouera. @@ -39,7 +40,7 @@ Un produit permettant aux clients d’effectuer des tâches administratives." ct ![Tableau de bord Paramètres de locataire Onglet Clés d’authentification](/images/fr-ca/cdy7uua7fh8z/7r8t3EGctFmvkCgPrU0i2R/bb24776ecacfeb67abc471b125d84ef4/Signing_Keys_-_FR.png) 2. Sous **Rotation Settings (Paramètres de rotation)**, localisez **Rotate Signing Key (Faire pivoter la clé de connexion)** et sélectionnez **Rotate Key (Faire pivoter la clé)**. -3. Cliquez sur **Rotation** pour confirmer.](/docs/images/ +3. Cliquez sur **Rotation** pour confirmer. ![Tableau de bord Paramètres Clés d’authentification Onglet Confirmation de la rotation](/images/fr-ca/cdy7uua7fh8z/6Ofp24mgt8ZrvaxF2wLA5N/34f20aa70259d4f55729eb35d2ebf248/Rotate_Keys_-_FR.png) @@ -48,16 +49,22 @@ Un produit permettant aux clients d’effectuer des tâches administratives." ct 1. Pour obtenir une liste des clés d’authentification, effectuez un appel `GET` au point de terminaison [Obtenir toutes les clés de connexion d’application](/docs/fr-ca/api/management/v2#!/Keys/get_signing_keys). 2. Pour faire pivoter la clé de connexion, effectuez un appel `POST` au point de terminaison [Rotate the Application Signing Key](/docs/fr-ca/api/management/v2#!/Keys/post_signing_keys) (Faire pivoter la clé de connexion d’application). Assurez-vous de remplacer la valeur de remplacement `MGMT_API_ACCESS_TOKEN` par votre jeton d’accès de Management API. -export const codeExample1 = ` curl --request POST \ + +```bash cURL + curl --request POST \ --url 'https://{yourDomain}/api/v2/keys/signing/rotate' \ --header 'authorization: Bearer {yourMgmtApiAccessToken}' -`; -export const codeExample2 = ` var client = new RestClient("https://{yourDomain}/api/v2/keys/signing/rotate"); + +``` +```csharp C# + var client = new RestClient("https://{yourDomain}/api/v2/keys/signing/rotate"); var request = new RestRequest(Method.POST); request.AddHeader("authorization", "Bearer {yourMgmtApiAccessToken}"); IRestResponse response = client.Execute(request); -`; -export const codeExample3 = ` package main + +``` +```go Go + package main import ( "fmt" @@ -82,12 +89,16 @@ func main() { fmt.Println(string(body)) } -`; -export const codeExample4 = ` HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/keys/signing/rotate") + +``` +```java Java + HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/keys/signing/rotate") .header("authorization", "Bearer {yourMgmtApiAccessToken}") .asString(); -`; -export const codeExample5 = ` var axios = require("axios").default; + +``` +```javascript Node.JS + var axios = require("axios").default; var options = { method: 'POST', @@ -100,8 +111,10 @@ console.log(response.data); }).catch(function (error) { console.error(error); }); -`; -export const codeExample6 = ` #import + +``` +```obj-c Obj-C + #import NSDictionary *headers = @{ @"authorization": @"Bearer {yourMgmtApiAccessToken}" }; @@ -122,8 +135,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request } }]; [dataTask resume]; -`; -export const codeExample7 = ` $curl = curl_init(); + +``` +```php PHP + $curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/keys/signing/rotate", @@ -148,8 +163,10 @@ echo "cURL Error #:" . $err; } else { echo $response; } -`; -export const codeExample8 = ` import http.client + +``` +```python Python + import http.client conn = http.client.HTTPSConnection("") @@ -161,8 +178,10 @@ res = conn.getresponse() data = res.read() print(data.decode("utf-8")) -`; -export const codeExample9 = ` require 'uri' + +``` +```ruby Ruby + require 'uri' require 'net/http' require 'openssl' @@ -177,8 +196,10 @@ request["authorization"] = 'Bearer {yourMgmtApiAccessToken}' response = http.request(request) puts response.read_body -`; -export const codeExample10 = ` import Foundation + +``` +```swift Swift + import Foundation let headers = ["authorization": "Bearer {yourMgmtApiAccessToken}"] @@ -199,20 +220,9 @@ if (error != nil) { }) dataTask.resume() -`; - - - - - - - - - - - - - + +``` +
diff --git a/main/docs/fr-ca/get-started/tenant-settings/signing-keys/view-signing-certificates.mdx b/main/docs/fr-ca/get-started/tenant-settings/signing-keys/view-signing-certificates.mdx index b044f8962..d74ce13e8 100644 --- a/main/docs/fr-ca/get-started/tenant-settings/signing-keys/view-signing-certificates.mdx +++ b/main/docs/fr-ca/get-started/tenant-settings/signing-keys/view-signing-certificates.mdx @@ -10,6 +10,7 @@ permalink: "view-signing-certificates" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Vous pouvez afficher les secrets client et les clés de connexion de l’application de votre locataire à l’aide de l’Auth0 Dashboard ou de +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer {yourMgmtApiAccessToken}" }; @@ -124,8 +137,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/keys/signing", @@ -149,8 +164,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -161,8 +178,10 @@ conn.request("GET", "/{yourDomain}/api/v2/keys/signing", headers=headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -176,8 +195,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer {yourMgmtApiAccessToken}' response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer {yourMgmtApiAccessToken}"] @@ -197,20 +218,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
@@ -230,14 +240,20 @@ dataTask.resume()`; Effectuez un appel `GET` vers le point de terminaison [`/signing_keys/get_signing_key`](/docs/fr-ca/api/management/v2#!/signing_keys/get_signing_key). Assurez-vous de remplacer les valeurs des espaces réservés `{yourKeyId}` et `{yourMgmtApiAccessToken}` par votre ID de clé de connexion et votre jeton d’accès de Management API, respectivement. -export const codeExample11 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/keys/signing/%7ByourKeyId%7D' \ - --header 'authorization: Bearer {yourMgmtApiAccessToken}'`; -export const codeExample12 = `var client = new RestClient("https://{yourDomain}/api/v2/keys/signing/%7ByourKeyId%7D"); + --header 'authorization: Bearer {yourMgmtApiAccessToken}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/keys/signing/%7ByourKeyId%7D"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer {yourMgmtApiAccessToken}"); -IRestResponse response = client.Execute(request);`; -export const codeExample13 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -261,11 +277,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample14 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/keys/signing/%7ByourKeyId%7D") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/keys/signing/%7ByourKeyId%7D") .header("authorization", "Bearer {yourMgmtApiAccessToken}") - .asString();`; -export const codeExample15 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -277,8 +297,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample16 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer {yourMgmtApiAccessToken}" }; @@ -298,8 +320,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/keys/signing/%7ByourKeyId%7D", @@ -323,8 +347,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -335,8 +361,10 @@ conn.request("GET", "/{yourDomain}/api/v2/keys/signing/%7ByourKeyId%7D", headers res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -350,8 +378,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer {yourMgmtApiAccessToken}' response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer {yourMgmtApiAccessToken}"] @@ -371,20 +401,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
diff --git a/main/docs/fr-ca/libraries/lock/lock-api-reference.mdx b/main/docs/fr-ca/libraries/lock/lock-api-reference.mdx index ec88d2aaf..f9a0ebdcb 100644 --- a/main/docs/fr-ca/libraries/lock/lock-api-reference.mdx +++ b/main/docs/fr-ca/libraries/lock/lock-api-reference.mdx @@ -27,9 +27,9 @@ Lock has many methods, features, and configurable options. This reference is des Initialise une nouvelle instance de `Auth0Lock` configurée avec le `clientID` de votre application et le `domain` de votre compte à partir de votre [Auth0](https://manage.auth0.com/#/) Dashboard. Le troisième paramètre, facultatif, est un objet `options` utilisé pour configurer Lock en fonction des besoins de votre application. Vous trouverez ces informations dans vos [paramètres d’application](https://manage.auth0.com/#/applications). -* **clientId {String}**: Required parameter. Your application’s clientId in Auth0. -* **domain {String}**: paramètre obligatoire. Votre domaine Auth0. En général, il s’agit de your-account.auth0.com. -* **options {Object}**: Optional parameter. Allows for the configuration of Lock’s appearance and behavior. See [the configuration options page](/docs/fr-ca/libraries/lock/lock-configuration) for details. +* **clientId `{String}`**: Required parameter. Your application’s clientId in Auth0. +* **domain `{String}`**: paramètre obligatoire. Votre domaine Auth0. En général, il s’agit de your-account.auth0.com. +* **options `{Object}`**: Optional parameter. Allows for the configuration of Lock’s appearance and behavior. See [the configuration options page](/docs/fr-ca/libraries/lock/lock-configuration) for details. @@ -78,7 +78,7 @@ export const codeExample1 = `var Auth = (function() { Once the user has logged in and you are in possession of a token, you can use that token to obtain the user’s profile with `getUserInfo`. This method replaces the deprecated `getProfile()`. -* **accessToken {String}**: jeton utilisateur. +* **accessToken `{String}`**: jeton utilisateur. * **callback {Function}**: sera invoqué après récupération du profil utilisateur. ```javascript lines @@ -128,8 +128,8 @@ Il existe une option supplémentaire qui peut être définie dans la méthode `s L’objet n’est disponible comme option que pour la méthode `show`; il n’est pas disponible avec l’objet `options` normal lors de l’instanciation de Lock. L’objet `flashMessage` affiche un message flash d’erreur ou de réussite lors de l’affichage du Lock. Il possède les paramètres suivants : -* **type** {String}: le type de message, qui doit être soit `error`, soit `success`. -* **text** {String}: Le texte à afficher. +* **type** `{String}`: le type de message, qui doit être soit `error`, soit `success`. +* **text** `{String}`: Le texte à afficher. ```javascript lines lock.show({ @@ -243,7 +243,7 @@ export const codeExample2 = `var Auth = (function() { This method can only be used when you set the [auth.autoParseHash](/docs/fr-ca/libraries/lock/lock-configuration) option to `false`. You’ll need to call `resumeAuth` to complete the authentication flow. This method is useful when you’re using a client-side router that uses a `#` to handle urls (angular2 with `useHash`, or react-router with `hashHistory`). -* **hash** {String}: le fragment de hachage reçu de la redirection. +* **hash** `{String}`: le fragment de hachage reçu de la redirection. * **callback** {Function}: sera invoqué une fois l’analyse terminée. Le premier argument est une erreur (le cas échéant) et le second est le résultat de l’authentification. S’il n’y a pas de hash disponible, les deux arguments seront `null`. ```javascript lines @@ -260,7 +260,7 @@ lock.resumeAuth(hash, function(error, authResult) { La méthode `checkSession` vous permet d’acquérir un nouveau jeton auprès d’Auth0 pour un utilisateur qui est déjà authentifié auprès d’Auth0 pour votre domaine. Elle prend les paramètres suivants : -* **options** {Object}: Optional. Accepts any valid OAuth2 parameters that would normally be sent to `/authorize`. Si vous les oubliez, les paramètres utilisés seront ceux fournis au moment de l’initialisation d’Auth0. +* **options** `{Object}`: Optional. Accepts any valid OAuth2 parameters that would normally be sent to `/authorize`. Si vous les oubliez, les paramètres utilisés seront ceux fournis au moment de l’initialisation d’Auth0. * **callback** {Function}: sera invoqué avec le résultat du renouvellement du jeton. Le premier argument est une erreur (le cas échéant) et le second est le résultat de l’authentification. ```javascript lines @@ -273,7 +273,7 @@ lock.checkSession({}, function(err, authResult) { Déconnecte l’utilisateur. -* **options** {Object}: facultatif, suit les mêmes règles que auth0.js logout(). +* **options** `{Object}`: facultatif, suit les mêmes règles que auth0.js logout(). ```javascript lines lock.logout({ diff --git a/main/docs/fr-ca/libraries/lock/lock-configuration.mdx b/main/docs/fr-ca/libraries/lock/lock-configuration.mdx index d75088138..df2dcad38 100644 --- a/main/docs/fr-ca/libraries/lock/lock-configuration.mdx +++ b/main/docs/fr-ca/libraries/lock/lock-configuration.mdx @@ -293,13 +293,13 @@ Les options d’authentification sont groupées dans la propriété `auth` de l ## Options UI -### allowAutocomplete {Boolean} +### allowAutocomplete `{Boolean}` Détermine si les champs du courriel ou du nom d’utilisateur autoriseront ou non la saisie semi-automatique (``). La valeur par défaut est false. `allowAutocomplete: true` -### allowPasswordAutocomplete {Boolean} +### allowPasswordAutocomplete `{Boolean}` Détermine si le champ du mot de passe autorisera ou non la saisie semi-automatique (``). La valeur par défaut est `false`. @@ -307,7 +307,7 @@ Réglez `allowPasswordAutocomplete` à `true` pour la prise en charge du gestion `allowPasswordAutocomplete: true` -### allowShowPassword {Boolean} +### allowShowPassword `{Boolean}` Cette option détermine s’il faut ou non ajouter une case à cocher à l’interface utilisateur qui, lorsqu’elle est sélectionnée, permettra à l’utilisateur d’afficher son mot de passe lors de sa saisie. L’option par défaut est `false`. @@ -327,25 +327,25 @@ Tableau de connexions qui seront utilisées pour les actions de `signin|signup|r `allowedConnections: ['qraftlabs.com']` -Exemples de `allowedConnections`:](/docs/images/ +Exemples de `allowedConnections`: ![Lock Option: Allowed Connections - Databa](/docs/images/s/fr-ca/cdy7uua7fh8z/1mllPDLFCCETwQ9MeGEf3W/763728971302656618ef3bd131ab83b1/lock-allowedconnections-database.png)![Lock Option: Allowed Connections - Social](/images/fr-ca/cdy7uua7fh8z/7uYN4ebrLLM8bjx1fee8j0/1e716cca3e1bae990063e9226dfe9ac2/lock-allowedconnections-social.png) -### autoclose {Boolean} +### autoclose `{Boolean}` Détermine si Lock sera fermé automatiquement après une connexion réussie. La valeur par défaut est false. Si Lock n'est pas `closable`, il ne sera pas fermé, même si cette option est définie sur true. `autoclose: true` -### autofocus {Boolean} +### autofocus `{Boolean}` Si c’est true, le focus est défini sur le premier champ du gadget logiciel. Par défaut sur `false` lorsqu’il est rendu sur un appareil mobile, ou si une option `container` est fournie; par défaut sur `true` dans tous les autres cas. `autofocus: false` -### avatar {Object} +### avatar `{Object}` Par défaut, Gravatar est utilisé pour récupérer l’avatar et le nom d’affichage de l’utilisateur, mais vous pouvez les obtenir de n’importe où avec l’option `avatar`. @@ -379,15 +379,15 @@ Comportement par défaut avec](/docs/images/: ![Lock Option: Avatar](/images/fr-ca/cdy7uua7fh8z/69Nz0QoQifPWpfBZwX15J0/204aad93cde406f0ed3771ce38766f56/lock-avatar.png) -### closable {Boolean} +### closable `{Boolean}` Détermine si le verrou peut être fermé ou non. Lorsqu’une option de `container` est fournie, sa valeur est toujours `false`, sinon elle est `true` par défaut. -`closable: false`](/docs/images/ +`closable: false` ![Lock Option: Closable](/images/fr-ca/cdy7uua7fh8z/2qwXtPQev1nlpyOQauXKBO/f967e1157972ecbf5b030b3be3600f2e/lock-closable.png) -### container {String} +### container `{String}` L'`identifiant` de l’élément html où le gadget logiciel sera affiché. @@ -407,16 +407,16 @@ Cela fait apparaître le gadget logiciel en ligne dans votre `div` plutôt que d // render lock.show(); -```](/docs/images/ +``` ![Lock Option: Container](/images/fr-ca/cdy7uua7fh8z/5L4S47Yfset2DR9pjcqVrX/1c4d1928cf75acf40129ffd01394bf33/lock-container.png) -### flashMessage {Object} +### flashMessage `{Object}` Affiche un message éclair `error` ou de `success` lorsque Lock est affiché. Cet objet a les propriétés suivantes : -* type {String}  : Le type de message, les types supportés sont `error`, `info`, et `success` -* text {String} : Le texte à afficher. +* type `{String}`  : Le type de message, les types supportés sont `error`, `info`, et `success` +* text `{String}` : Le texte à afficher. ```javascript lines var options = { @@ -427,15 +427,15 @@ var options = { }; ``` -### language {String} +### language `{String}` Spécifie la langue du gadget logiciel. La valeur par défaut est « en ». Consultez le [répertoire d’internationalisation](https://github.com/auth0/lock/blob/master/src/i18n/) pour une liste actuelle des langues fournies. -`language: 'es'`](/docs/images/ +`language: 'es'` ![Lock Option: Language](/images/fr-ca/cdy7uua7fh8z/3u3lytCUBDbcKmXFV34OUv/5cf5d7e1af9593a3b094f32815a4da11/lock-language.png) -### languageDictionary {Object} +### languageDictionary `{Object}` Permet de personnaliser chaque élément de texte affiché dans Lock. La valeur par défaut est {}. Voir [Spécification du dictionnaire de langue](https://github.com/auth0/lock/blob/master/src/i18n/en.js) en anglais pour la liste complète des valeurs `LanguageDictionary` pouvant être modifiées avec cet objet. @@ -446,13 +446,13 @@ var options = { title: "Log me in" }, }; -```](/docs/images/ +``` ![Lock Option: Language Dictionary](/images/fr-ca/cdy7uua7fh8z/5203ofwtagtIKGT4HnIPmk/8ad9cdd151a2cdb18b8a42ee47dbf679/lock-languagedictionary.png) De plus, consultez la page [Personnalisation des messages d’erreur](/docs/fr-ca/customize/login-pages/classic-login/customize-lock-error-messages) ou la page [Internationalisation](/docs/fr-ca/customize/internationalization-and-localization/lock-internationalization) pour plus d’informations sur l’utilisation de l’option `LanguageDictionary`. -### popupOptions {Object} +### popupOptions `{Object}` Permet de personnaliser l’emplacement de la fenêtre contextuelle dans l’écran. Toute fonctionnalité de position et de taille autorisée par window.open est acceptée. La valeur par défaut est {}. @@ -467,7 +467,7 @@ var options = { }; ``` -### rememberLastLogin {Boolean} +### rememberLastLogin `{Boolean}` Détermine s’il faut ou non afficher un écran qui vous permet de vous connecter rapidement avec le compte que vous avez utilisé la dernière fois. Demande des données d’authentification unique ( -### autoParseHash {Boolean} +### autoParseHash `{Boolean}` Lorsque `autoParseHash` est défini sur `true`, Lock analysera la chaîne `window.location.hash` une fois instanciée. S’il est défini sur `false`, vous devrez reprendre manuellement l’authentification à l’aide de la méthode [summaryAuth](/docs/fr-ca/libraries/lock/lock-api-reference). @@ -631,7 +631,7 @@ var options = { }; ``` -### connectionScopes {Object} +### connectionScopes `{Object}` Cette option vous permet de définir les permissions à envoyer à la connexion oauth2/média social pour l’authentification. @@ -647,7 +647,7 @@ var options = { Une liste de domaines particuliers pour vos connexions aux médias sociaux peut être obtenue auprès du fournisseur en question. Par exemple, la référence [Facebook for Developers](https://developers.facebook.com/docs/facebook-login/permissions/) a une liste d’autorisations distinctes qui peuvent être demandées pour votre connexion. -### params {Object} +### params `{Object}` Vous pouvez envoyer des paramètres lors du démarrage d’une connexion en les ajoutant à l’objet options. L’exemple ci-dessous ajoute un paramètre `state` avec une valeur égale à `foo` et ajoute également un paramètre `scope` (qui inclut la permission, puis les attributs demandés). @@ -664,7 +664,7 @@ var options = { Pour plus de détails sur les paramètres pris en charge, consultez [Paramètres d’authentification de Lock](/docs/fr-ca/libraries/lock/lock-authentication-parameters). -### redirect {Boolean} +### redirect `{Boolean}` La valeur par défaut est true. Lorsqu’il est défini sur true, le mode de redirection sera utilisé. S’il est défini sur false, le [mode fenêtre contextuelle](/docs/fr-ca/libraries/lock/lock-authentication-modes) est choisi. @@ -676,7 +676,7 @@ var options = { }; ``` -### redirectUrl {String} +### redirectUrl `{String}` L’URL Auth0 de redirectiion après l’authentification. La valeur par défaut est le lien vide "" (pas d’URL de redirection). @@ -690,7 +690,7 @@ var options = { Lorsque `redirectUrl` est fourni (défini sur une valeur non vide), l’option `responseType` sera définie par défaut sur `code` si elle n’est pas définie manuellement. -### responseMode {String} +### responseMode `{String}` Doit être défini sur `« form_post »` si vous souhaitez que le code ou le jeton soit transmis via une requête HTTP POST à `​​redirectUrl`, au lieu d’être inclus dans ses parties de requête ou de fragment. @@ -704,7 +704,7 @@ var options = { }; ``` -### responseType {String} +### responseType `{String}` La valeur `responseType` doit être définie sur « token » pour les applications à page unique et sur « code » dans le cas contraire. La valeur par défaut est « code » lorsque redirectUrl est fourni, et « token » dans le cas contraire. @@ -718,7 +718,7 @@ var options = { Lorsque `responsetype` est défini sur `code`, Lock n’affichera jamais un message **Dernière fois que vous vous êtes connecté avec** et demandera toujours à l’utilisateur ses informations d’identification. -## sso {Boolean} +## sso `{Boolean}` La valeur par défaut est vrai. Lorsqu’il est défini sur true, il active l'[authentification unique](/docs/fr-ca/authenticate/single-sign-on) dans Lock. @@ -793,7 +793,7 @@ var options = { storage: "root" }] }; -```](/docs/images/ +``` ![Lock Option: Additional Signup Fields](/images/fr-ca/cdy7uua7fh8z/2KPDGZb3caq57caJ90w53k/e092bdb4a4d93589aa006f796ff20fca/lock-additionalsignupfields.png) @@ -876,69 +876,69 @@ var options = { Certains cas d’utilisation peuvent être en mesure d’utiliser des données `additionalSignUpFields` pour les modèles de courriels, comme une option pour les préférences linguistiques, dont la valeur pourrait ensuite être utilisée pour définir la langue des communications par courriel modélisées. -### allowLogin {Boolean} +### allowLogin `{Boolean}` Lorsqu’il est défini sur `false`, le gadget logiciel n’affichera pas l’écran de connexion. Ceci est utile si vous souhaitez utiliser le gadget logiciel uniquement pour les inscriptions (les onglets de connexion et d’inscription dans l’écran d’inscription seront masqués) ou pour réinitialiser les mots de passe (le bouton de retour dans l’écran de mot de passe oublié sera masqué). Dans de tels cas, vous devrez peut-être également spécifier les options `initialScreen`, `AllowForgotPassword` et `AllowSignUp`. La valeur par défaut est `true`. -`allowLogin: false`](/docs/images/ +`allowLogin: false` ![Lock Option: Allow Login](/images/fr-ca/cdy7uua7fh8z/6gI4aSLHXLzhcHiR9aWMET/d05c2a08a3895278b01150ecf894cb5f/lock-allowlogin.png) -### allowForgotPassword {Boolean} +### allowForgotPassword `{Boolean}` Lorsqu’il est défini sur false, `allowForgotPassword` masque le lien « Vous ne vous souvenez pas de votre mot de passe? » dans l’écran de connexion, rendant l’écran Mot de passe oublié inaccessible. La valeur par défaut est vrai. Si vous utilisez une connexion à une base de données personnalisée qui ne dispose pas d’un script de modification du mot de passe, l’écran Mot de passe oublié ne sera pas disponible. -`allowForgotPassword: false`](/docs/images/ +`allowForgotPassword: false` ![Lock Option: Allow Forgot Password](/images/fr-ca/cdy7uua7fh8z/1L6wJS3UnWK1VGKYMFhAB9/2ddcf2d462255e78a8b78958c2503809/lock-allowforgotpassword.png) -### allowSignUp {Boolean} +### allowSignUp `{Boolean}` Lorsqu’il est défini sur `false`, masque les onglets de connexion et d’inscription dans l’écran de connexion, rendant l’écran de connexion inaccessible. Par défaut sur `vrai`. Gardez à l’esprit que si la connexion à la base de données a désactivé les inscriptions ou si vous utilisez une base de données personnalisée qui ne dispose pas de script de création, l’écran de connexion ne sera pas disponible. Gardez également à l’esprit que cette option contrôle **uniquement** l’apparence côté client et n’arrête pas complètement les nouvelles connexions de visiteurs anonymes déterminés. Si vous souhaitez empêcher complètement la connexion de nouveaux utilisateurs, vous devez utiliser l’option **Disable Sign Ups (Désactiver les connexions)** dans le tableau de bord, dans les paramètres de connexion. -`allowSignUp: false`](/docs/images/ +`allowSignUp: false` ![Lock Option: Allow Signup](/images/fr-ca/cdy7uua7fh8z/2BNlYe99EFlRmIlhoLZiEB/f280d865cb16fa5fecda952271cb18bf/lock-allowsignup.png) -### defaultDatabaseConnection {String} +### defaultDatabaseConnection `{String}` Spécifie la connexion à la base de données qui sera utilisée lorsqu’il y en a plusieurs disponibles. `defaultDatabaseConnection: 'test-database'` -### initialScreen {String} +### initialScreen `{String}` Le nom de l’écran qui sera affiché à l’ouverture du gadget logiciel. Les valeurs valides sont `connexion`, `s’inscrire` et `Mot de passe oublié`. Si cette option n’est pas spécifiée, le gadget logiciel affichera par défaut le premier écran disponible dans cette liste. `initialScreen: 'forgotPassword'` -### loginAfterSignUp {Boolean} +### loginAfterSignUp `{Boolean}` Détermine si l’utilisateur sera automatiquement connecté ou non après une inscription réussie. Par défaut sur `vrai`. `loginAfterSignUp: false` -### forgotPasswordLink {String} +### forgotPasswordLink `{String}` Définissez l’URL d’une page qui permet à l’utilisateur de réinitialiser son mot de passe. Lorsqu’il est défini sur un lien non vide, l’utilisateur sera redirigé vers l’URL fournie lorsqu’il cliquera sur le lien « Vous ne vous souvenez pas de votre mot de passe? dans l’écran de connexion. `forgotPasswordLink: 'https://yoursite.com/reset-password'` -### showTerms {Boolean} +### showTerms `{Boolean}` Lorsqu’il est défini sur `true`, affiche le lien `languageDictionary.signUpTerms`. Par défaut sur `vrai`. `showTerms: false` -### mustAcceptTerms {Boolean} +### mustAcceptTerms `{Boolean}` Une fois définie sur `true`, affiche une case à cocher à côté des modalités qui doivent être vérifiées avant de procéder à l’inscription. Les modalités peuvent être spécifiées à l’aide de l’option `languageDictionary`. Cette option ne prendra effet que pour les utilisateurs s’inscrivant avec des connexions à la base de données. La valeur par défaut est false. `mustAcceptTerms: true` -### prefill {Object} +### prefill `{Object}` Permet de définir la valeur initiale des entrées courriel et/ou nom d’utilisateur. En cas d’omission, aucune valeur initiale ne sera fournie. @@ -952,13 +952,13 @@ var options = { }; ``` -### signUpLink {String} +### signUpLink `{String}` Définissez l’URL à demander en cliquant sur le bouton d’inscription. Lorsqu’elle est définie sur un lien non vide, cette option force `Permettre l’inscription` à `true`. `signUpLink: 'https://yoursite.com/signup'` -### usernameStyle {String} +### usernameStyle `{String}` Détermine ce qui sera utilisé pour identifier l’utilisateur pour une connexion à la base de données dont l’option `require_username` est défini (s’il n’est pas défini, l’option `usernameStyle` sera ignorée). Les valeurs possibles sont `"username"` and `"email"`. Par défaut, `username` et `email` sont autorisés; la définition de cette option limitera les connexions à utiliser l’un ou l’autre. @@ -966,13 +966,13 @@ Détermine ce qui sera utilisé pour identifier l’utilisateur pour une connexi ## Options Entreprise -### defaultEnterpriseConnection {String} +### defaultEnterpriseConnection `{String}` Spécifie la connexion d’entreprise qui permet de se connecter à l’aide d’un nom d’utilisateur et d’un mot de passe qui seront utilisés lorsqu’il y en a plusieurs disponibles ou qu’il existe une connexion à une base de données. Si `defaultDatabaseConnection` est fourni, la connexion à la base de données sera utilisée et cette option sera ignorée. `defaultEnterpriseConnection: 'test-database'` -### defaultADUsernameFromEmailPrefix {Boolean} +### defaultADUsernameFromEmailPrefix `{Boolean}` Résolvez le nom d’utilisateur de l’espace réservé AD à partir du préfixe du courriel. Par défaut sur `vrai`. @@ -980,7 +980,7 @@ Résolvez le nom d’utilisateur de l’espace réservé AD à partir du préfix ## Options sans mot de passe -### passwordlessMethod {String} +### passwordlessMethod `{String}` Lorsque vous utilisez `Auth0LockPasswordless` avec une connexion de messagerie, vous pouvez utiliser cette option pour choisir entre l’envoi d’un [code](/docs/fr-ca/connections/passwordless/spa-email-code) ou d’un [lien magique](/docs/fr-ca/connections/passwordless/spa-email-link) pour authentifier l’utilisateur. Les valeurs disponibles pour les connexions de messagerie sont `code` et `lien`. Par défaut à `code`. Les connexions SMS sans mot de passe utiliseront toujours `code`. @@ -988,19 +988,19 @@ Lorsque vous utilisez `Auth0LockPasswordless` avec une connexion de messagerie, ## Autres options -### configurationBaseUrl {String} +### configurationBaseUrl `{String}` Remplace l’URL de base des paramètres de l’application. Par défaut, utilise le domaine fourni. Cette option n’est nécessaire que si votre cas d’utilisation spécifique exige que votre application n’utilise pas le comportement par défaut. `configurationBaseUrl: "https://www.example.com"` -### languageBaseUrl {String} +### languageBaseUrl `{String}` Remplace l’URL source de la langue pour les traductions fournies par Auth0. Par défaut, cette option utilise l’URL `https://cdn.auth0.com` CDN d’Auth0 puisque c’est là que sont stockées toutes les traductions fournies. En fournissant une autre valeur, vous pouvez utiliser une autre source pour les traductions si nécessaire. `languageBaseUrl: "https://www.example.com"` -### hashCleanup {Boolean} +### hashCleanup `{Boolean}` Lorsque l’option `hashCleanup` est activée, elle supprimera la partie hachage de l’URL de rappel après l’authentification de l’utilisateur. La valeur par défaut est true. diff --git a/main/docs/fr-ca/libraries/lock/lock-ui-customization.mdx b/main/docs/fr-ca/libraries/lock/lock-ui-customization.mdx index de07b806e..42eeed918 100644 --- a/main/docs/fr-ca/libraries/lock/lock-ui-customization.mdx +++ b/main/docs/fr-ca/libraries/lock/lock-ui-customization.mdx @@ -21,7 +21,7 @@ First, you'll define the `options` object, containing whichever options you're w There are a couple of theming options currently available, namespaced under the `theme` property. -#### logo {String} +#### logo `{String}` ![Lock UI customization - Logo](/docs/images/fr-ca/cdy7uua7fh8z/FdOAKKy71rTbFjIlZEL8D/2eef96008095d85388daaa461707901d/lock-theme-logo.png) @@ -35,7 +35,7 @@ var options = { }; ``` -#### primaryColor {String} +#### primaryColor `{String}` ![Lock UI customization - primary color](/docs/images/fr-ca/cdy7uua7fh8z/1qQjeTmXJyIziv400VPaOn/48dd3cb8a72a6e88b2634b4b8a8bed63/lock-theme-primarycolor.png) @@ -50,14 +50,14 @@ var options = { }; ``` -#### authButtons {Object} +#### authButtons `{Object}` Allows the customization of buttons in Lock. Each custom connection whose button you desire to customize should be listed by name, each with their own set of parameters. The customizable parameters are listed below: -* **displayName** {String}: The name to show instead of the connection name when building the button title, such as `LOGIN WITH MYCONNECTION` for login). -* **primaryColor** {String}: The button's background color. Defaults to `#eb5424`. -* **foregroundColor** {String}: The button's text color. Defaults to `#FFFFFF`. -* **icon** {String}: The URL of the icon for this connection. For example: `http://site.com/logo.png`. +* **displayName** `{String}`: The name to show instead of the connection name when building the button title, such as `LOGIN WITH MYCONNECTION` for login). +* **primaryColor** `{String}`: The button's background color. Defaults to `#eb5424`. +* **foregroundColor** `{String}`: The button's text color. Defaults to `#FFFFFF`. +* **icon** `{String}`: The URL of the icon for this connection. For example: `http://site.com/logo.png`. ```javascript lines var options = { diff --git a/main/docs/fr-ca/manage-users/access-control/configure-core-rbac/enable-role-based-access-control-for-apis.mdx b/main/docs/fr-ca/manage-users/access-control/configure-core-rbac/enable-role-based-access-control-for-apis.mdx index 63128a620..587b323a9 100644 --- a/main/docs/fr-ca/manage-users/access-control/configure-core-rbac/enable-role-based-access-control-for-apis.mdx +++ b/main/docs/fr-ca/manage-users/access-control/configure-core-rbac/enable-role-based-access-control-for-apis.mdx @@ -10,6 +10,7 @@ permalink: "enable-role-based-access-control-for-apis" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Vous pouvez activer le [contrôle d'accès basé sur les rôles (RBAC)](/docs/fr-ca/manage-users/access-control/rbac) à l’aide de Auth0 Dashboard ou de response = Unirest.patch("https://{yourDomain}/api/v2/resource-servers/API_ID") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/resource-servers/API_ID") .header("content-type", "application/json") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ \"enforce_policies\": \"true\", \"token_dialect\": \"TOKEN_DIALECT\" }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "enforce_policies": "true", "token_dialect": "TOKEN_DIALECT" }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -111,8 +122,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @@ -139,8 +152,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/resource-servers/API_ID", @@ -150,7 +165,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{ \"enforce_policies\": \"true\", \"token_dialect\": \"TOKEN_DIALECT\" }", + CURLOPT_POSTFIELDS => "{ "enforce_policies": "true", "token_dialect": "TOKEN_DIALECT" }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "cache-control: no-cache", @@ -167,12 +182,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"enforce_policies\": \"true\", \"token_dialect\": \"TOKEN_DIALECT\" }" +payload = "{ "enforce_policies": "true", "token_dialect": "TOKEN_DIALECT" }" headers = { 'content-type': "application/json", @@ -185,8 +202,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/resource-servers/API_ID", payload, h res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -200,11 +219,13 @@ request = Net::HTTP::Patch.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ \"enforce_policies\": \"true\", \"token_dialect\": \"TOKEN_DIALECT\" }" +request.body = "{ "enforce_policies": "true", "token_dialect": "TOKEN_DIALECT" }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -235,20 +256,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + Remplacez les valeurs `API_ID`, `MGMT_API_ACCESS_TOKEN` et `TOKEN_DIALECT` par leurs valeurs respectives, comme indiqué dans le tableau suivant : diff --git a/main/docs/fr-ca/manage-users/access-control/configure-core-rbac/rbac-users/assign-permissions-to-users.mdx b/main/docs/fr-ca/manage-users/access-control/configure-core-rbac/rbac-users/assign-permissions-to-users.mdx index 4317cb0c8..42e8884ec 100644 --- a/main/docs/fr-ca/manage-users/access-control/configure-core-rbac/rbac-users/assign-permissions-to-users.mdx +++ b/main/docs/fr-ca/manage-users/access-control/configure-core-rbac/rbac-users/assign-permissions-to-users.mdx @@ -10,6 +10,7 @@ permalink: "assign-permissions-to-users" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Vous pouvez attribuer des [autorisations](/docs/fr-ca/manage-users/access-control/rbac) à un utilisateur en utilisant Auth0 Dashboard ou response = Unirest.post("https://{yourDomain}/api/v2/users/USER_ID/permissions") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/users/USER_ID/permissions") .header("content-type", "application/json") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ \"permissions\": [ { \"resource_server_identifier\": \"API_IDENTIFIER\", \"permission_name\": \"PERMISSION_NAME\" }, { \"resource_server_identifier\": \"API_IDENTIFIER\", \"permission_name\": \"PERMISSION_NAME\" } ] }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "permissions": [ { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" } ] }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -126,8 +137,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @@ -153,8 +166,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users/USER_ID/permissions", @@ -164,7 +179,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{ \"permissions\": [ { \"resource_server_identifier\": \"API_IDENTIFIER\", \"permission_name\": \"PERMISSION_NAME\" }, { \"resource_server_identifier\": \"API_IDENTIFIER\", \"permission_name\": \"PERMISSION_NAME\" } ] }", + CURLOPT_POSTFIELDS => "{ "permissions": [ { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" } ] }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "cache-control: no-cache", @@ -181,12 +196,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"permissions\": [ { \"resource_server_identifier\": \"API_IDENTIFIER\", \"permission_name\": \"PERMISSION_NAME\" }, { \"resource_server_identifier\": \"API_IDENTIFIER\", \"permission_name\": \"PERMISSION_NAME\" } ] }" +payload = "{ "permissions": [ { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" } ] }" headers = { 'content-type': "application/json", @@ -199,8 +216,10 @@ conn.request("POST", "/{yourDomain}/api/v2/users/USER_ID/permissions", payload, res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -214,11 +233,13 @@ request = Net::HTTP::Post.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ \"permissions\": [ { \"resource_server_identifier\": \"API_IDENTIFIER\", \"permission_name\": \"PERMISSION_NAME\" }, { \"resource_server_identifier\": \"API_IDENTIFIER\", \"permission_name\": \"PERMISSION_NAME\" } ] }" +request.body = "{ "permissions": [ { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" } ] }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -255,20 +276,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
diff --git a/main/docs/fr-ca/manage-users/access-control/configure-core-rbac/rbac-users/assign-roles-to-users.mdx b/main/docs/fr-ca/manage-users/access-control/configure-core-rbac/rbac-users/assign-roles-to-users.mdx index 0c760347d..1ce4b9004 100644 --- a/main/docs/fr-ca/manage-users/access-control/configure-core-rbac/rbac-users/assign-roles-to-users.mdx +++ b/main/docs/fr-ca/manage-users/access-control/configure-core-rbac/rbac-users/assign-roles-to-users.mdx @@ -10,6 +10,7 @@ permalink: "assign-roles-to-users" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Vous pouvez attribuer des [rôles](/docs/fr-ca/authorization/concepts/rbac) à un utilisateur en utilisant l’Auth0 Dashboard ou response = Unirest.post("https://{yourDomain}/api/v2/users/USER_ID/roles") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/users/USER_ID/roles") .header("content-type", "application/json") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ \"roles\": [ \"ROLE_ID\", \"ROLE_ID\" ] }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "roles": [ "ROLE_ID", "ROLE_ID" ] }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -110,8 +121,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @@ -137,8 +150,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users/USER_ID/roles", @@ -148,7 +163,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{ \"roles\": [ \"ROLE_ID\", \"ROLE_ID\" ] }", + CURLOPT_POSTFIELDS => "{ "roles": [ "ROLE_ID", "ROLE_ID" ] }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "cache-control: no-cache", @@ -165,12 +180,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"roles\": [ \"ROLE_ID\", \"ROLE_ID\" ] }" +payload = "{ "roles": [ "ROLE_ID", "ROLE_ID" ] }" headers = { 'content-type': "application/json", @@ -183,8 +200,10 @@ conn.request("POST", "/{yourDomain}/api/v2/users/USER_ID/roles", payload, header res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -198,11 +217,13 @@ request = Net::HTTP::Post.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ \"roles\": [ \"ROLE_ID\", \"ROLE_ID\" ] }" +request.body = "{ "roles": [ "ROLE_ID", "ROLE_ID" ] }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -230,20 +251,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
diff --git a/main/docs/fr-ca/manage-users/access-control/configure-core-rbac/rbac-users/remove-permissions-from-users.mdx b/main/docs/fr-ca/manage-users/access-control/configure-core-rbac/rbac-users/remove-permissions-from-users.mdx index 2291de454..8567f34cd 100644 --- a/main/docs/fr-ca/manage-users/access-control/configure-core-rbac/rbac-users/remove-permissions-from-users.mdx +++ b/main/docs/fr-ca/manage-users/access-control/configure-core-rbac/rbac-users/remove-permissions-from-users.mdx @@ -10,6 +10,7 @@ permalink: "remove-permissions-from-users" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Vous pouvez supprimer les autorisations directement attribuées à un utilisateur à l’aide de Auth0 Dashboard ou de response = Unirest.delete("https://{yourDomain}/api/v2/users/USER_ID/permissions") +} +``` +```java Java +HttpResponse response = Unirest.delete("https://{yourDomain}/api/v2/users/USER_ID/permissions") .header("content-type", "application/json") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ \"permissions\": [ { \"resource_server_identifier\": \"API_ID\", \"permission_name\": \"PERMISSION_NAME\" }, { \"resource_server_identifier\": \"API_ID\", \"permission_name\": \"PERMISSION_NAME\" } ] }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "permissions": [ { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" } ] }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'DELETE', @@ -101,8 +112,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @@ -128,8 +141,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users/USER_ID/permissions", @@ -139,7 +154,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "DELETE", - CURLOPT_POSTFIELDS => "{ \"permissions\": [ { \"resource_server_identifier\": \"API_ID\", \"permission_name\": \"PERMISSION_NAME\" }, { \"resource_server_identifier\": \"API_ID\", \"permission_name\": \"PERMISSION_NAME\" } ] }", + CURLOPT_POSTFIELDS => "{ "permissions": [ { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" } ] }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "cache-control: no-cache", @@ -156,12 +171,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"permissions\": [ { \"resource_server_identifier\": \"API_ID\", \"permission_name\": \"PERMISSION_NAME\" }, { \"resource_server_identifier\": \"API_ID\", \"permission_name\": \"PERMISSION_NAME\" } ] }" +payload = "{ "permissions": [ { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" } ] }" headers = { 'content-type': "application/json", @@ -174,8 +191,10 @@ conn.request("DELETE", "/{yourDomain}/api/v2/users/USER_ID/permissions", payload res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -189,11 +208,13 @@ request = Net::HTTP::Delete.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ \"permissions\": [ { \"resource_server_identifier\": \"API_ID\", \"permission_name\": \"PERMISSION_NAME\" }, { \"resource_server_identifier\": \"API_ID\", \"permission_name\": \"PERMISSION_NAME\" } ] }" +request.body = "{ "permissions": [ { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" } ] }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -230,20 +251,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
diff --git a/main/docs/fr-ca/manage-users/access-control/configure-core-rbac/rbac-users/remove-roles-from-users.mdx b/main/docs/fr-ca/manage-users/access-control/configure-core-rbac/rbac-users/remove-roles-from-users.mdx index 93537c04a..e2684b9d9 100644 --- a/main/docs/fr-ca/manage-users/access-control/configure-core-rbac/rbac-users/remove-roles-from-users.mdx +++ b/main/docs/fr-ca/manage-users/access-control/configure-core-rbac/rbac-users/remove-roles-from-users.mdx @@ -10,6 +10,7 @@ permalink: "remove-roles-from-users" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Vous pouvez supprimer les [roles](/docs/fr-ca/manage-users/access-control/rbac) (rôles) attribués à un utilisateur en utilisant le Tableau de bord Auth0 ou Management API. Les rôles attribués sont utilisés avec l’ensemble de fonctionnalités API Authorization Core. @@ -27,20 +28,26 @@ Pour que le contrôle d'accès basé sur les rôles (RBAC) fonctionne correcteme Effectuer un appel `DELETE` au point de terminaison [Supprimer des rôles utilisateur](https://auth0.com/docs/api/management/v2#!/Users/delete_user_roles). Assurez-vous de remplacer les valeurs d’espace réservé `USER_ID`, `MGMT_API_ACCESS_TOKEN` et `ROLE_ID` par votre ID utilisateur, le jeton d’accès à Management API et les ID de rôle, respectivement. -export const codeExample1 = `curl --request DELETE \ + +```bash cURL +curl --request DELETE \ --url 'https://{yourDomain}/api/v2/users/USER_ID/roles' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{ "roles": [ "ROLE_ID", "ROLE_ID" ] }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/users/USER_ID/roles"); + --data '{ "roles": [ "ROLE_ID", "ROLE_ID" ] }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users/USER_ID/roles"); var request = new RestRequest(Method.DELETE); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{ \"roles\": [ \"ROLE_ID\", \"ROLE_ID\" ] }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "roles": [ "ROLE_ID", "ROLE_ID" ] }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -53,7 +60,7 @@ func main() { url := "https://{yourDomain}/api/v2/users/USER_ID/roles" - payload := strings.NewReader("{ \"roles\": [ \"ROLE_ID\", \"ROLE_ID\" ] }") + payload := strings.NewReader("{ "roles": [ "ROLE_ID", "ROLE_ID" ] }") req, _ := http.NewRequest("DELETE", url, payload) @@ -69,14 +76,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.delete("https://{yourDomain}/api/v2/users/USER_ID/roles") +} +``` +```java Java +HttpResponse response = Unirest.delete("https://{yourDomain}/api/v2/users/USER_ID/roles") .header("content-type", "application/json") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ \"roles\": [ \"ROLE_ID\", \"ROLE_ID\" ] }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "roles": [ "ROLE_ID", "ROLE_ID" ] }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'DELETE', @@ -93,8 +104,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @@ -120,8 +133,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users/USER_ID/roles", @@ -131,7 +146,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "DELETE", - CURLOPT_POSTFIELDS => "{ \"roles\": [ \"ROLE_ID\", \"ROLE_ID\" ] }", + CURLOPT_POSTFIELDS => "{ "roles": [ "ROLE_ID", "ROLE_ID" ] }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "cache-control: no-cache", @@ -148,12 +163,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"roles\": [ \"ROLE_ID\", \"ROLE_ID\" ] }" +payload = "{ "roles": [ "ROLE_ID", "ROLE_ID" ] }" headers = { 'content-type': "application/json", @@ -166,8 +183,10 @@ conn.request("DELETE", "/{yourDomain}/api/v2/users/USER_ID/roles", payload, head res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -181,11 +200,13 @@ request = Net::HTTP::Delete.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ \"roles\": [ \"ROLE_ID\", \"ROLE_ID\" ] }" +request.body = "{ "roles": [ "ROLE_ID", "ROLE_ID" ] }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -213,20 +234,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
diff --git a/main/docs/fr-ca/manage-users/access-control/configure-core-rbac/rbac-users/view-user-permissions.mdx b/main/docs/fr-ca/manage-users/access-control/configure-core-rbac/rbac-users/view-user-permissions.mdx index 1b6a6d6a2..25583b9ce 100644 --- a/main/docs/fr-ca/manage-users/access-control/configure-core-rbac/rbac-users/view-user-permissions.mdx +++ b/main/docs/fr-ca/manage-users/access-control/configure-core-rbac/rbac-users/view-user-permissions.mdx @@ -10,6 +10,7 @@ permalink: "view-user-permissions" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; You can view the [permissions](/docs/fr-ca/manage-users/access-control/rbac) assigned to a user using the Auth0 Dashboard. Cette tâche peut également être effectuée à l’aide de response = Unirest.get("https://{yourDomain}/api/v2/users/USER_ID/permissions") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/users/USER_ID/permissions") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -105,8 +116,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN" }; @@ -126,8 +139,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users/USER_ID/permissions", @@ -151,8 +166,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -163,8 +180,10 @@ conn.request("GET", "/{yourDomain}/api/v2/users/USER_ID/permissions", headers=he res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -178,8 +197,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer MGMT_API_ACCESS_TOKEN"] @@ -199,20 +220,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
diff --git a/main/docs/fr-ca/manage-users/access-control/configure-core-rbac/rbac-users/view-user-roles.mdx b/main/docs/fr-ca/manage-users/access-control/configure-core-rbac/rbac-users/view-user-roles.mdx index 4623befa7..13a00e5a8 100644 --- a/main/docs/fr-ca/manage-users/access-control/configure-core-rbac/rbac-users/view-user-roles.mdx +++ b/main/docs/fr-ca/manage-users/access-control/configure-core-rbac/rbac-users/view-user-roles.mdx @@ -10,6 +10,7 @@ permalink: "view-user-roles" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Vous pouvez afficher les [roles](/docs/fr-ca/manage-users/access-control/rbac) (rôles) attribués à un utilisateur en utilisant l’Auth0 Dashboard. Cette tâche peut également être effectuée à l’aide de response = Unirest.get("https://{yourDomain}/api/v2/users/USER_ID/roles") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/users/USER_ID/roles") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -95,8 +106,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN" }; @@ -116,8 +129,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users/USER_ID/roles", @@ -141,8 +156,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -153,8 +170,10 @@ conn.request("GET", "/{yourDomain}/api/v2/users/USER_ID/roles", headers=headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -168,8 +187,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer MGMT_API_ACCESS_TOKEN"] @@ -189,20 +210,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
diff --git a/main/docs/fr-ca/manage-users/access-control/configure-core-rbac/roles/add-permissions-to-roles.mdx b/main/docs/fr-ca/manage-users/access-control/configure-core-rbac/roles/add-permissions-to-roles.mdx index 17b6a3351..dfb47dab5 100644 --- a/main/docs/fr-ca/manage-users/access-control/configure-core-rbac/roles/add-permissions-to-roles.mdx +++ b/main/docs/fr-ca/manage-users/access-control/configure-core-rbac/roles/add-permissions-to-roles.mdx @@ -10,6 +10,7 @@ permalink: "add-permissions-to-roles" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Vous pouvez ajouter des autorisations aux [rôles](/docs/fr-ca/manage-users/access-control/rbac) à l’aide de l’Auth0 Dashboard ou de la audience) et le(s) nom(s) de la (des) autorisation(s), respectivement. -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/api/v2/roles/ROLE_ID/permissions' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{ "permissions": [ { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" } ] }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/roles/ROLE_ID/permissions"); + --data '{ "permissions": [ { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" } ] }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/roles/ROLE_ID/permissions"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{ \"permissions\": [ { \"resource_server_identifier\": \"API_IDENTIFIER\", \"permission_name\": \"PERMISSION_NAME\" }, { \"resource_server_identifier\": \"API_IDENTIFIER\", \"permission_name\": \"PERMISSION_NAME\" } ] }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "permissions": [ { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" } ] }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -58,7 +65,7 @@ func main() { url := "https://{yourDomain}/api/v2/roles/ROLE_ID/permissions" - payload := strings.NewReader("{ \"permissions\": [ { \"resource_server_identifier\": \"API_IDENTIFIER\", \"permission_name\": \"PERMISSION_NAME\" }, { \"resource_server_identifier\": \"API_IDENTIFIER\", \"permission_name\": \"PERMISSION_NAME\" } ] }") + payload := strings.NewReader("{ "permissions": [ { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" } ] }") req, _ := http.NewRequest("POST", url, payload) @@ -74,14 +81,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/roles/ROLE_ID/permissions") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/roles/ROLE_ID/permissions") .header("content-type", "application/json") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ \"permissions\": [ { \"resource_server_identifier\": \"API_IDENTIFIER\", \"permission_name\": \"PERMISSION_NAME\" }, { \"resource_server_identifier\": \"API_IDENTIFIER\", \"permission_name\": \"PERMISSION_NAME\" } ] }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "permissions": [ { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" } ] }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -109,8 +120,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @@ -136,8 +149,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/roles/ROLE_ID/permissions", @@ -147,7 +162,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{ \"permissions\": [ { \"resource_server_identifier\": \"API_IDENTIFIER\", \"permission_name\": \"PERMISSION_NAME\" }, { \"resource_server_identifier\": \"API_IDENTIFIER\", \"permission_name\": \"PERMISSION_NAME\" } ] }", + CURLOPT_POSTFIELDS => "{ "permissions": [ { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" } ] }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "cache-control: no-cache", @@ -164,12 +179,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"permissions\": [ { \"resource_server_identifier\": \"API_IDENTIFIER\", \"permission_name\": \"PERMISSION_NAME\" }, { \"resource_server_identifier\": \"API_IDENTIFIER\", \"permission_name\": \"PERMISSION_NAME\" } ] }" +payload = "{ "permissions": [ { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" } ] }" headers = { 'content-type': "application/json", @@ -182,8 +199,10 @@ conn.request("POST", "/{yourDomain}/api/v2/roles/ROLE_ID/permissions", payload, res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -197,11 +216,13 @@ request = Net::HTTP::Post.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ \"permissions\": [ { \"resource_server_identifier\": \"API_IDENTIFIER\", \"permission_name\": \"PERMISSION_NAME\" }, { \"resource_server_identifier\": \"API_IDENTIFIER\", \"permission_name\": \"PERMISSION_NAME\" } ] }" +request.body = "{ "permissions": [ { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" } ] }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -238,20 +259,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
diff --git a/main/docs/fr-ca/manage-users/access-control/configure-core-rbac/roles/create-roles.mdx b/main/docs/fr-ca/manage-users/access-control/configure-core-rbac/roles/create-roles.mdx index d7e60d171..89d522861 100644 --- a/main/docs/fr-ca/manage-users/access-control/configure-core-rbac/roles/create-roles.mdx +++ b/main/docs/fr-ca/manage-users/access-control/configure-core-rbac/roles/create-roles.mdx @@ -10,6 +10,7 @@ permalink: "create-roles" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Vous pouvez créer des [rôles](/docs/fr-ca/manage-users/access-control/rbac) à l'aide d'Auth0 Dashboard ou de Management API. Les rôles peuvent être utilisés avec l'ensemble de fonctionnalités API Authorization Core. @@ -30,20 +31,26 @@ Principal produit d’Auth0 pour configurer vos services." cta="Voir le glossair Faites un appel `POST` au [point de terminaison Créer un rôle](https://auth0.com/docs/api/management/v2#!/Roles/post_roles). Assurez-vous de remplacer les valeurs des paramètres fictifs `MGMT_API_ACCESS_TOKEN`, `ROLE_NAME` et `ROLE_DESC` par votre jeton d’accès à Management API, le nom et la description de votre rôle, respectivement. -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/api/v2/roles' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{ "name": "ROLE_NAME", "description": "ROLE_DESC" }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/roles"); + --data '{ "name": "ROLE_NAME", "description": "ROLE_DESC" }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/roles"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{ \"name\": \"ROLE_NAME\", \"description\": \"ROLE_DESC\" }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "name": "ROLE_NAME", "description": "ROLE_DESC" }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -56,7 +63,7 @@ func main() { url := "https://{yourDomain}/api/v2/roles" - payload := strings.NewReader("{ \"name\": \"ROLE_NAME\", \"description\": \"ROLE_DESC\" }") + payload := strings.NewReader("{ "name": "ROLE_NAME", "description": "ROLE_DESC" }") req, _ := http.NewRequest("POST", url, payload) @@ -72,14 +79,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/roles") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/roles") .header("content-type", "application/json") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ \"name\": \"ROLE_NAME\", \"description\": \"ROLE_DESC\" }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "name": "ROLE_NAME", "description": "ROLE_DESC" }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -96,8 +107,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @@ -124,8 +137,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/roles", @@ -135,7 +150,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{ \"name\": \"ROLE_NAME\", \"description\": \"ROLE_DESC\" }", + CURLOPT_POSTFIELDS => "{ "name": "ROLE_NAME", "description": "ROLE_DESC" }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "cache-control: no-cache", @@ -152,12 +167,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"name\": \"ROLE_NAME\", \"description\": \"ROLE_DESC\" }" +payload = "{ "name": "ROLE_NAME", "description": "ROLE_DESC" }" headers = { 'content-type': "application/json", @@ -170,8 +187,10 @@ conn.request("POST", "/{yourDomain}/api/v2/roles", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -185,11 +204,13 @@ request = Net::HTTP::Post.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ \"name\": \"ROLE_NAME\", \"description\": \"ROLE_DESC\" }" +request.body = "{ "name": "ROLE_NAME", "description": "ROLE_DESC" }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -220,20 +241,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
diff --git a/main/docs/fr-ca/manage-users/access-control/configure-core-rbac/roles/delete-roles.mdx b/main/docs/fr-ca/manage-users/access-control/configure-core-rbac/roles/delete-roles.mdx index 5d9a13735..f199bfa51 100644 --- a/main/docs/fr-ca/manage-users/access-control/configure-core-rbac/roles/delete-roles.mdx +++ b/main/docs/fr-ca/manage-users/access-control/configure-core-rbac/roles/delete-roles.mdx @@ -10,6 +10,7 @@ permalink: "delete-roles" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Vous pouvez supprimer un [rôle](/docs/fr-ca/manage-users/access-control/rbac) avec Auth0 Dashboard ou response = Unirest.delete("https://{yourDomain}/api/v2/roles/ROLE_ID") +} +``` +```java Java +HttpResponse response = Unirest.delete("https://{yourDomain}/api/v2/roles/ROLE_ID") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'DELETE', @@ -73,8 +84,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN" }; @@ -94,8 +107,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/roles/ROLE_ID", @@ -119,8 +134,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -131,8 +148,10 @@ conn.request("DELETE", "/{yourDomain}/api/v2/roles/ROLE_ID", headers=headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -146,8 +165,10 @@ request = Net::HTTP::Delete.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer MGMT_API_ACCESS_TOKEN"] @@ -167,20 +188,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
diff --git a/main/docs/fr-ca/manage-users/access-control/configure-core-rbac/roles/edit-role-definitions.mdx b/main/docs/fr-ca/manage-users/access-control/configure-core-rbac/roles/edit-role-definitions.mdx index 1589f7bc1..f55170ebc 100644 --- a/main/docs/fr-ca/manage-users/access-control/configure-core-rbac/roles/edit-role-definitions.mdx +++ b/main/docs/fr-ca/manage-users/access-control/configure-core-rbac/roles/edit-role-definitions.mdx @@ -10,6 +10,7 @@ permalink: "edit-role-definitions" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Vous pouvez modifier un [rôle](/docs/fr-ca/manage-users/access-control/rbac) avec Auth0 Dashboard ou response = Unirest.patch("https://{yourDomain}/api/v2/roles/ROLE_ID") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/roles/ROLE_ID") .header("content-type", "application/json") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ \"name\": \"ROLE_NAME\", \"description\": \"ROLE_DESC\" }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "name": "ROLE_NAME", "description": "ROLE_DESC" }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -94,8 +105,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @@ -122,8 +135,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/roles/ROLE_ID", @@ -133,7 +148,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{ \"name\": \"ROLE_NAME\", \"description\": \"ROLE_DESC\" }", + CURLOPT_POSTFIELDS => "{ "name": "ROLE_NAME", "description": "ROLE_DESC" }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "cache-control: no-cache", @@ -150,12 +165,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"name\": \"ROLE_NAME\", \"description\": \"ROLE_DESC\" }" +payload = "{ "name": "ROLE_NAME", "description": "ROLE_DESC" }" headers = { 'content-type': "application/json", @@ -168,8 +185,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/roles/ROLE_ID", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -183,11 +202,13 @@ request = Net::HTTP::Patch.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ \"name\": \"ROLE_NAME\", \"description\": \"ROLE_DESC\" }" +request.body = "{ "name": "ROLE_NAME", "description": "ROLE_DESC" }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -218,20 +239,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
diff --git a/main/docs/fr-ca/manage-users/access-control/configure-core-rbac/roles/remove-permissions-from-roles.mdx b/main/docs/fr-ca/manage-users/access-control/configure-core-rbac/roles/remove-permissions-from-roles.mdx index 30242b0a6..31464bd67 100644 --- a/main/docs/fr-ca/manage-users/access-control/configure-core-rbac/roles/remove-permissions-from-roles.mdx +++ b/main/docs/fr-ca/manage-users/access-control/configure-core-rbac/roles/remove-permissions-from-roles.mdx @@ -10,6 +10,7 @@ permalink: "remove-permissions-from-roles" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Vous pouvez supprimer les [autorisations](/docs/fr-ca/manage-users/access-control/rbac) attribuées à un rôle en utilisant Dashboard ou Management API. Les autorisations et rôles attribués sont utilisés avec l’ensemble de fonctionnalités de Authorization Core API. @@ -27,20 +28,26 @@ Pour que le contrôle d'accès basé sur les rôles (RBAC) fonctionne correcteme Faites un appel `DELETE` au [point de terminaison Supprimer les autorisations utilisateur](https://auth0.com/docs/api/management/v2#!/Roles/delete_role_permission_assignment). Remplacez les valeurs des paramètres fictifs `ROLE_ID`, `MGMT_API_ACCESS_TOKEN`, `API_ID` et `PERMISSION_NAME` avec votre identifiant d’utilisateur, le jeton d’accès à Management API, les identifiants de l’API et les noms de l’autorisation respectivement. -export const codeExample1 = `curl --request DELETE \ + +```bash cURL +curl --request DELETE \ --url 'https://{yourDomain}/api/v2/roles/ROLE_ID/permissions' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{ "permissions": [ { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" } ] }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/roles/ROLE_ID/permissions"); + --data '{ "permissions": [ { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" } ] }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/roles/ROLE_ID/permissions"); var request = new RestRequest(Method.DELETE); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{ \"permissions\": [ { \"resource_server_identifier\": \"API_ID\", \"permission_name\": \"PERMISSION_NAME\" }, { \"resource_server_identifier\": \"API_ID\", \"permission_name\": \"PERMISSION_NAME\" } ] }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "permissions": [ { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" } ] }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -53,7 +60,7 @@ func main() { url := "https://{yourDomain}/api/v2/roles/ROLE_ID/permissions" - payload := strings.NewReader("{ \"permissions\": [ { \"resource_server_identifier\": \"API_ID\", \"permission_name\": \"PERMISSION_NAME\" }, { \"resource_server_identifier\": \"API_ID\", \"permission_name\": \"PERMISSION_NAME\" } ] }") + payload := strings.NewReader("{ "permissions": [ { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" } ] }") req, _ := http.NewRequest("DELETE", url, payload) @@ -69,14 +76,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.delete("https://{yourDomain}/api/v2/roles/ROLE_ID/permissions") +} +``` +```java Java +HttpResponse response = Unirest.delete("https://{yourDomain}/api/v2/roles/ROLE_ID/permissions") .header("content-type", "application/json") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ \"permissions\": [ { \"resource_server_identifier\": \"API_ID\", \"permission_name\": \"PERMISSION_NAME\" }, { \"resource_server_identifier\": \"API_ID\", \"permission_name\": \"PERMISSION_NAME\" } ] }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "permissions": [ { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" } ] }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'DELETE', @@ -98,8 +109,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @@ -125,8 +138,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/roles/ROLE_ID/permissions", @@ -136,7 +151,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "DELETE", - CURLOPT_POSTFIELDS => "{ \"permissions\": [ { \"resource_server_identifier\": \"API_ID\", \"permission_name\": \"PERMISSION_NAME\" }, { \"resource_server_identifier\": \"API_ID\", \"permission_name\": \"PERMISSION_NAME\" } ] }", + CURLOPT_POSTFIELDS => "{ "permissions": [ { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" } ] }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "cache-control: no-cache", @@ -153,12 +168,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"permissions\": [ { \"resource_server_identifier\": \"API_ID\", \"permission_name\": \"PERMISSION_NAME\" }, { \"resource_server_identifier\": \"API_ID\", \"permission_name\": \"PERMISSION_NAME\" } ] }" +payload = "{ "permissions": [ { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" } ] }" headers = { 'content-type': "application/json", @@ -171,8 +188,10 @@ conn.request("DELETE", "/{yourDomain}/api/v2/roles/ROLE_ID/permissions", payload res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -186,11 +205,13 @@ request = Net::HTTP::Delete.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ \"permissions\": [ { \"resource_server_identifier\": \"API_ID\", \"permission_name\": \"PERMISSION_NAME\" }, { \"resource_server_identifier\": \"API_ID\", \"permission_name\": \"PERMISSION_NAME\" } ] }" +request.body = "{ "permissions": [ { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" } ] }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -227,20 +248,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
diff --git a/main/docs/fr-ca/manage-users/access-control/configure-core-rbac/roles/view-role-permissions.mdx b/main/docs/fr-ca/manage-users/access-control/configure-core-rbac/roles/view-role-permissions.mdx index 261d1cd1a..6beb50cbc 100644 --- a/main/docs/fr-ca/manage-users/access-control/configure-core-rbac/roles/view-role-permissions.mdx +++ b/main/docs/fr-ca/manage-users/access-control/configure-core-rbac/roles/view-role-permissions.mdx @@ -10,6 +10,7 @@ permalink: "view-role-permissions" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Vous pouvez afficher les [autorisations](/docs/fr-ca/manage-users/access-control/rbac) attribuées à un rôle en utilisant Auth0 Dashboard ou response = Unirest.get("https://{yourDomain}/api/v2/roles/ROLE_ID/permissions") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/roles/ROLE_ID/permissions") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -99,8 +110,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN" }; @@ -120,8 +133,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/roles/ROLE_ID/permissions", @@ -145,8 +160,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -157,8 +174,10 @@ conn.request("GET", "/{yourDomain}/api/v2/roles/ROLE_ID/permissions", headers=he res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -172,8 +191,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer MGMT_API_ACCESS_TOKEN"] @@ -193,20 +214,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
diff --git a/main/docs/fr-ca/manage-users/my-account-api.mdx b/main/docs/fr-ca/manage-users/my-account-api.mdx index a98916354..51d89689b 100644 --- a/main/docs/fr-ca/manage-users/my-account-api.mdx +++ b/main/docs/fr-ca/manage-users/my-account-api.mdx @@ -10,6 +10,7 @@ permalink: "my-account-api" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; @@ -133,12 +134,18 @@ The My Account API supports the following scopes: ##### Step 1: Request authorization code -export const codeExample1 = `curl --request GET \ - --url 'https://{yourDomain}/authorize?response_type=code&client_id={yourClientId}&redirect_uri=%7ByourRedirectUri%7D&scope=create%3Ame%3Aauthentication_methods&offline_access=&audience=https%3A%2F%2F{yourDomain}%2Fme%2F'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/authorize?response_type=code&client_id={yourClientId}&redirect_uri=%7ByourRedirectUri%7D&scope=create%3Ame%3Aauthentication_methods&offline_access=&audience=https%3A%2F%2F{yourDomain}%2Fme%2F"); + +```bash cURL +curl --request GET \ + --url 'https://{yourDomain}/authorize?response_type=code&client_id={yourClientId}&redirect_uri=%7ByourRedirectUri%7D&scope=create%3Ame%3Aauthentication_methods&offline_access=&audience=https%3A%2F%2F{yourDomain}%2Fme%2F' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/authorize?response_type=code&client_id={yourClientId}&redirect_uri=%7ByourRedirectUri%7D&scope=create%3Ame%3Aauthentication_methods&offline_access=&audience=https%3A%2F%2F{yourDomain}%2Fme%2F"); var request = new RestRequest(Method.GET); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -160,10 +167,14 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.get("https://{yourDomain}/authorize?response_type=code&client_id={yourClientId}&redirect_uri=%7ByourRedirectUri%7D&scope=create%3Ame%3Aauthentication_methods&offline_access=&audience=https%3A%2F%2F{yourDomain}%2Fme%2F") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/authorize?response_type=code&client_id={yourClientId}&redirect_uri=%7ByourRedirectUri%7D&scope=create%3Ame%3Aauthentication_methods&offline_access=&audience=https%3A%2F%2F{yourDomain}%2Fme%2F") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -182,8 +193,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://{yourDomain}/authorize?response_type=code&client_id={yourClientId}&redirect_uri=%7ByourRedirectUri%7D&scope=create%3Ame%3Aauthentication_methods&offline_access=&audience=https%3A%2F%2F{yourDomain}%2Fme%2F"] cachePolicy:NSURLRequestUseProtocolCachePolicy @@ -200,8 +213,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/authorize?response_type=code&client_id={yourClientId}&redirect_uri=%7ByourRedirectUri%7D&scope=create%3Ame%3Aauthentication_methods&offline_access=&audience=https%3A%2F%2F{yourDomain}%2Fme%2F", @@ -222,8 +237,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -232,8 +249,10 @@ conn.request("GET", "/{yourDomain}/authorize?response_type=code&client_id={yourC res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -246,8 +265,10 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Get.new(url) response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let request = NSMutableURLRequest(url: NSURL(string: "https://{yourDomain}/authorize?response_type=code&client_id={yourClientId}&redirect_uri=%7ByourRedirectUri%7D&scope=create%3Ame%3Aauthentication_methods&offline_access=&audience=https%3A%2F%2F{yourDomain}%2Fme%2F")! as URL, cachePolicy: .useProtocolCachePolicy, @@ -264,33 +285,28 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ##### Step 2: Exchange code for access token -export const codeExample11 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/json' \ - --data '{"grant_type": "authorization_code","client_id": "{yourClientId}","client_secret": "{yourClientId}","code": "{yourAuthorizationCode}","redirect_uri": "{yourRedirectUri}","audience": "{yourAudience}","scope": "create:me:authentication_methods","offline_access": ""}'`; -export const codeExample12 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data '{"grant_type": "authorization_code","client_id": "{yourClientId}","client_secret": "{yourClientId}","code": "{yourAuthorizationCode}","redirect_uri": "{yourRedirectUri}","audience": "{yourAudience}","scope": "create:me:authentication_methods","offline_access": ""}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\"grant_type\": \"authorization_code\",\"client_id\": \"{yourClientId}\",\"client_secret\": \"{yourClientId}\",\"code\": \"{yourAuthorizationCode}\",\"redirect_uri\": \"{yourRedirectUri}\",\"audience\": \"{yourAudience}\",\"scope\": \"create:me:authentication_methods\",\"offline_access\": \"\"}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample13 = `package main +request.AddParameter("application/json", "{"grant_type": "authorization_code","client_id": "{yourClientId}","client_secret": "{yourClientId}","code": "{yourAuthorizationCode}","redirect_uri": "{yourRedirectUri}","audience": "{yourAudience}","scope": "create:me:authentication_methods","offline_access": ""}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -303,7 +319,7 @@ func main() { url := "https://{yourDomain}/oauth/token" - payload := strings.NewReader("{\"grant_type\": \"authorization_code\",\"client_id\": \"{yourClientId}\",\"client_secret\": \"{yourClientId}\",\"code\": \"{yourAuthorizationCode}\",\"redirect_uri\": \"{yourRedirectUri}\",\"audience\": \"{yourAudience}\",\"scope\": \"create:me:authentication_methods\",\"offline_access\": \"\"}") + payload := strings.NewReader("{"grant_type": "authorization_code","client_id": "{yourClientId}","client_secret": "{yourClientId}","code": "{yourAuthorizationCode}","redirect_uri": "{yourRedirectUri}","audience": "{yourAudience}","scope": "create:me:authentication_methods","offline_access": ""}") req, _ := http.NewRequest("POST", url, payload) @@ -317,12 +333,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample14 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/json") - .body("{\"grant_type\": \"authorization_code\",\"client_id\": \"{yourClientId}\",\"client_secret\": \"{yourClientId}\",\"code\": \"{yourAuthorizationCode}\",\"redirect_uri\": \"{yourRedirectUri}\",\"audience\": \"{yourAudience}\",\"scope\": \"create:me:authentication_methods\",\"offline_access\": \"\"}") - .asString();`; -export const codeExample15 = `var axios = require("axios").default; + .body("{"grant_type": "authorization_code","client_id": "{yourClientId}","client_secret": "{yourClientId}","code": "{yourAuthorizationCode}","redirect_uri": "{yourRedirectUri}","audience": "{yourAudience}","scope": "create:me:authentication_methods","offline_access": ""}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -344,8 +364,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample16 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json" }; NSDictionary *parameters = @{ @"grant_type": @"authorization_code", @@ -376,8 +398,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -387,7 +411,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{\"grant_type\": \"authorization_code\",\"client_id\": \"{yourClientId}\",\"client_secret\": \"{yourClientId}\",\"code\": \"{yourAuthorizationCode}\",\"redirect_uri\": \"{yourRedirectUri}\",\"audience\": \"{yourAudience}\",\"scope\": \"create:me:authentication_methods\",\"offline_access\": \"\"}", + CURLOPT_POSTFIELDS => "{"grant_type": "authorization_code","client_id": "{yourClientId}","client_secret": "{yourClientId}","code": "{yourAuthorizationCode}","redirect_uri": "{yourRedirectUri}","audience": "{yourAudience}","scope": "create:me:authentication_methods","offline_access": ""}", CURLOPT_HTTPHEADER => [ "content-type: application/json" ], @@ -402,12 +426,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"grant_type\": \"authorization_code\",\"client_id\": \"{yourClientId}\",\"client_secret\": \"{yourClientId}\",\"code\": \"{yourAuthorizationCode}\",\"redirect_uri\": \"{yourRedirectUri}\",\"audience\": \"{yourAudience}\",\"scope\": \"create:me:authentication_methods\",\"offline_access\": \"\"}" +payload = "{"grant_type": "authorization_code","client_id": "{yourClientId}","client_secret": "{yourClientId}","code": "{yourAuthorizationCode}","redirect_uri": "{yourRedirectUri}","audience": "{yourAudience}","scope": "create:me:authentication_methods","offline_access": ""}" headers = { 'content-type': "application/json" } @@ -416,8 +442,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -429,11 +457,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["content-type"] = 'application/json' -request.body = "{\"grant_type\": \"authorization_code\",\"client_id\": \"{yourClientId}\",\"client_secret\": \"{yourClientId}\",\"code\": \"{yourAuthorizationCode}\",\"redirect_uri\": \"{yourRedirectUri}\",\"audience\": \"{yourAudience}\",\"scope\": \"create:me:authentication_methods\",\"offline_access\": \"\"}" +request.body = "{"grant_type": "authorization_code","client_id": "{yourClientId}","client_secret": "{yourClientId}","code": "{yourAuthorizationCode}","redirect_uri": "{yourRedirectUri}","audience": "{yourAudience}","scope": "create:me:authentication_methods","offline_access": ""}" response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/json"] let parameters = [ @@ -466,35 +496,30 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + #### Embedded login with native passkeys ##### Step 1: Request login challenge -export const codeExample21 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/passkey/challenge' \ --header 'content-type: application/json' \ - --data '{"client_id": "{yourDomain}"}'`; -export const codeExample22 = `var client = new RestClient("https://{yourDomain}/passkey/challenge"); + --data '{"client_id": "{yourDomain}"}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/passkey/challenge"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\"client_id\": \"{yourDomain}\"}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample23 = `package main +request.AddParameter("application/json", "{"client_id": "{yourDomain}"}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -507,7 +532,7 @@ func main() { url := "https://{yourDomain}/passkey/challenge" - payload := strings.NewReader("{\"client_id\": \"{yourDomain}\"}") + payload := strings.NewReader("{"client_id": "{yourDomain}"}") req, _ := http.NewRequest("POST", url, payload) @@ -521,12 +546,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample24 = `HttpResponse response = Unirest.post("https://{yourDomain}/passkey/challenge") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/passkey/challenge") .header("content-type", "application/json") - .body("{\"client_id\": \"{yourDomain}\"}") - .asString();`; -export const codeExample25 = `var axios = require("axios").default; + .body("{"client_id": "{yourDomain}"}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -539,8 +568,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample26 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json" }; NSDictionary *parameters = @{ @"client_id": @"{yourDomain}" }; @@ -564,8 +595,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample27 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/passkey/challenge", @@ -575,7 +608,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{\"client_id\": \"{yourDomain}\"}", + CURLOPT_POSTFIELDS => "{"client_id": "{yourDomain}"}", CURLOPT_HTTPHEADER => [ "content-type: application/json" ], @@ -590,12 +623,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample28 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"client_id\": \"{yourDomain}\"}" +payload = "{"client_id": "{yourDomain}"}" headers = { 'content-type': "application/json" } @@ -604,8 +639,10 @@ conn.request("POST", "/{yourDomain}/passkey/challenge", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample29 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -617,11 +654,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["content-type"] = 'application/json' -request.body = "{\"client_id\": \"{yourDomain}\"}" +request.body = "{"client_id": "{yourDomain}"}" response = http.request(request) -puts response.read_body`; -export const codeExample30 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/json"] let parameters = ["client_id": "{yourDomain}"] as [String : Any] @@ -645,33 +684,28 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ##### Step 2: Authenticate existing user -export const codeExample31 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/json' \ - --data '{ "grant_type": "urn:okta:params:oauth:grant-type:webauthn", "client_id": "{yourClientId}", "scope": "create:me:authentication_methods offline_access", "audience": "https://{yourDomain}/me/" "auth_session": "{sessionIdFromTheFirstRequest}", "authn_response": "{authenticatorResponse}"}'`; -export const codeExample32 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data '{ "grant_type": "urn:okta:params:oauth:grant-type:webauthn", "client_id": "{yourClientId}", "scope": "create:me:authentication_methods offline_access", "audience": "https://{yourDomain}/me/" "auth_session": "{sessionIdFromTheFirstRequest}", "authn_response": "{authenticatorResponse}"}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{ \"grant_type\": \"urn:okta:params:oauth:grant-type:webauthn\", \"client_id\": \"{yourClientId}\", \"scope\": \"create:me:authentication_methods offline_access\", \"audience\": \"https://{yourDomain}/me/\" \"auth_session\": \"{sessionIdFromTheFirstRequest}\", \"authn_response\": \"{authenticatorResponse}\"}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample33 = `package main +request.AddParameter("application/json", "{ "grant_type": "urn:okta:params:oauth:grant-type:webauthn", "client_id": "{yourClientId}", "scope": "create:me:authentication_methods offline_access", "audience": "https://{yourDomain}/me/" "auth_session": "{sessionIdFromTheFirstRequest}", "authn_response": "{authenticatorResponse}"}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -684,7 +718,7 @@ func main() { url := "https://{yourDomain}/oauth/token" - payload := strings.NewReader("{ \"grant_type\": \"urn:okta:params:oauth:grant-type:webauthn\", \"client_id\": \"{yourClientId}\", \"scope\": \"create:me:authentication_methods offline_access\", \"audience\": \"https://{yourDomain}/me/\" \"auth_session\": \"{sessionIdFromTheFirstRequest}\", \"authn_response\": \"{authenticatorResponse}\"}") + payload := strings.NewReader("{ "grant_type": "urn:okta:params:oauth:grant-type:webauthn", "client_id": "{yourClientId}", "scope": "create:me:authentication_methods offline_access", "audience": "https://{yourDomain}/me/" "auth_session": "{sessionIdFromTheFirstRequest}", "authn_response": "{authenticatorResponse}"}") req, _ := http.NewRequest("POST", url, payload) @@ -698,12 +732,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample34 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/json") - .body("{ \"grant_type\": \"urn:okta:params:oauth:grant-type:webauthn\", \"client_id\": \"{yourClientId}\", \"scope\": \"create:me:authentication_methods offline_access\", \"audience\": \"https://{yourDomain}/me/\" \"auth_session\": \"{sessionIdFromTheFirstRequest}\", \"authn_response\": \"{authenticatorResponse}\"}") - .asString();`; -export const codeExample35 = `var axios = require("axios").default; + .body("{ "grant_type": "urn:okta:params:oauth:grant-type:webauthn", "client_id": "{yourClientId}", "scope": "create:me:authentication_methods offline_access", "audience": "https://{yourDomain}/me/" "auth_session": "{sessionIdFromTheFirstRequest}", "authn_response": "{authenticatorResponse}"}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -716,8 +754,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample36 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json" }; @@ -740,8 +780,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample37 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -751,7 +793,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{ \"grant_type\": \"urn:okta:params:oauth:grant-type:webauthn\", \"client_id\": \"{yourClientId}\", \"scope\": \"create:me:authentication_methods offline_access\", \"audience\": \"https://{yourDomain}/me/\" \"auth_session\": \"{sessionIdFromTheFirstRequest}\", \"authn_response\": \"{authenticatorResponse}\"}", + CURLOPT_POSTFIELDS => "{ "grant_type": "urn:okta:params:oauth:grant-type:webauthn", "client_id": "{yourClientId}", "scope": "create:me:authentication_methods offline_access", "audience": "https://{yourDomain}/me/" "auth_session": "{sessionIdFromTheFirstRequest}", "authn_response": "{authenticatorResponse}"}", CURLOPT_HTTPHEADER => [ "content-type: application/json" ], @@ -766,12 +808,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample38 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"grant_type\": \"urn:okta:params:oauth:grant-type:webauthn\", \"client_id\": \"{yourClientId}\", \"scope\": \"create:me:authentication_methods offline_access\", \"audience\": \"https://{yourDomain}/me/\" \"auth_session\": \"{sessionIdFromTheFirstRequest}\", \"authn_response\": \"{authenticatorResponse}\"}" +payload = "{ "grant_type": "urn:okta:params:oauth:grant-type:webauthn", "client_id": "{yourClientId}", "scope": "create:me:authentication_methods offline_access", "audience": "https://{yourDomain}/me/" "auth_session": "{sessionIdFromTheFirstRequest}", "authn_response": "{authenticatorResponse}"}" headers = { 'content-type': "application/json" } @@ -780,8 +824,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample39 = `rrequire 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +rrequire 'uri' require 'net/http' require 'openssl' @@ -793,11 +839,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["content-type"] = 'application/json' -request.body = "{ \"grant_type\": \"urn:okta:params:oauth:grant-type:webauthn\", \"client_id\": \"{yourClientId}\", \"scope\": \"create:me:authentication_methods offline_access\", \"audience\": \"https://{yourDomain}/me/\" \"auth_session\": \"{sessionIdFromTheFirstRequest}\", \"authn_response\": \"{authenticatorResponse}\"}" +request.body = "{ "grant_type": "urn:okta:params:oauth:grant-type:webauthn", "client_id": "{yourClientId}", "scope": "create:me:authentication_methods offline_access", "audience": "https://{yourDomain}/me/" "auth_session": "{sessionIdFromTheFirstRequest}", "authn_response": "{authenticatorResponse}"}" response = http.request(request) -puts response.read_body`; -export const codeExample40 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/json"] @@ -820,20 +868,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ## Rate limits diff --git a/main/docs/fr-ca/manage-users/organizations/configure-organizations/add-member-roles.mdx b/main/docs/fr-ca/manage-users/organizations/configure-organizations/add-member-roles.mdx index 61d325198..6151a0ddd 100644 --- a/main/docs/fr-ca/manage-users/organizations/configure-organizations/add-member-roles.mdx +++ b/main/docs/fr-ca/manage-users/organizations/configure-organizations/add-member-roles.mdx @@ -9,6 +9,9 @@ permalink: "add-member-roles" 'twitter:description': "Apprenez à ajouter des rôles aux membres de l’organisation en utilisant Auth0 Dashboard ou Management API." --- + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + Chaque membre de l’[organisation](/docs/fr-ca/manage-users/organizations/organizations-overview) peut se voir attribuer un ou plusieurs rôles, qui sont appliqués lorsque les utilisateurs se connectent via l’organisation. Pour en savoir plus sur les rôles et leur comportement, consultez [Contrôle d’accès basé sur les rôles (RBAC)](/docs/fr-ca/manage-users/access-control/rbac). Vous pouvez ajouter des rôles aux membres d’une organisation à l’aide e diff --git a/main/docs/fr-ca/manage-users/organizations/configure-organizations/assign-members.mdx b/main/docs/fr-ca/manage-users/organizations/configure-organizations/assign-members.mdx index e5c94fde2..5faffc130 100644 --- a/main/docs/fr-ca/manage-users/organizations/configure-organizations/assign-members.mdx +++ b/main/docs/fr-ca/manage-users/organizations/configure-organizations/assign-members.mdx @@ -9,6 +9,9 @@ permalink: "assign-members" 'twitter:description': "Apprenez à affecter des membres directement à une organisation à l’aide du Auth0 Dashboard (Tableau de bord Auth0) ou de Management API." --- + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + Pour affecter un membre à votre [organisation](/docs/fr-ca/manage-users/organizations/organizations-overview), vous devez déjà avoir [créé l’utilisateur](/docs/fr-ca/manage-users/user-accounts/create-users) dans votre locataire. Si vous n’arrivez pas à trouver un utilisateur, vous pouvez [l’inviter](/docs/fr-ca/manage-users/organizations/configure-organizations/invite-members). Pour gérer les membres directement, vous pouvez utiliser le diff --git a/main/docs/fr-ca/manage-users/organizations/configure-organizations/create-organizations.mdx b/main/docs/fr-ca/manage-users/organizations/configure-organizations/create-organizations.mdx index 390309f54..faad34372 100644 --- a/main/docs/fr-ca/manage-users/organizations/configure-organizations/create-organizations.mdx +++ b/main/docs/fr-ca/manage-users/organizations/configure-organizations/create-organizations.mdx @@ -10,6 +10,7 @@ permalink: "create-organizations" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Vous pouvez créer des [organisations](/docs/fr-ca/manage-users/organizations/organizations-overview) à l’aide du Tableau de bord Auth0 ou de Management API. @@ -77,20 +78,26 @@ Pour créer une organisation via Management API : Effectuer un appel `POST` au point de terminaison `Créer des organisations`. Assurez-vous de remplacer les valeurs d’espace par les valeurs appropriées de votre locataire. Pour plus de détails, consultez le graphique des paramètres ci-dessous. -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/api/v2/organizations' \ --header 'authorization: Bearer {MGMT_API_ACCESS_TOKEN}' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{ "name": "ORG_NAME", "display_name": "ORG_DISPLAY_NAME", "branding": [ { "logo_url": "{orgLogo}", "colors": [ { "primary": "{orgPrimaryColor}", "page_background": "{orgPageBackground}" } ] } ], "metadata": [ { "{key}": "{value}", "{key}": "{value}", "{key}": "{value}" } ] }, "enabled_connections": [ { "connection_id": "{connectionId}", "assign_membership_on_login": "{assignMembershipOption}" }, { "connection_id": "{connectionId}", "assign_membership_on_login": "{assignMembershipOption}" } ] }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/organizations"); + --data '{ "name": "ORG_NAME", "display_name": "ORG_DISPLAY_NAME", "branding": [ { "logo_url": "{orgLogo}", "colors": [ { "primary": "{orgPrimaryColor}", "page_background": "{orgPageBackground}" } ] } ], "metadata": [ { "{key}": "{value}", "{key}": "{value}", "{key}": "{value}" } ] }, "enabled_connections": [ { "connection_id": "{connectionId}", "assign_membership_on_login": "{assignMembershipOption}" }, { "connection_id": "{connectionId}", "assign_membership_on_login": "{assignMembershipOption}" } ] }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/organizations"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer {MGMT_API_ACCESS_TOKEN}"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{ \"name\": \"ORG_NAME\", \"display_name\": \"ORG_DISPLAY_NAME\", \"branding\": [ { \"logo_url\": \"{orgLogo}\", \"colors\": [ { \"primary\": \"{orgPrimaryColor}\", \"page_background\": \"{orgPageBackground}\" } ] } ], \"metadata\": [ { \"{key}\": \"{value}\", \"{key}\": \"{value}\", \"{key}\": \"{value}\" } ] }, \"enabled_connections\": [ { \"connection_id\": \"{connectionId}\", \"assign_membership_on_login\": \"{assignMembershipOption}\" }, { \"connection_id\": \"{connectionId}\", \"assign_membership_on_login\": \"{assignMembershipOption}\" } ] }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "name": "ORG_NAME", "display_name": "ORG_DISPLAY_NAME", "branding": [ { "logo_url": "{orgLogo}", "colors": [ { "primary": "{orgPrimaryColor}", "page_background": "{orgPageBackground}" } ] } ], "metadata": [ { "{key}": "{value}", "{key}": "{value}", "{key}": "{value}" } ] }, "enabled_connections": [ { "connection_id": "{connectionId}", "assign_membership_on_login": "{assignMembershipOption}" }, { "connection_id": "{connectionId}", "assign_membership_on_login": "{assignMembershipOption}" } ] }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -103,7 +110,7 @@ func main() { url := "https://{yourDomain}/api/v2/organizations" - payload := strings.NewReader("{ \"name\": \"ORG_NAME\", \"display_name\": \"ORG_DISPLAY_NAME\", \"branding\": [ { \"logo_url\": \"{orgLogo}\", \"colors\": [ { \"primary\": \"{orgPrimaryColor}\", \"page_background\": \"{orgPageBackground}\" } ] } ], \"metadata\": [ { \"{key}\": \"{value}\", \"{key}\": \"{value}\", \"{key}\": \"{value}\" } ] }, \"enabled_connections\": [ { \"connection_id\": \"{connectionId}\", \"assign_membership_on_login\": \"{assignMembershipOption}\" }, { \"connection_id\": \"{connectionId}\", \"assign_membership_on_login\": \"{assignMembershipOption}\" } ] }") + payload := strings.NewReader("{ "name": "ORG_NAME", "display_name": "ORG_DISPLAY_NAME", "branding": [ { "logo_url": "{orgLogo}", "colors": [ { "primary": "{orgPrimaryColor}", "page_background": "{orgPageBackground}" } ] } ], "metadata": [ { "{key}": "{value}", "{key}": "{value}", "{key}": "{value}" } ] }, "enabled_connections": [ { "connection_id": "{connectionId}", "assign_membership_on_login": "{assignMembershipOption}" }, { "connection_id": "{connectionId}", "assign_membership_on_login": "{assignMembershipOption}" } ] }") req, _ := http.NewRequest("POST", url, payload) @@ -119,14 +126,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/organizations") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/organizations") .header("content-type", "application/json") .header("authorization", "Bearer {MGMT_API_ACCESS_TOKEN}") .header("cache-control", "no-cache") - .body("{ \"name\": \"ORG_NAME\", \"display_name\": \"ORG_DISPLAY_NAME\", \"branding\": [ { \"logo_url\": \"{orgLogo}\", \"colors\": [ { \"primary\": \"{orgPrimaryColor}\", \"page_background\": \"{orgPageBackground}\" } ] } ], \"metadata\": [ { \"{key}\": \"{value}\", \"{key}\": \"{value}\", \"{key}\": \"{value}\" } ] }, \"enabled_connections\": [ { \"connection_id\": \"{connectionId}\", \"assign_membership_on_login\": \"{assignMembershipOption}\" }, { \"connection_id\": \"{connectionId}\", \"assign_membership_on_login\": \"{assignMembershipOption}\" } ] }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "name": "ORG_NAME", "display_name": "ORG_DISPLAY_NAME", "branding": [ { "logo_url": "{orgLogo}", "colors": [ { "primary": "{orgPrimaryColor}", "page_background": "{orgPageBackground}" } ] } ], "metadata": [ { "{key}": "{value}", "{key}": "{value}", "{key}": "{value}" } ] }, "enabled_connections": [ { "connection_id": "{connectionId}", "assign_membership_on_login": "{assignMembershipOption}" }, { "connection_id": "{connectionId}", "assign_membership_on_login": "{assignMembershipOption}" } ] }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -143,8 +154,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer {MGMT_API_ACCESS_TOKEN}", @@ -169,8 +182,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/organizations", @@ -180,7 +195,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{ \"name\": \"ORG_NAME\", \"display_name\": \"ORG_DISPLAY_NAME\", \"branding\": [ { \"logo_url\": \"{orgLogo}\", \"colors\": [ { \"primary\": \"{orgPrimaryColor}\", \"page_background\": \"{orgPageBackground}\" } ] } ], \"metadata\": [ { \"{key}\": \"{value}\", \"{key}\": \"{value}\", \"{key}\": \"{value}\" } ] }, \"enabled_connections\": [ { \"connection_id\": \"{connectionId}\", \"assign_membership_on_login\": \"{assignMembershipOption}\" }, { \"connection_id\": \"{connectionId}\", \"assign_membership_on_login\": \"{assignMembershipOption}\" } ] }", + CURLOPT_POSTFIELDS => "{ "name": "ORG_NAME", "display_name": "ORG_DISPLAY_NAME", "branding": [ { "logo_url": "{orgLogo}", "colors": [ { "primary": "{orgPrimaryColor}", "page_background": "{orgPageBackground}" } ] } ], "metadata": [ { "{key}": "{value}", "{key}": "{value}", "{key}": "{value}" } ] }, "enabled_connections": [ { "connection_id": "{connectionId}", "assign_membership_on_login": "{assignMembershipOption}" }, { "connection_id": "{connectionId}", "assign_membership_on_login": "{assignMembershipOption}" } ] }", CURLOPT_HTTPHEADER => [ "authorization: Bearer {MGMT_API_ACCESS_TOKEN}", "cache-control: no-cache", @@ -197,12 +212,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"name\": \"ORG_NAME\", \"display_name\": \"ORG_DISPLAY_NAME\", \"branding\": [ { \"logo_url\": \"{orgLogo}\", \"colors\": [ { \"primary\": \"{orgPrimaryColor}\", \"page_background\": \"{orgPageBackground}\" } ] } ], \"metadata\": [ { \"{key}\": \"{value}\", \"{key}\": \"{value}\", \"{key}\": \"{value}\" } ] }, \"enabled_connections\": [ { \"connection_id\": \"{connectionId}\", \"assign_membership_on_login\": \"{assignMembershipOption}\" }, { \"connection_id\": \"{connectionId}\", \"assign_membership_on_login\": \"{assignMembershipOption}\" } ] }" +payload = "{ "name": "ORG_NAME", "display_name": "ORG_DISPLAY_NAME", "branding": [ { "logo_url": "{orgLogo}", "colors": [ { "primary": "{orgPrimaryColor}", "page_background": "{orgPageBackground}" } ] } ], "metadata": [ { "{key}": "{value}", "{key}": "{value}", "{key}": "{value}" } ] }, "enabled_connections": [ { "connection_id": "{connectionId}", "assign_membership_on_login": "{assignMembershipOption}" }, { "connection_id": "{connectionId}", "assign_membership_on_login": "{assignMembershipOption}" } ] }" headers = { 'content-type': "application/json", @@ -215,8 +232,10 @@ conn.request("POST", "/{yourDomain}/api/v2/organizations", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -230,11 +249,13 @@ request = Net::HTTP::Post.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer {MGMT_API_ACCESS_TOKEN}' request["cache-control"] = 'no-cache' -request.body = "{ \"name\": \"ORG_NAME\", \"display_name\": \"ORG_DISPLAY_NAME\", \"branding\": [ { \"logo_url\": \"{orgLogo}\", \"colors\": [ { \"primary\": \"{orgPrimaryColor}\", \"page_background\": \"{orgPageBackground}\" } ] } ], \"metadata\": [ { \"{key}\": \"{value}\", \"{key}\": \"{value}\", \"{key}\": \"{value}\" } ] }, \"enabled_connections\": [ { \"connection_id\": \"{connectionId}\", \"assign_membership_on_login\": \"{assignMembershipOption}\" }, { \"connection_id\": \"{connectionId}\", \"assign_membership_on_login\": \"{assignMembershipOption}\" } ] }" +request.body = "{ "name": "ORG_NAME", "display_name": "ORG_DISPLAY_NAME", "branding": [ { "logo_url": "{orgLogo}", "colors": [ { "primary": "{orgPrimaryColor}", "page_background": "{orgPageBackground}" } ] } ], "metadata": [ { "{key}": "{value}", "{key}": "{value}", "{key}": "{value}" } ] }, "enabled_connections": [ { "connection_id": "{connectionId}", "assign_membership_on_login": "{assignMembershipOption}" }, { "connection_id": "{connectionId}", "assign_membership_on_login": "{assignMembershipOption}" } ] }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -261,20 +282,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + diff --git a/main/docs/fr-ca/manage-users/organizations/configure-organizations/define-organization-behavior.mdx b/main/docs/fr-ca/manage-users/organizations/configure-organizations/define-organization-behavior.mdx index 498ee4bf5..abaf860ce 100644 --- a/main/docs/fr-ca/manage-users/organizations/configure-organizations/define-organization-behavior.mdx +++ b/main/docs/fr-ca/manage-users/organizations/configure-organizations/define-organization-behavior.mdx @@ -10,6 +10,7 @@ permalink: "define-organization-behavior" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Lorsque vous représentez votre application dans Auth0, vous pouvez spécifier les types d’utilisateurs que l’application doit prendre en charge. Certaines applications permettent aux individus de se connecter avec des comptes personnels, tandis que d’autres sont destinées à être utilisées par les membres des [organizations](/docs/fr-ca/manage-users/organizations/organizations-overview). Certains devraient prendre en charge les deux. Ceci est connu sous le nom de comportement d’organisation et peut être défini pour chaque application à laquelle vous vous connectez à Auth0. @@ -58,20 +59,26 @@ Pour définir le comportement de l’organisation à partir d’Auth0 Dashboard Effectuez une requête `PATCH` au point de terminaison [Mettre à jour un client](/docs/fr-ca/api/management/v2#!/Clients/patch_clients_by_id). Veillez à remplacer les valeurs fictives `client_id`, `mgmt_api_access_token`, `organization_usage`, et `organization_require_behavior` par votre ID client, votre jeton d’accès du Management API, l’option d’utilisation de l’organisation et l’option de comportement de l’organisation, respectivement. -export const codeExample1 = `curl --request PATCH \ + +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/clients/CLIENT_ID' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{ "organization_usage": "ORG_USAGE", "organization_require_behavior": "ORG_REQUIRE_BEHAVIOR" }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/clients/CLIENT_ID"); + --data '{ "organization_usage": "ORG_USAGE", "organization_require_behavior": "ORG_REQUIRE_BEHAVIOR" }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/clients/CLIENT_ID"); var request = new RestRequest(Method.PATCH); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{ \"organization_usage\": \"ORG_USAGE\", \"organization_require_behavior\": \"ORG_REQUIRE_BEHAVIOR\" }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "organization_usage": "ORG_USAGE", "organization_require_behavior": "ORG_REQUIRE_BEHAVIOR" }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -84,7 +91,7 @@ func main() { url := "https://{yourDomain}/api/v2/clients/CLIENT_ID" - payload := strings.NewReader("{ \"organization_usage\": \"ORG_USAGE\", \"organization_require_behavior\": \"ORG_REQUIRE_BEHAVIOR\" }") + payload := strings.NewReader("{ "organization_usage": "ORG_USAGE", "organization_require_behavior": "ORG_REQUIRE_BEHAVIOR" }") req, _ := http.NewRequest("PATCH", url, payload) @@ -100,14 +107,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/clients/CLIENT_ID") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/clients/CLIENT_ID") .header("content-type", "application/json") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ \"organization_usage\": \"ORG_USAGE\", \"organization_require_behavior\": \"ORG_REQUIRE_BEHAVIOR\" }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "organization_usage": "ORG_USAGE", "organization_require_behavior": "ORG_REQUIRE_BEHAVIOR" }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -127,8 +138,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @@ -155,8 +168,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/clients/CLIENT_ID", @@ -166,7 +181,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{ \"organization_usage\": \"ORG_USAGE\", \"organization_require_behavior\": \"ORG_REQUIRE_BEHAVIOR\" }", + CURLOPT_POSTFIELDS => "{ "organization_usage": "ORG_USAGE", "organization_require_behavior": "ORG_REQUIRE_BEHAVIOR" }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "cache-control: no-cache", @@ -183,12 +198,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"organization_usage\": \"ORG_USAGE\", \"organization_require_behavior\": \"ORG_REQUIRE_BEHAVIOR\" }" +payload = "{ "organization_usage": "ORG_USAGE", "organization_require_behavior": "ORG_REQUIRE_BEHAVIOR" }" headers = { 'content-type': "application/json", @@ -201,8 +218,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/clients/CLIENT_ID", payload, headers res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -216,11 +235,13 @@ request = Net::HTTP::Patch.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ \"organization_usage\": \"ORG_USAGE\", \"organization_require_behavior\": \"ORG_REQUIRE_BEHAVIOR\" }" +request.body = "{ "organization_usage": "ORG_USAGE", "organization_require_behavior": "ORG_REQUIRE_BEHAVIOR" }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -251,20 +272,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
diff --git a/main/docs/fr-ca/manage-users/organizations/configure-organizations/delete-organizations.mdx b/main/docs/fr-ca/manage-users/organizations/configure-organizations/delete-organizations.mdx index 98e3f2a3b..71787b39c 100644 --- a/main/docs/fr-ca/manage-users/organizations/configure-organizations/delete-organizations.mdx +++ b/main/docs/fr-ca/manage-users/organizations/configure-organizations/delete-organizations.mdx @@ -10,6 +10,7 @@ permalink: "delete-organizations" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Lors de la suppression d’une [organisation](/docs/fr-ca/manage-users/organizations/organizations-overview), le lien entre les utilisateurs et l’organisation concernée est supprimé, mais les utilisateurs eux-mêmes ne sont pas supprimés de votre locataire. @@ -34,14 +35,20 @@ Pour supprimer une organisation à partir d’Auth0 Dashboard : Effectuez un appel `GET` au point de terminaison`Delete Organization`. Veillez à remplacer les valeurs de remplacement `ORG_ID` et `MGMT_API_ACCESS_TOKEN` par l’identifiant de votre organisation et le jeton d’accès à Management API, respectivement. -export const codeExample1 = `curl --request DELETE \ + +```bash cURL +curl --request DELETE \ --url 'https://{yourDomain}/api/v2/organizations/ORG_ID' \ - --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/organizations/ORG_ID"); + --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/organizations/ORG_ID"); var request = new RestRequest(Method.DELETE); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -65,11 +72,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.delete("https://{yourDomain}/api/v2/organizations/ORG_ID") +} +``` +```java Java +HttpResponse response = Unirest.delete("https://{yourDomain}/api/v2/organizations/ORG_ID") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'DELETE', @@ -81,8 +92,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN" }; @@ -102,8 +115,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/organizations/ORG_ID", @@ -127,8 +142,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -139,8 +156,10 @@ conn.request("DELETE", "/{yourDomain}/api/v2/organizations/ORG_ID", headers=head res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -154,8 +173,10 @@ request = Net::HTTP::Delete.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer MGMT_API_ACCESS_TOKEN"] @@ -175,20 +196,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + diff --git a/main/docs/fr-ca/manage-users/organizations/configure-organizations/disable-connections.mdx b/main/docs/fr-ca/manage-users/organizations/configure-organizations/disable-connections.mdx index f2c0a1e42..8261a0402 100644 --- a/main/docs/fr-ca/manage-users/organizations/configure-organizations/disable-connections.mdx +++ b/main/docs/fr-ca/manage-users/organizations/configure-organizations/disable-connections.mdx @@ -10,6 +10,7 @@ permalink: "disable-connections" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Vous pouvez désactiver les connexions d’[organisations](/docs/fr-ca/manage-users/organizations/organizations-overview) à l’aide d’Auth0 Dashboard ou de response = Unirest.delete("https://{yourDomain}/api/v2/organizations/ORG_ID/enabled_connections/CONNECTION_ID") +} +``` +```java Java +HttpResponse response = Unirest.delete("https://{yourDomain}/api/v2/organizations/ORG_ID/enabled_connections/CONNECTION_ID") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'DELETE', @@ -74,8 +85,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN" }; @@ -95,8 +108,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/organizations/ORG_ID/enabled_connections/CONNECTION_ID", @@ -120,8 +135,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -132,8 +149,10 @@ conn.request("DELETE", "/{yourDomain}/api/v2/organizations/ORG_ID/enabled_connec res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -147,8 +166,10 @@ request = Net::HTTP::Delete.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer MGMT_API_ACCESS_TOKEN"] @@ -168,20 +189,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + diff --git a/main/docs/fr-ca/manage-users/organizations/configure-organizations/enable-connections.mdx b/main/docs/fr-ca/manage-users/organizations/configure-organizations/enable-connections.mdx index 58eccc362..0b0eaec22 100644 --- a/main/docs/fr-ca/manage-users/organizations/configure-organizations/enable-connections.mdx +++ b/main/docs/fr-ca/manage-users/organizations/configure-organizations/enable-connections.mdx @@ -9,6 +9,9 @@ permalink: "enable-connections" 'twitter:description': "Découvrez comment activer les connexions d’organisation à l’aide du Auth0 Dashboard et de Management API." --- + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + Vous pouvez activer des connexions spécifiques pour chaque [organisation](/docs/fr-ca/manage-users/organizations/organizations-overview) afin de fournir différentes options de connexion aux utilisateurs. Après avoir activé une connexion, elle est ajoutée à l’invite de connexion de l’organisation et les utilisateurs peuvent s’authentifier via cette connexion pour accéder à vos applications. Pour activer une connexion pour une organisation, la connexion **doit** déjà exister dans votre locataire. Les connexions prises en charge comprennent les [connexions de base de données](/docs/fr-ca/connections/database), [connexions via un réseau social](/docs/fr-ca/connections/identity-providers-social) et [connexions d’entreprise](/docs/fr-ca/connections/identity-providers-enterprise). @@ -83,7 +86,7 @@ Effectuez un appel `POST` au point de terminaison `Créer des connexions pour un * **Pour les connexions de bases de données seulement**: Remplacez `{isSignupEnabled}` avec `true` ou `false` par rapport à votre choix d’inscription. * **Pour les connexions Enterprise seulement**: Remplacez `{showAsButtonOption}` avec `true` ou `false` par rapport à votre choix de bouton de connexion. - + ```bash cURL lines curl --request POST \ @@ -300,7 +303,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + diff --git a/main/docs/fr-ca/manage-users/organizations/configure-organizations/remove-member-roles.mdx b/main/docs/fr-ca/manage-users/organizations/configure-organizations/remove-member-roles.mdx index ddba04a5f..4cc3d0e32 100644 --- a/main/docs/fr-ca/manage-users/organizations/configure-organizations/remove-member-roles.mdx +++ b/main/docs/fr-ca/manage-users/organizations/configure-organizations/remove-member-roles.mdx @@ -10,6 +10,7 @@ permalink: "remove-member-roles" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Vous pouvez retirer des rôles aux membres de l’ [organisation](/docs/fr-ca/manage-users/organizations/organizations-overview) à l’aide d’Auth0 Dashboard ou de response = Unirest.delete("https://{yourDomain}/api/v2/organizations/ORG_ID/members/USER_ID/roles") +} +``` +```java Java +HttpResponse response = Unirest.delete("https://{yourDomain}/api/v2/organizations/ORG_ID/members/USER_ID/roles") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ \"roles\": [ \"ROLE_ID\", \"ROLE_ID\", \"ROLE_ID\" ] }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "roles": [ "ROLE_ID", "ROLE_ID", "ROLE_ID" ] }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'DELETE', @@ -86,8 +97,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @"cache-control": @"no-cache" }; @@ -112,8 +125,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/organizations/ORG_ID/members/USER_ID/roles", @@ -123,7 +138,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "DELETE", - CURLOPT_POSTFIELDS => "{ \"roles\": [ \"ROLE_ID\", \"ROLE_ID\", \"ROLE_ID\" ] }", + CURLOPT_POSTFIELDS => "{ "roles": [ "ROLE_ID", "ROLE_ID", "ROLE_ID" ] }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "cache-control: no-cache" @@ -139,12 +154,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"roles\": [ \"ROLE_ID\", \"ROLE_ID\", \"ROLE_ID\" ] }" +payload = "{ "roles": [ "ROLE_ID", "ROLE_ID", "ROLE_ID" ] }" headers = { 'authorization': "Bearer MGMT_API_ACCESS_TOKEN", @@ -156,8 +173,10 @@ conn.request("DELETE", "/{yourDomain}/api/v2/organizations/ORG_ID/members/USER_I res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -170,11 +189,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Delete.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ \"roles\": [ \"ROLE_ID\", \"ROLE_ID\", \"ROLE_ID\" ] }" +request.body = "{ "roles": [ "ROLE_ID", "ROLE_ID", "ROLE_ID" ] }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "authorization": "Bearer MGMT_API_ACCESS_TOKEN", @@ -201,20 +222,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + diff --git a/main/docs/fr-ca/manage-users/organizations/configure-organizations/remove-members.mdx b/main/docs/fr-ca/manage-users/organizations/configure-organizations/remove-members.mdx index b35bccce6..9a91e4f98 100644 --- a/main/docs/fr-ca/manage-users/organizations/configure-organizations/remove-members.mdx +++ b/main/docs/fr-ca/manage-users/organizations/configure-organizations/remove-members.mdx @@ -10,6 +10,7 @@ permalink: "remove-members" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Vous pouvez retirer des rôles aux membres de l’[organization](/docs/fr-ca/manage-users/organizations/organizations-overview) à l’aide de l’Auth0 Dashboard ou de Management API. La suppression d’un utilisateur d’une organisation ne supprime que son affiliation à l’organisation en question; elle ne le supprime pas de la connexion ou du locataire d’Auth0. La suppression prend en moyenne entre 5 et 10 secondes. @@ -26,18 +27,24 @@ Pour supprimer une connexion par l’entremise de l’Auth0 Dashboard : Pour supprimer des membres par l’entremise de Management API : Effectuez un appel `DELETE` au point de terminaison `Delete Organization Members (Supprimer les membres de l’organization)`. Assurez-vous de remplacer les valeurs d’espace réservé `ORG_ID`, `MGMT_API_ACCESS_TOKEN`, et `USER_ID` par l’identifiant de votre organisation, le jeton d’accès de Management API et l’identifiant de l’utilisateur, respectivement. -export const codeExample1 = `curl --request DELETE \ + +```bash cURL +curl --request DELETE \ --url 'https://{yourDomain}/api/v2/organizations/ORG_ID/members' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'cache-control: no-cache' \ - --data '{ "members": [ "USER_ID", "USER_ID", "USER_ID" ] }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/organizations/ORG_ID/members"); + --data '{ "members": [ "USER_ID", "USER_ID", "USER_ID" ] }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/organizations/ORG_ID/members"); var request = new RestRequest(Method.DELETE); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("undefined", "{ \"members\": [ \"USER_ID\", \"USER_ID\", \"USER_ID\" ] }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("undefined", "{ "members": [ "USER_ID", "USER_ID", "USER_ID" ] }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -50,7 +57,7 @@ func main() { url := "https://{yourDomain}/api/v2/organizations/ORG_ID/members" - payload := strings.NewReader("{ \"members\": [ \"USER_ID\", \"USER_ID\", \"USER_ID\" ] }") + payload := strings.NewReader("{ "members": [ "USER_ID", "USER_ID", "USER_ID" ] }") req, _ := http.NewRequest("DELETE", url, payload) @@ -65,13 +72,17 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.delete("https://{yourDomain}/api/v2/organizations/ORG_ID/members") +} +``` +```java Java +HttpResponse response = Unirest.delete("https://{yourDomain}/api/v2/organizations/ORG_ID/members") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ \"members\": [ \"USER_ID\", \"USER_ID\", \"USER_ID\" ] }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "members": [ "USER_ID", "USER_ID", "USER_ID" ] }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'DELETE', @@ -84,8 +95,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @"cache-control": @"no-cache" }; @@ -110,8 +123,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/organizations/ORG_ID/members", @@ -121,7 +136,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "DELETE", - CURLOPT_POSTFIELDS => "{ \"members\": [ \"USER_ID\", \"USER_ID\", \"USER_ID\" ] }", + CURLOPT_POSTFIELDS => "{ "members": [ "USER_ID", "USER_ID", "USER_ID" ] }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "cache-control: no-cache" @@ -137,12 +152,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"members\": [ \"USER_ID\", \"USER_ID\", \"USER_ID\" ] }" +payload = "{ "members": [ "USER_ID", "USER_ID", "USER_ID" ] }" headers = { 'authorization': "Bearer MGMT_API_ACCESS_TOKEN", @@ -154,8 +171,10 @@ conn.request("DELETE", "/{yourDomain}/api/v2/organizations/ORG_ID/members", payl res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -168,11 +187,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Delete.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ \"members\": [ \"USER_ID\", \"USER_ID\", \"USER_ID\" ] }" +request.body = "{ "members": [ "USER_ID", "USER_ID", "USER_ID" ] }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "authorization": "Bearer MGMT_API_ACCESS_TOKEN", @@ -199,20 +220,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + diff --git a/main/docs/fr-ca/manage-users/organizations/configure-organizations/retrieve-connections.mdx b/main/docs/fr-ca/manage-users/organizations/configure-organizations/retrieve-connections.mdx index bedf97eaf..4859b13ff 100644 --- a/main/docs/fr-ca/manage-users/organizations/configure-organizations/retrieve-connections.mdx +++ b/main/docs/fr-ca/manage-users/organizations/configure-organizations/retrieve-connections.mdx @@ -10,6 +10,7 @@ permalink: "retrieve-connections" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Lorsque vous travaillez de manière programmatique avec des [organisations](/docs/fr-ca/manage-users/organizations/organizations-overview), il se peut que vous ayez besoin de récupérer la liste des connexions qui lui sont associées. @@ -26,14 +27,20 @@ Un produit permettant aux clients d’effectuer des tâches administratives." ct Effectuez un appel `GET` au point de terminaison `Get Organization Connections`. Assurez-vous de remplacer les valeurs des paramètres fictifs `ORG_ID` et `MGMT_API_ACCESS_TOKEN` par l’identifiant de votre organisation et le jeton d’accès à Management API, respectivement. -export const codeExample1 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/organizations/ORG_ID/enabled_connections' \ - --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/organizations/ORG_ID/enabled_connections"); + --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/organizations/ORG_ID/enabled_connections"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -57,11 +64,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/organizations/ORG_ID/enabled_connections") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/organizations/ORG_ID/enabled_connections") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -73,8 +84,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN" }; @@ -94,8 +107,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/organizations/ORG_ID/enabled_connections", @@ -119,8 +134,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -131,8 +148,10 @@ conn.request("GET", "/{yourDomain}/api/v2/organizations/ORG_ID/enabled_connectio res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -146,8 +165,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer MGMT_API_ACCESS_TOKEN"] @@ -167,20 +188,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + diff --git a/main/docs/fr-ca/manage-users/organizations/configure-organizations/retrieve-member-roles.mdx b/main/docs/fr-ca/manage-users/organizations/configure-organizations/retrieve-member-roles.mdx index ba6b34b6d..b37f043d1 100644 --- a/main/docs/fr-ca/manage-users/organizations/configure-organizations/retrieve-member-roles.mdx +++ b/main/docs/fr-ca/manage-users/organizations/configure-organizations/retrieve-member-roles.mdx @@ -10,6 +10,7 @@ permalink: "retrieve-member-roles" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Lorsque vous travaillez programmatiquement avec des [organisations](/docs/fr-ca/manage-users/organizations/organizations-overview), vous devrez peut-être récupérer une liste des rôles attribués à un membre d’une organisation. @@ -26,14 +27,20 @@ Un produit permettant aux clients d’effectuer des tâches administratives." ct Effectuez une requête `GET` au point de terminaison `Obtenir les rôles des membres d'une organisation`. Assurez-vous de remplacer les valeurs des espaces réservés `ORG_ID`, `USER_ID`, and `MGMT_API_ACCESS_TOKEN`, avec votre ID d’organisation, l’ID d’utilisateur du membre et votre jeton d’accès du Management API, respectivement. -export const codeExample1 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/organizations/ORG_ID/members/USER_ID/roles' \ - --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/organizations/ORG_ID/members/USER_ID/roles"); + --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/organizations/ORG_ID/members/USER_ID/roles"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -57,11 +64,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/organizations/ORG_ID/members/USER_ID/roles") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/organizations/ORG_ID/members/USER_ID/roles") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -73,8 +84,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN" }; @@ -94,8 +107,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/organizations/ORG_ID/members/USER_ID/roles", @@ -119,8 +134,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -131,8 +148,10 @@ conn.request("GET", "/{yourDomain}/api/v2/organizations/ORG_ID/members/USER_ID/r res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -146,8 +165,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer MGMT_API_ACCESS_TOKEN"] @@ -167,20 +188,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + diff --git a/main/docs/fr-ca/manage-users/organizations/configure-organizations/retrieve-members.mdx b/main/docs/fr-ca/manage-users/organizations/configure-organizations/retrieve-members.mdx index 582bd5f95..47148ac04 100644 --- a/main/docs/fr-ca/manage-users/organizations/configure-organizations/retrieve-members.mdx +++ b/main/docs/fr-ca/manage-users/organizations/configure-organizations/retrieve-members.mdx @@ -10,6 +10,7 @@ permalink: "retrieve-members" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Lorsque vous travaillez avec des [organisations](/docs/fr-ca/manage-users/organizations/organizations-overview) de manière programmatique, vous pouvez avoir besoin de récupérer la liste des membres d’organisation. @@ -32,14 +33,20 @@ Vous pouvez afficher jusqu’à 1 000 membres d’une organisation à l’aide Effectuez un appel `GET` vers le point de terminaison `Obtenir les utilisateurs de l’organisation`. Assurez-vous de remplacer les valeurs des paramètres fictifs `ORG_ID` et `MGMT_API_ACCESS_TOKEN` par l’identifiant de votre organisation et le jeton d’accès à Management API, respectivement. -export const codeExample1 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/organizations/ORG_ID/members' \ - --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/organizations/ORG_ID/members"); + --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/organizations/ORG_ID/members"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -63,11 +70,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/organizations/ORG_ID/members") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/organizations/ORG_ID/members") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -79,8 +90,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN" }; @@ -100,8 +113,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/organizations/ORG_ID/members", @@ -125,8 +140,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -137,8 +154,10 @@ conn.request("GET", "/{yourDomain}/api/v2/organizations/ORG_ID/members", headers res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -152,8 +171,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer MGMT_API_ACCESS_TOKEN"] @@ -173,20 +194,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + diff --git a/main/docs/fr-ca/manage-users/organizations/configure-organizations/retrieve-organizations.mdx b/main/docs/fr-ca/manage-users/organizations/configure-organizations/retrieve-organizations.mdx index f76738466..421d0f80a 100644 --- a/main/docs/fr-ca/manage-users/organizations/configure-organizations/retrieve-organizations.mdx +++ b/main/docs/fr-ca/manage-users/organizations/configure-organizations/retrieve-organizations.mdx @@ -10,6 +10,7 @@ permalink: "retrieve-organizations" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Lorsque vous travaillez avec [organizations](/docs/fr-ca/manage-users/organizations/organizations-overview) de manière programmatique, vous pouvez avoir besoin de récupérer soit une liste de toutes les organisations, soit des organisations individuellement par nom ou par ID. @@ -32,14 +33,20 @@ Pour récupérer plus de 1000 résultats, vous devez utiliser la méthode de pa Effectuez un appel `GET` au point de terminaison`Get Organizations`. Veillez à remplacer la valeur de remplacement `MGMT_API_ACCESS_TOKEN` par votre jeton d’accès au Management API. -export const codeExample1 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/organizations' \ - --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/organizations"); + --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/organizations"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -63,11 +70,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/organizations") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/organizations") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -79,8 +90,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN" }; @@ -100,8 +113,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/organizations", @@ -125,8 +140,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -137,8 +154,10 @@ conn.request("GET", "/{yourDomain}/api/v2/organizations", headers=headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -152,8 +171,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer MGMT_API_ACCESS_TOKEN"] @@ -173,20 +194,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + @@ -282,14 +292,20 @@ Vous pouvez récupérer une organisation par son identifiant via Management API. Effectuez un appel `GET` au point de terminaison`Get Organization`. Veillez à remplacer les valeurs de remplacement `ORG_ID` et `MGMT_API_ACCESS_TOKEN` par l’identifiant de votre organisation et le jeton d’accès à Management API, respectivement. -export const codeExample11 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/organizations/ORG_ID' \ - --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN'`; -export const codeExample12 = `var client = new RestClient("https://{yourDomain}/api/v2/organizations/ORG_ID"); + --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/organizations/ORG_ID"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); -IRestResponse response = client.Execute(request);`; -export const codeExample13 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -313,11 +329,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample14 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/organizations/ORG_ID") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/organizations/ORG_ID") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") - .asString();`; -export const codeExample15 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -329,8 +349,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample16 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN" }; @@ -350,8 +372,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/organizations/ORG_ID", @@ -375,8 +399,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -387,8 +413,10 @@ conn.request("GET", "/{yourDomain}/api/v2/organizations/ORG_ID", headers=headers res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -402,8 +430,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer MGMT_API_ACCESS_TOKEN"] @@ -423,20 +453,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + @@ -530,14 +549,20 @@ Vous pouvez récupérer une organisation par son nom via Management API. Effectuez un appel `GET` au point de terminaison`Get Organization by Name`. Veillez à remplacer les valeurs fictives `ORG_NAME` et `MGMT_API_ACCESS_TOKEN` par l’identifiant de votre organisation et le jeton d’accès à Management API, respectivement. -export const codeExample21 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/organizations/name/ORG_NAME' \ - --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN'`; -export const codeExample22 = `var client = new RestClient("https://{yourDomain}/api/v2/organizations/name/ORG_NAME"); + --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/organizations/name/ORG_NAME"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); -IRestResponse response = client.Execute(request);`; -export const codeExample23 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -561,11 +586,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample24 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/organizations/name/ORG_NAME") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/organizations/name/ORG_NAME") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") - .asString();`; -export const codeExample25 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -577,8 +606,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample26 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN" }; @@ -598,8 +629,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample27 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/organizations/name/ORG_NAME", @@ -623,8 +656,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample28 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -635,8 +670,10 @@ conn.request("GET", "/{yourDomain}/api/v2/organizations/name/ORG_NAME", headers= res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample29 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -650,8 +687,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' response = http.request(request) -puts response.read_body`; -export const codeExample30 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer MGMT_API_ACCESS_TOKEN"] @@ -671,20 +710,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + diff --git a/main/docs/fr-ca/manage-users/organizations/configure-organizations/retrieve-user-membership.mdx b/main/docs/fr-ca/manage-users/organizations/configure-organizations/retrieve-user-membership.mdx index acc5b9ac3..87bb5c9ff 100644 --- a/main/docs/fr-ca/manage-users/organizations/configure-organizations/retrieve-user-membership.mdx +++ b/main/docs/fr-ca/manage-users/organizations/configure-organizations/retrieve-user-membership.mdx @@ -10,6 +10,7 @@ permalink: "retrieve-user-membership" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Lorsque vous travaillez avec des [organisations](/docs/fr-ca/manage-users/organizations/organizations-overview) de manière programmatique, vous devrez peut-être récupérer la liste des organisations auxquelles un utilisateur est affilié. @@ -24,14 +25,20 @@ Vous pouvez afficher jusqu’à 1 000 membres d’une organisation à l’aide Effectuez un appel `GET` au point de terminaison `Obtenir les organisations d’utilisateurs`. Veillez à remplacer les valeurs d’espace réservé `USER_ID` et `MGMT_API_ACCESS_TOKEN` par l’ID utilisateur et votre jeton d’accès à Management API, respectivement. -export const codeExample1 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/users/USER_ID/organizations' \ - --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/users/USER_ID/organizations"); + --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users/USER_ID/organizations"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -55,11 +62,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/users/USER_ID/organizations") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/users/USER_ID/organizations") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -71,8 +82,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN" }; @@ -92,8 +105,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users/USER_ID/organizations", @@ -117,8 +132,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -129,8 +146,10 @@ conn.request("GET", "/{yourDomain}/api/v2/users/USER_ID/organizations", headers= res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -144,8 +163,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer MGMT_API_ACCESS_TOKEN"] @@ -165,20 +186,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + diff --git a/main/docs/fr-ca/manage-users/sessions/configure-session-lifetime-settings.mdx b/main/docs/fr-ca/manage-users/sessions/configure-session-lifetime-settings.mdx index aaec57a1f..9489cb542 100644 --- a/main/docs/fr-ca/manage-users/sessions/configure-session-lifetime-settings.mdx +++ b/main/docs/fr-ca/manage-users/sessions/configure-session-lifetime-settings.mdx @@ -10,6 +10,7 @@ permalink: "configure-session-lifetime-settings" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; **Expiration absolue** L’expiration absolue d’une session est définie lors de la création de la session. Vous pouvez ajuster l’Expiration absolue en configurant les paramètres de session à l’aide du Auth0 Dashboard ou de +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/tenants/settings' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{ "session_lifetime": SESSION_LIFETIME_VALUE, "idle_session_lifetime": IDLE_SESSION_LIFETIME_VALUE }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/tenants/settings"); + --data '{ "session_lifetime": SESSION_LIFETIME_VALUE, "idle_session_lifetime": IDLE_SESSION_LIFETIME_VALUE }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/tenants/settings"); var request = new RestRequest(Method.PATCH); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{ \"session_lifetime\": SESSION_LIFETIME_VALUE, \"idle_session_lifetime\": IDLE_SESSION_LIFETIME_VALUE }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "session_lifetime": SESSION_LIFETIME_VALUE, "idle_session_lifetime": IDLE_SESSION_LIFETIME_VALUE }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -70,7 +77,7 @@ func main() { url := "https://{yourDomain}/api/v2/tenants/settings" - payload := strings.NewReader("{ \"session_lifetime\": SESSION_LIFETIME_VALUE, \"idle_session_lifetime\": IDLE_SESSION_LIFETIME_VALUE }") + payload := strings.NewReader("{ "session_lifetime": SESSION_LIFETIME_VALUE, "idle_session_lifetime": IDLE_SESSION_LIFETIME_VALUE }") req, _ := http.NewRequest("PATCH", url, payload) @@ -86,14 +93,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/tenants/settings") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/tenants/settings") .header("content-type", "application/json") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ \"session_lifetime\": SESSION_LIFETIME_VALUE, \"idle_session_lifetime\": IDLE_SESSION_LIFETIME_VALUE }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "session_lifetime": SESSION_LIFETIME_VALUE, "idle_session_lifetime": IDLE_SESSION_LIFETIME_VALUE }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -110,8 +121,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @@ -136,8 +149,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/tenants/settings", @@ -147,7 +162,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{ \"session_lifetime\": SESSION_LIFETIME_VALUE, \"idle_session_lifetime\": IDLE_SESSION_LIFETIME_VALUE }", + CURLOPT_POSTFIELDS => "{ "session_lifetime": SESSION_LIFETIME_VALUE, "idle_session_lifetime": IDLE_SESSION_LIFETIME_VALUE }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "cache-control: no-cache", @@ -164,12 +179,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"session_lifetime\": SESSION_LIFETIME_VALUE, \"idle_session_lifetime\": IDLE_SESSION_LIFETIME_VALUE }" +payload = "{ "session_lifetime": SESSION_LIFETIME_VALUE, "idle_session_lifetime": IDLE_SESSION_LIFETIME_VALUE }" headers = { 'content-type': "application/json", @@ -182,8 +199,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/tenants/settings", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -197,11 +216,13 @@ request = Net::HTTP::Patch.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ \"session_lifetime\": SESSION_LIFETIME_VALUE, \"idle_session_lifetime\": IDLE_SESSION_LIFETIME_VALUE }" +request.body = "{ "session_lifetime": SESSION_LIFETIME_VALUE, "idle_session_lifetime": IDLE_SESSION_LIFETIME_VALUE }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -228,20 +249,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
diff --git a/main/docs/fr-ca/manage-users/user-accounts/change-user-picture.mdx b/main/docs/fr-ca/manage-users/user-accounts/change-user-picture.mdx index d34dae596..8acb2f61c 100644 --- a/main/docs/fr-ca/manage-users/user-accounts/change-user-picture.mdx +++ b/main/docs/fr-ca/manage-users/user-accounts/change-user-picture.mdx @@ -10,6 +10,7 @@ permalink: "change-user-picture" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Auth0 normalise les propriétés de profil commun dans le profil utilisateur : `name`, `picture`, etc. Le champ relatif à l’image est alimenté soit par l’image de profil du fournisseur social, soit par l’image Gravatar associée à l’adresse courriel de l’utilisateur. @@ -21,18 +22,24 @@ L’attribut `user.picture` n’est pas directement modifiable lorsqu’il est f Alternativement, vous pouvez utiliser des métadonnées pour stocker l’attribut d’image pour les utilisateurs. Par exemple, si votre application permet de télécharger des photos de profil, une fois la photo téléchargée, vous pouvez définir l’URL de l’image dans `user.user_metadata.picture` : -export const codeExample1 = `curl --request PATCH \ + +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/users/USER_ID' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'content-type: application/json' \ - --data '{"user_metadata": {"picture": "https://example.com/some-image.png"}}'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/users/USER_ID"); + --data '{"user_metadata": {"picture": "https://example.com/some-image.png"}}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users/USER_ID"); var request = new RestRequest(Method.PATCH); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\"user_metadata\": {\"picture\": \"https://example.com/some-image.png\"}}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{"user_metadata": {"picture": "https://example.com/some-image.png"}}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -45,7 +52,7 @@ func main() { url := "https://{yourDomain}/api/v2/users/USER_ID" - payload := strings.NewReader("{\"user_metadata\": {\"picture\": \"https://example.com/some-image.png\"}}") + payload := strings.NewReader("{"user_metadata": {"picture": "https://example.com/some-image.png"}}") req, _ := http.NewRequest("PATCH", url, payload) @@ -60,13 +67,17 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/users/USER_ID") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/users/USER_ID") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("content-type", "application/json") - .body("{\"user_metadata\": {\"picture\": \"https://example.com/some-image.png\"}}") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{"user_metadata": {"picture": "https://example.com/some-image.png"}}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -82,8 +93,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @"content-type": @"application/json" }; @@ -108,8 +121,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users/USER_ID", @@ -119,7 +134,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{\"user_metadata\": {\"picture\": \"https://example.com/some-image.png\"}}", + CURLOPT_POSTFIELDS => "{"user_metadata": {"picture": "https://example.com/some-image.png"}}", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "content-type: application/json" @@ -135,12 +150,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"user_metadata\": {\"picture\": \"https://example.com/some-image.png\"}}" +payload = "{"user_metadata": {"picture": "https://example.com/some-image.png"}}" headers = { 'authorization': "Bearer MGMT_API_ACCESS_TOKEN", @@ -152,8 +169,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/users/USER_ID", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -166,11 +185,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Patch.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["content-type"] = 'application/json' -request.body = "{\"user_metadata\": {\"picture\": \"https://example.com/some-image.png\"}}" +request.body = "{"user_metadata": {"picture": "https://example.com/some-image.png"}}" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "authorization": "Bearer MGMT_API_ACCESS_TOKEN", @@ -197,20 +218,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ## Utiliser les Actions diff --git a/main/docs/fr-ca/manage-users/user-accounts/metadata/manage-metadata-api.mdx b/main/docs/fr-ca/manage-users/user-accounts/metadata/manage-metadata-api.mdx index 0c0bf35b3..071d695ad 100644 --- a/main/docs/fr-ca/manage-users/user-accounts/metadata/manage-metadata-api.mdx +++ b/main/docs/fr-ca/manage-users/user-accounts/metadata/manage-metadata-api.mdx @@ -10,6 +10,7 @@ permalink: "manage-metadata-api" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; ## Métadonnées de l’utilisateur @@ -32,18 +33,24 @@ Pour créer un utilisateur avec les détails de profil suivants : Effectuez l’appel `POST` suivant au point de terminaison Management API [`/post_users`](/docs/fr-ca/api/management/v2#!/Users/post_users) pour créer l’utilisateur et définir les valeurs des propriétés : -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/api/v2/users' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'content-type: application/json' \ - --data '{"email": "jane.doe@example.com", "user_metadata": {"hobby": "surfing"}, "app_metadata": {"plan": "full"}}'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/users"); + --data '{"email": "jane.doe@example.com", "user_metadata": {"hobby": "surfing"}, "app_metadata": {"plan": "full"}}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users"); var request = new RestRequest(Method.POST); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\"email\": \"jane.doe@example.com\", \"user_metadata\": {\"hobby\": \"surfing\"}, \"app_metadata\": {\"plan\": \"full\"}}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{"email": "jane.doe@example.com", "user_metadata": {"hobby": "surfing"}, "app_metadata": {"plan": "full"}}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -56,7 +63,7 @@ func main() { url := "https://{yourDomain}/api/v2/users" - payload := strings.NewReader("{\"email\": \"jane.doe@example.com\", \"user_metadata\": {\"hobby\": \"surfing\"}, \"app_metadata\": {\"plan\": \"full\"}}") + payload := strings.NewReader("{"email": "jane.doe@example.com", "user_metadata": {"hobby": "surfing"}, "app_metadata": {"plan": "full"}}") req, _ := http.NewRequest("POST", url, payload) @@ -71,13 +78,17 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/users") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/users") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("content-type", "application/json") - .body("{\"email\": \"jane.doe@example.com\", \"user_metadata\": {\"hobby\": \"surfing\"}, \"app_metadata\": {\"plan\": \"full\"}}") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{"email": "jane.doe@example.com", "user_metadata": {"hobby": "surfing"}, "app_metadata": {"plan": "full"}}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -97,8 +108,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @"content-type": @"application/json" }; @@ -125,8 +138,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users", @@ -136,7 +151,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{\"email\": \"jane.doe@example.com\", \"user_metadata\": {\"hobby\": \"surfing\"}, \"app_metadata\": {\"plan\": \"full\"}}", + CURLOPT_POSTFIELDS => "{"email": "jane.doe@example.com", "user_metadata": {"hobby": "surfing"}, "app_metadata": {"plan": "full"}}", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "content-type: application/json" @@ -152,12 +167,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"email\": \"jane.doe@example.com\", \"user_metadata\": {\"hobby\": \"surfing\"}, \"app_metadata\": {\"plan\": \"full\"}}" +payload = "{"email": "jane.doe@example.com", "user_metadata": {"hobby": "surfing"}, "app_metadata": {"plan": "full"}}" headers = { 'authorization': "Bearer MGMT_API_ACCESS_TOKEN", @@ -169,8 +186,10 @@ conn.request("POST", "/{yourDomain}/api/v2/users", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -183,11 +202,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["content-type"] = 'application/json' -request.body = "{\"email\": \"jane.doe@example.com\", \"user_metadata\": {\"hobby\": \"surfing\"}, \"app_metadata\": {\"plan\": \"full\"}}" +request.body = "{"email": "jane.doe@example.com", "user_metadata": {"hobby": "surfing"}, "app_metadata": {"plan": "full"}}" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "authorization": "Bearer MGMT_API_ACCESS_TOKEN", @@ -218,20 +239,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ### Mettre à jour les métadonnées d’un utilisateur @@ -263,18 +273,24 @@ To update `user_metadata` and add the user’s home address as a second-level pr Vous feriez l’appel `PATCH` suivant : -export const codeExample11 = `curl --request PATCH \ + +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/users/user_id' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'content-type: application/json' \ - --data '{"user_metadata": {"addresses": {"home": "123 Main Street, Anytown, ST 12345"}}}'`; -export const codeExample12 = `var client = new RestClient("https://{yourDomain}/api/v2/users/user_id"); + --data '{"user_metadata": {"addresses": {"home": "123 Main Street, Anytown, ST 12345"}}}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users/user_id"); var request = new RestRequest(Method.PATCH); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\"user_metadata\": {\"addresses\": {\"home\": \"123 Main Street, Anytown, ST 12345\"}}}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample13 = `package main +request.AddParameter("application/json", "{"user_metadata": {"addresses": {"home": "123 Main Street, Anytown, ST 12345"}}}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -287,7 +303,7 @@ func main() { url := "https://{yourDomain}/api/v2/users/user_id" - payload := strings.NewReader("{\"user_metadata\": {\"addresses\": {\"home\": \"123 Main Street, Anytown, ST 12345\"}}}") + payload := strings.NewReader("{"user_metadata": {"addresses": {"home": "123 Main Street, Anytown, ST 12345"}}}") req, _ := http.NewRequest("PATCH", url, payload) @@ -302,13 +318,17 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample14 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/users/user_id") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/users/user_id") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("content-type", "application/json") - .body("{\"user_metadata\": {\"addresses\": {\"home\": \"123 Main Street, Anytown, ST 12345\"}}}") - .asString();`; -export const codeExample15 = `var axios = require("axios").default; + .body("{"user_metadata": {"addresses": {"home": "123 Main Street, Anytown, ST 12345"}}}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -324,8 +344,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample16 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @"content-type": @"application/json" }; @@ -350,8 +372,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users/user_id", @@ -361,7 +385,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{\"user_metadata\": {\"addresses\": {\"home\": \"123 Main Street, Anytown, ST 12345\"}}}", + CURLOPT_POSTFIELDS => "{"user_metadata": {"addresses": {"home": "123 Main Street, Anytown, ST 12345"}}}", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "content-type: application/json" @@ -377,12 +401,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"user_metadata\": {\"addresses\": {\"home\": \"123 Main Street, Anytown, ST 12345\"}}}" +payload = "{"user_metadata": {"addresses": {"home": "123 Main Street, Anytown, ST 12345"}}}" headers = { 'authorization': "Bearer MGMT_API_ACCESS_TOKEN", @@ -394,8 +420,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/users/user_id", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -408,11 +436,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Patch.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["content-type"] = 'application/json' -request.body = "{\"user_metadata\": {\"addresses\": {\"home\": \"123 Main Street, Anytown, ST 12345\"}}}" +request.body = "{"user_metadata": {"addresses": {"home": "123 Main Street, Anytown, ST 12345"}}}" response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "authorization": "Bearer MGMT_API_ACCESS_TOKEN", @@ -439,20 +469,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + The user’s profile will now appear as follows: @@ -496,18 +515,24 @@ For example, to add a user’s work address as an additional inner property, you Par conséquent, l’appel `PATCH` correspondant à l’API serait : -export const codeExample21 = `curl --request PATCH \ + +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/users/user_id' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'content-type: application/json' \ - --data '{"user_metadata": {"addresses": {"home": "123 Main Street, Anytown, ST 12345", "work": "100 Industrial Way, Anytown, ST 12345"}}}'`; -export const codeExample22 = `var client = new RestClient("https://{yourDomain}/api/v2/users/user_id"); + --data '{"user_metadata": {"addresses": {"home": "123 Main Street, Anytown, ST 12345", "work": "100 Industrial Way, Anytown, ST 12345"}}}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users/user_id"); var request = new RestRequest(Method.PATCH); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\"user_metadata\": {\"addresses\": {\"home\": \"123 Main Street, Anytown, ST 12345\", \"work\": \"100 Industrial Way, Anytown, ST 12345\"}}}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample23 = `package main +request.AddParameter("application/json", "{"user_metadata": {"addresses": {"home": "123 Main Street, Anytown, ST 12345", "work": "100 Industrial Way, Anytown, ST 12345"}}}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -520,7 +545,7 @@ func main() { url := "https://{yourDomain}/api/v2/users/user_id" - payload := strings.NewReader("{\"user_metadata\": {\"addresses\": {\"home\": \"123 Main Street, Anytown, ST 12345\", \"work\": \"100 Industrial Way, Anytown, ST 12345\"}}}") + payload := strings.NewReader("{"user_metadata": {"addresses": {"home": "123 Main Street, Anytown, ST 12345", "work": "100 Industrial Way, Anytown, ST 12345"}}}") req, _ := http.NewRequest("PATCH", url, payload) @@ -535,13 +560,17 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample24 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/users/user_id") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/users/user_id") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("content-type", "application/json") - .body("{\"user_metadata\": {\"addresses\": {\"home\": \"123 Main Street, Anytown, ST 12345\", \"work\": \"100 Industrial Way, Anytown, ST 12345\"}}}") - .asString();`; -export const codeExample25 = `var axios = require("axios").default; + .body("{"user_metadata": {"addresses": {"home": "123 Main Street, Anytown, ST 12345", "work": "100 Industrial Way, Anytown, ST 12345"}}}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -564,8 +593,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample26 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @"content-type": @"application/json" }; @@ -590,8 +621,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample27 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users/user_id", @@ -601,7 +634,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{\"user_metadata\": {\"addresses\": {\"home\": \"123 Main Street, Anytown, ST 12345\", \"work\": \"100 Industrial Way, Anytown, ST 12345\"}}}", + CURLOPT_POSTFIELDS => "{"user_metadata": {"addresses": {"home": "123 Main Street, Anytown, ST 12345", "work": "100 Industrial Way, Anytown, ST 12345"}}}", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "content-type: application/json" @@ -617,12 +650,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample28 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"user_metadata\": {\"addresses\": {\"home\": \"123 Main Street, Anytown, ST 12345\", \"work\": \"100 Industrial Way, Anytown, ST 12345\"}}}" +payload = "{"user_metadata": {"addresses": {"home": "123 Main Street, Anytown, ST 12345", "work": "100 Industrial Way, Anytown, ST 12345"}}}" headers = { 'authorization': "Bearer MGMT_API_ACCESS_TOKEN", @@ -634,8 +669,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/users/user_id", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample29 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -648,11 +685,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Patch.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["content-type"] = 'application/json' -request.body = "{\"user_metadata\": {\"addresses\": {\"home\": \"123 Main Street, Anytown, ST 12345\", \"work\": \"100 Industrial Way, Anytown, ST 12345\"}}}" +request.body = "{"user_metadata": {"addresses": {"home": "123 Main Street, Anytown, ST 12345", "work": "100 Industrial Way, Anytown, ST 12345"}}}" response = http.request(request) -puts response.read_body`; -export const codeExample30 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "authorization": "Bearer MGMT_API_ACCESS_TOKEN", @@ -682,20 +721,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ### Supprimer les métadonnées de l’utilisateur diff --git a/main/docs/fr-ca/manage-users/user-accounts/user-account-linking.mdx b/main/docs/fr-ca/manage-users/user-accounts/user-account-linking.mdx index 6b36080c4..9adc416b3 100644 --- a/main/docs/fr-ca/manage-users/user-accounts/user-account-linking.mdx +++ b/main/docs/fr-ca/manage-users/user-accounts/user-account-linking.mdx @@ -2,6 +2,9 @@ title: Association de comptes d’utilisateur --- + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + Auth0 permet de relier des comptes d’utilisateurs provenant de différents fournisseurs d’identité. Cela permet à un utilisateur de s’authentifier à partir de n’importe lequel de ses comptes tout en étant toujours reconnu par votre application et associé au même profil utilisateur. @@ -31,7 +34,7 @@ Le processus de liaison des comptes permet de fusionner deux profils utilisateur Vous pouvez voir ci-dessous comment se présentera le profil résultant de l’association du compte primaire et du compte secondaire de notre exemple. - + ```json Profil du compte principal "email": "your0@email.com", @@ -131,7 +134,7 @@ Vous pouvez voir ci-dessous comment se présentera le profil résultant de l’a ... } ``` - + Remarques : diff --git a/main/docs/fr-ca/manage-users/user-accounts/user-profiles/configure-connection-sync-with-auth0.mdx b/main/docs/fr-ca/manage-users/user-accounts/user-profiles/configure-connection-sync-with-auth0.mdx index 47654fd39..6381d9e2c 100644 --- a/main/docs/fr-ca/manage-users/user-accounts/user-profiles/configure-connection-sync-with-auth0.mdx +++ b/main/docs/fr-ca/manage-users/user-accounts/user-profiles/configure-connection-sync-with-auth0.mdx @@ -10,6 +10,7 @@ permalink: "configure-connection-sync-with-auth0" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Vous pouvez mettre à jour les préférences de connexion pour un fournisseur d’identité en amont afin de contrôler quand les mises à jour des attributs racine du profil utilisateur sont autorisées à l’aide de Auth0 Dashboard ou de response = Unirest.patch("https://{yourDomain}/api/v2/connections/CONNECTION_ID") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/connections/CONNECTION_ID") .header("content-type", "application/json") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{\"options\":{\"set_user_root_attributes\": \"ATTRIBUTE_UPDATE_VALUE\"}}") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{"options":{"set_user_root_attributes": "ATTRIBUTE_UPDATE_VALUE"}}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -105,8 +116,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @@ -132,8 +145,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/connections/CONNECTION_ID", @@ -143,7 +158,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{\"options\":{\"set_user_root_attributes\": \"ATTRIBUTE_UPDATE_VALUE\"}}", + CURLOPT_POSTFIELDS => "{"options":{"set_user_root_attributes": "ATTRIBUTE_UPDATE_VALUE"}}", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "cache-control: no-cache", @@ -160,12 +175,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"options\":{\"set_user_root_attributes\": \"ATTRIBUTE_UPDATE_VALUE\"}}" +payload = "{"options":{"set_user_root_attributes": "ATTRIBUTE_UPDATE_VALUE"}}" headers = { 'content-type': "application/json", @@ -178,8 +195,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/connections/CONNECTION_ID", payload, res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -193,11 +212,13 @@ request = Net::HTTP::Patch.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{\"options\":{\"set_user_root_attributes\": \"ATTRIBUTE_UPDATE_VALUE\"}}" +request.body = "{"options":{"set_user_root_attributes": "ATTRIBUTE_UPDATE_VALUE"}}" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -225,20 +246,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
diff --git a/main/docs/fr-ca/manage-users/user-accounts/user-profiles/root-attributes/set-root-attributes-during-user-import.mdx b/main/docs/fr-ca/manage-users/user-accounts/user-profiles/root-attributes/set-root-attributes-during-user-import.mdx index e44522831..1a8b87e22 100644 --- a/main/docs/fr-ca/manage-users/user-accounts/user-profiles/root-attributes/set-root-attributes-during-user-import.mdx +++ b/main/docs/fr-ca/manage-users/user-accounts/user-profiles/root-attributes/set-root-attributes-during-user-import.mdx @@ -10,24 +10,31 @@ permalink: "set-root-attributes-during-user-import" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Ce guide vous montrera comment établir les attributs racine pour les utilisateurs au cours de l’importation en utilisant Management API Auth0. Cela permet de minimiser le nombre de requêtes API nécessaires pour établir les attributs racine lorsque vous importez des utilisateurs. Pour voir quels attributs vous pouvez importer, visitez [Structure du profil utilisateur normalisé](/docs/fr-ca/manage-users/user-accounts/user-profiles/user-profile-structure). Faites une requête `POST` au point de terminaison [Créer une tâche pour importer les utilisateurs](/docs/fr-ca/api/management/v2#!/Jobs/post_users_imports). Assurez-vous de remplacer les valeurs des espaces réservés `MGMT_API_ACCESS_TOKEN`, `CONNECTION_ID`, and `JSON_USER_FILE_PATH` avec votre jeton d’accès de Management API, votre ID de connexion et le nom du fichier contenant les utilisateurs, respectivement. -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/api/v2/jobs/usersimports' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'content-type: multipart/form-data ' \ - --data '{ "connection_id": "CONNECTION_ID", "users": "JSON_USER_FILE_PATH" }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/jobs/usersimports"); + --data '{ "connection_id": "CONNECTION_ID", "users": "JSON_USER_FILE_PATH" }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/jobs/usersimports"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "multipart/form-data "); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); -request.AddParameter("multipart/form-data ", "{ \"connection_id\": \"CONNECTION_ID\", \"users\": \"JSON_USER_FILE_PATH\" }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("multipart/form-data ", "{ "connection_id": "CONNECTION_ID", "users": "JSON_USER_FILE_PATH" }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -40,7 +47,7 @@ func main() { url := "https://{yourDomain}/api/v2/jobs/usersimports" - payload := strings.NewReader("{ \"connection_id\": \"CONNECTION_ID\", \"users\": \"JSON_USER_FILE_PATH\" }") + payload := strings.NewReader("{ "connection_id": "CONNECTION_ID", "users": "JSON_USER_FILE_PATH" }") req, _ := http.NewRequest("POST", url, payload) @@ -55,13 +62,17 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/jobs/usersimports") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/jobs/usersimports") .header("content-type", "multipart/form-data ") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") - .body("{ \"connection_id\": \"CONNECTION_ID\", \"users\": \"JSON_USER_FILE_PATH\" }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "connection_id": "CONNECTION_ID", "users": "JSON_USER_FILE_PATH" }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -77,8 +88,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"multipart/form-data ", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN" }; @@ -102,8 +115,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/jobs/usersimports", @@ -113,7 +128,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{ \"connection_id\": \"CONNECTION_ID\", \"users\": \"JSON_USER_FILE_PATH\" }", + CURLOPT_POSTFIELDS => "{ "connection_id": "CONNECTION_ID", "users": "JSON_USER_FILE_PATH" }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "content-type: multipart/form-data " @@ -129,12 +144,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"connection_id\": \"CONNECTION_ID\", \"users\": \"JSON_USER_FILE_PATH\" }" +payload = "{ "connection_id": "CONNECTION_ID", "users": "JSON_USER_FILE_PATH" }" headers = { 'content-type': "multipart/form-data ", @@ -146,8 +163,10 @@ conn.request("POST", "/{yourDomain}/api/v2/jobs/usersimports", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -160,11 +179,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["content-type"] = 'multipart/form-data ' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' -request.body = "{ \"connection_id\": \"CONNECTION_ID\", \"users\": \"JSON_USER_FILE_PATH\" }" +request.body = "{ "connection_id": "CONNECTION_ID", "users": "JSON_USER_FILE_PATH" }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "multipart/form-data ", @@ -190,20 +211,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
diff --git a/main/docs/fr-ca/manage-users/user-accounts/user-profiles/root-attributes/set-root-attributes-during-user-sign-up.mdx b/main/docs/fr-ca/manage-users/user-accounts/user-profiles/root-attributes/set-root-attributes-during-user-sign-up.mdx index f2d6c6611..1e8c09312 100644 --- a/main/docs/fr-ca/manage-users/user-accounts/user-profiles/root-attributes/set-root-attributes-during-user-sign-up.mdx +++ b/main/docs/fr-ca/manage-users/user-accounts/user-profiles/root-attributes/set-root-attributes-during-user-sign-up.mdx @@ -10,26 +10,33 @@ permalink: "set-root-attributes-during-user-sign-up" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Vous pouvez établir les attributs racine pour les utilisateurs au cours de l’inscription en utilisant Management API Auth0. Cela permet de minimiser le nombre de requêtes API nécessaires pour établir les attributs racines lorsque vous créez des utilisateurs. Faites une requête `POST` au [point de terminaison Créer un utilisateur](/docs/fr-ca/api/management/v2#!/Users/post_users). Assurez-vous de remplacer les espaces réservés `MGMT_API_ACCESS_TOKEN`, `CONNECTION_NAME`, `EMAIL_VALUE`, `PASSWORD_VALUE`, `GIVEN_NAME_VALUE`, `FAMILY_NAME_VALUE`, `NAME_VALUE`, `NICKNAME_VALUE`, and `PICTURE` avec votre jeton d’accès à Management API, votre nom de connexion initial, votre adresse courriel, votre mot de passe, votre prénom, votre nom de famille, votre nom, votre surnom et votre photo, URL, respectivement. -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/api/v2/users' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{ "connection": CONNECTION_NAME, "email": EMAIL_VALUE, "password": PASSWORD_VALUE, "given_name": GIVEN_NAME_VALUE, "family_name": FAMILY_NAME_VALUE,"name": NAME_VALUE, "nickname": NICKNAME_VALUE,"picture": PICTURE_VALUE }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/users"); + --data '{ "connection": CONNECTION_NAME, "email": EMAIL_VALUE, "password": PASSWORD_VALUE, "given_name": GIVEN_NAME_VALUE, "family_name": FAMILY_NAME_VALUE,"name": NAME_VALUE, "nickname": NICKNAME_VALUE,"picture": PICTURE_VALUE }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{ \"connection\": CONNECTION_NAME, \"email\": EMAIL_VALUE, \"password\": PASSWORD_VALUE, \"given_name\": GIVEN_NAME_VALUE, \"family_name\": FAMILY_NAME_VALUE,\"name\": NAME_VALUE, \"nickname\": NICKNAME_VALUE,\"picture\": PICTURE_VALUE }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "connection": CONNECTION_NAME, "email": EMAIL_VALUE, "password": PASSWORD_VALUE, "given_name": GIVEN_NAME_VALUE, "family_name": FAMILY_NAME_VALUE,"name": NAME_VALUE, "nickname": NICKNAME_VALUE,"picture": PICTURE_VALUE }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -42,7 +49,7 @@ func main() { url := "https://{yourDomain}/api/v2/users" - payload := strings.NewReader("{ \"connection\": CONNECTION_NAME, \"email\": EMAIL_VALUE, \"password\": PASSWORD_VALUE, \"given_name\": GIVEN_NAME_VALUE, \"family_name\": FAMILY_NAME_VALUE,\"name\": NAME_VALUE, \"nickname\": NICKNAME_VALUE,\"picture\": PICTURE_VALUE }") + payload := strings.NewReader("{ "connection": CONNECTION_NAME, "email": EMAIL_VALUE, "password": PASSWORD_VALUE, "given_name": GIVEN_NAME_VALUE, "family_name": FAMILY_NAME_VALUE,"name": NAME_VALUE, "nickname": NICKNAME_VALUE,"picture": PICTURE_VALUE }") req, _ := http.NewRequest("POST", url, payload) @@ -58,14 +65,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/users") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/users") .header("content-type", "application/json") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ \"connection\": CONNECTION_NAME, \"email\": EMAIL_VALUE, \"password\": PASSWORD_VALUE, \"given_name\": GIVEN_NAME_VALUE, \"family_name\": FAMILY_NAME_VALUE,\"name\": NAME_VALUE, \"nickname\": NICKNAME_VALUE,\"picture\": PICTURE_VALUE }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "connection": CONNECTION_NAME, "email": EMAIL_VALUE, "password": PASSWORD_VALUE, "given_name": GIVEN_NAME_VALUE, "family_name": FAMILY_NAME_VALUE,"name": NAME_VALUE, "nickname": NICKNAME_VALUE,"picture": PICTURE_VALUE }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -82,8 +93,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @@ -108,8 +121,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users", @@ -119,7 +134,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{ \"connection\": CONNECTION_NAME, \"email\": EMAIL_VALUE, \"password\": PASSWORD_VALUE, \"given_name\": GIVEN_NAME_VALUE, \"family_name\": FAMILY_NAME_VALUE,\"name\": NAME_VALUE, \"nickname\": NICKNAME_VALUE,\"picture\": PICTURE_VALUE }", + CURLOPT_POSTFIELDS => "{ "connection": CONNECTION_NAME, "email": EMAIL_VALUE, "password": PASSWORD_VALUE, "given_name": GIVEN_NAME_VALUE, "family_name": FAMILY_NAME_VALUE,"name": NAME_VALUE, "nickname": NICKNAME_VALUE,"picture": PICTURE_VALUE }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "cache-control: no-cache", @@ -136,12 +151,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"connection\": CONNECTION_NAME, \"email\": EMAIL_VALUE, \"password\": PASSWORD_VALUE, \"given_name\": GIVEN_NAME_VALUE, \"family_name\": FAMILY_NAME_VALUE,\"name\": NAME_VALUE, \"nickname\": NICKNAME_VALUE,\"picture\": PICTURE_VALUE }" +payload = "{ "connection": CONNECTION_NAME, "email": EMAIL_VALUE, "password": PASSWORD_VALUE, "given_name": GIVEN_NAME_VALUE, "family_name": FAMILY_NAME_VALUE,"name": NAME_VALUE, "nickname": NICKNAME_VALUE,"picture": PICTURE_VALUE }" headers = { 'content-type': "application/json", @@ -154,8 +171,10 @@ conn.request("POST", "/{yourDomain}/api/v2/users", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -169,11 +188,13 @@ request = Net::HTTP::Post.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ \"connection\": CONNECTION_NAME, \"email\": EMAIL_VALUE, \"password\": PASSWORD_VALUE, \"given_name\": GIVEN_NAME_VALUE, \"family_name\": FAMILY_NAME_VALUE,\"name\": NAME_VALUE, \"nickname\": NICKNAME_VALUE,\"picture\": PICTURE_VALUE }" +request.body = "{ "connection": CONNECTION_NAME, "email": EMAIL_VALUE, "password": PASSWORD_VALUE, "given_name": GIVEN_NAME_VALUE, "family_name": FAMILY_NAME_VALUE,"name": NAME_VALUE, "nickname": NICKNAME_VALUE,"picture": PICTURE_VALUE }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -200,20 +221,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
diff --git a/main/docs/fr-ca/manage-users/user-accounts/user-profiles/root-attributes/update-root-attributes-for-users.mdx b/main/docs/fr-ca/manage-users/user-accounts/user-profiles/root-attributes/update-root-attributes-for-users.mdx index 815f2dc1f..8c4ec28d2 100644 --- a/main/docs/fr-ca/manage-users/user-accounts/user-profiles/root-attributes/update-root-attributes-for-users.mdx +++ b/main/docs/fr-ca/manage-users/user-accounts/user-profiles/root-attributes/update-root-attributes-for-users.mdx @@ -10,6 +10,7 @@ permalink: "update-root-attributes-for-users" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Vous pouvez mettre à jour les attributs racine d’un profil utilisateur existant à l’aide de Management API d’Auth0. @@ -18,20 +19,26 @@ La fonctionnalité [Profil utilisateur normalisé](/docs/fr-ca/manage-users/user Faites un appel `PATCH (CORRECTIF)` à [Update a User endpoint (Mettre à jour le point de terminaison d’un utilisateur)](https://auth0.com/docs/api/management/v2/users/patch-users-by-id). Assurez-vous de remplacer les valeurs d’espace réservé `USER_ID`, `JMGMT_API_ACCESS_TOKEN`, `GIVEN_NAME_VALUE`, `FAMILY_NAME_VALUE`, `NAME_VALUE`, `NICKNAME_VALUE` et `PICTURE` avec votre identifiant utilisateur, votre jeton d’accès à Management API, votre prénom, votre nom de famille, votre nom, votre surnom et votre photo URL, respectivement. -export const codeExample1 = `curl --request PATCH \ + +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/users/USER_ID' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{ "given_name": GIVEN_NAME_VALUE, "family_name": FAMILY_NAME_VALUE,"name": NAME_VALUE, "nickname": NICKNAME_VALUE,"picture": PICTURE_VALUE }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/users/USER_ID"); + --data '{ "given_name": GIVEN_NAME_VALUE, "family_name": FAMILY_NAME_VALUE,"name": NAME_VALUE, "nickname": NICKNAME_VALUE,"picture": PICTURE_VALUE }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users/USER_ID"); var request = new RestRequest(Method.PATCH); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{ \"given_name\": GIVEN_NAME_VALUE, \"family_name\": FAMILY_NAME_VALUE,\"name\": NAME_VALUE, \"nickname\": NICKNAME_VALUE,\"picture\": PICTURE_VALUE }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "given_name": GIVEN_NAME_VALUE, "family_name": FAMILY_NAME_VALUE,"name": NAME_VALUE, "nickname": NICKNAME_VALUE,"picture": PICTURE_VALUE }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -44,7 +51,7 @@ func main() { url := "https://{yourDomain}/api/v2/users/USER_ID" - payload := strings.NewReader("{ \"given_name\": GIVEN_NAME_VALUE, \"family_name\": FAMILY_NAME_VALUE,\"name\": NAME_VALUE, \"nickname\": NICKNAME_VALUE,\"picture\": PICTURE_VALUE }") + payload := strings.NewReader("{ "given_name": GIVEN_NAME_VALUE, "family_name": FAMILY_NAME_VALUE,"name": NAME_VALUE, "nickname": NICKNAME_VALUE,"picture": PICTURE_VALUE }") req, _ := http.NewRequest("PATCH", url, payload) @@ -60,14 +67,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/users/USER_ID") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/users/USER_ID") .header("content-type", "application/json") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ \"given_name\": GIVEN_NAME_VALUE, \"family_name\": FAMILY_NAME_VALUE,\"name\": NAME_VALUE, \"nickname\": NICKNAME_VALUE,\"picture\": PICTURE_VALUE }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "given_name": GIVEN_NAME_VALUE, "family_name": FAMILY_NAME_VALUE,"name": NAME_VALUE, "nickname": NICKNAME_VALUE,"picture": PICTURE_VALUE }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -84,8 +95,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @@ -110,8 +123,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users/USER_ID", @@ -121,7 +136,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{ \"given_name\": GIVEN_NAME_VALUE, \"family_name\": FAMILY_NAME_VALUE,\"name\": NAME_VALUE, \"nickname\": NICKNAME_VALUE,\"picture\": PICTURE_VALUE }", + CURLOPT_POSTFIELDS => "{ "given_name": GIVEN_NAME_VALUE, "family_name": FAMILY_NAME_VALUE,"name": NAME_VALUE, "nickname": NICKNAME_VALUE,"picture": PICTURE_VALUE }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "cache-control: no-cache", @@ -138,12 +153,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"given_name\": GIVEN_NAME_VALUE, \"family_name\": FAMILY_NAME_VALUE,\"name\": NAME_VALUE, \"nickname\": NICKNAME_VALUE,\"picture\": PICTURE_VALUE }" +payload = "{ "given_name": GIVEN_NAME_VALUE, "family_name": FAMILY_NAME_VALUE,"name": NAME_VALUE, "nickname": NICKNAME_VALUE,"picture": PICTURE_VALUE }" headers = { 'content-type': "application/json", @@ -156,8 +173,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/users/USER_ID", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -171,11 +190,13 @@ request = Net::HTTP::Patch.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ \"given_name\": GIVEN_NAME_VALUE, \"family_name\": FAMILY_NAME_VALUE,\"name\": NAME_VALUE, \"nickname\": NICKNAME_VALUE,\"picture\": PICTURE_VALUE }" +request.body = "{ "given_name": GIVEN_NAME_VALUE, "family_name": FAMILY_NAME_VALUE,"name": NAME_VALUE, "nickname": NICKNAME_VALUE,"picture": PICTURE_VALUE }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -202,20 +223,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
diff --git a/main/docs/fr-ca/manage-users/user-migration/bulk-user-exports.mdx b/main/docs/fr-ca/manage-users/user-migration/bulk-user-exports.mdx index 954498bca..786790f40 100644 --- a/main/docs/fr-ca/manage-users/user-migration/bulk-user-exports.mdx +++ b/main/docs/fr-ca/manage-users/user-migration/bulk-user-exports.mdx @@ -10,6 +10,7 @@ permalink: "bulk-user-exports" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Vous pouvez utiliser le point de terminaison `POST /api/v2/jobs/users-exports` pour créer une tâche qui exporte tous les utilisateurs associés à une [connexion](/docs/fr-ca/identityproviders), ou tous les utilisateurs du locataire. @@ -54,18 +55,24 @@ Mettez à jour le `connection_id` avec votre ID de connexion à la base de donn Permissions requises : `read:users` -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/api/v2/jobs/users-exports' \ --header 'authorization: Bearer {yourMgmtAPIAccessToken}' \ --header 'content-type: application/json' \ - --data '{"connection_id": "{yourConnectionId}", "format": "csv", "limit": 5, "fields": [{"name": "email"}, { "name": "identities[0].connection", "export_as": "provider" }]}'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/jobs/users-exports"); + --data '{"connection_id": "{yourConnectionId}", "format": "csv", "limit": 5, "fields": [{"name": "email"}, { "name": "identities[0].connection", "export_as": "provider" }]}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/jobs/users-exports"); var request = new RestRequest(Method.POST); request.AddHeader("authorization", "Bearer {yourMgmtAPIAccessToken}"); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\"connection_id\": \"{yourConnectionId}\", \"format\": \"csv\", \"limit\": 5, \"fields\": [{\"name\": \"email\"}, { \"name\": \"identities[0].connection\", \"export_as\": \"provider\" }]}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{"connection_id": "{yourConnectionId}", "format": "csv", "limit": 5, "fields": [{"name": "email"}, { "name": "identities[0].connection", "export_as": "provider" }]}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -78,7 +85,7 @@ func main() { url := "https://{yourDomain}/api/v2/jobs/users-exports" - payload := strings.NewReader("{\"connection_id\": \"{yourConnectionId}\", \"format\": \"csv\", \"limit\": 5, \"fields\": [{\"name\": \"email\"}, { \"name\": \"identities[0].connection\", \"export_as\": \"provider\" }]}") + payload := strings.NewReader("{"connection_id": "{yourConnectionId}", "format": "csv", "limit": 5, "fields": [{"name": "email"}, { "name": "identities[0].connection", "export_as": "provider" }]}") req, _ := http.NewRequest("POST", url, payload) @@ -93,13 +100,17 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/jobs/users-exports") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/jobs/users-exports") .header("authorization", "Bearer {yourMgmtAPIAccessToken}") .header("content-type", "application/json") - .body("{\"connection_id\": \"{yourConnectionId}\", \"format\": \"csv\", \"limit\": 5, \"fields\": [{\"name\": \"email\"}, { \"name\": \"identities[0].connection\", \"export_as\": \"provider\" }]}") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{"connection_id": "{yourConnectionId}", "format": "csv", "limit": 5, "fields": [{"name": "email"}, { "name": "identities[0].connection", "export_as": "provider" }]}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -120,8 +131,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer {yourMgmtAPIAccessToken}", @"content-type": @"application/json" }; @@ -149,8 +162,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/jobs/users-exports", @@ -160,7 +175,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{\"connection_id\": \"{yourConnectionId}\", \"format\": \"csv\", \"limit\": 5, \"fields\": [{\"name\": \"email\"}, { \"name\": \"identities[0].connection\", \"export_as\": \"provider\" }]}", + CURLOPT_POSTFIELDS => "{"connection_id": "{yourConnectionId}", "format": "csv", "limit": 5, "fields": [{"name": "email"}, { "name": "identities[0].connection", "export_as": "provider" }]}", CURLOPT_HTTPHEADER => [ "authorization: Bearer {yourMgmtAPIAccessToken}", "content-type: application/json" @@ -176,12 +191,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"connection_id\": \"{yourConnectionId}\", \"format\": \"csv\", \"limit\": 5, \"fields\": [{\"name\": \"email\"}, { \"name\": \"identities[0].connection\", \"export_as\": \"provider\" }]}" +payload = "{"connection_id": "{yourConnectionId}", "format": "csv", "limit": 5, "fields": [{"name": "email"}, { "name": "identities[0].connection", "export_as": "provider" }]}" headers = { 'authorization': "Bearer {yourMgmtAPIAccessToken}", @@ -193,8 +210,10 @@ conn.request("POST", "/{yourDomain}/api/v2/jobs/users-exports", payload, headers res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -207,11 +226,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["authorization"] = 'Bearer {yourMgmtAPIAccessToken}' request["content-type"] = 'application/json' -request.body = "{\"connection_id\": \"{yourConnectionId}\", \"format\": \"csv\", \"limit\": 5, \"fields\": [{\"name\": \"email\"}, { \"name\": \"identities[0].connection\", \"export_as\": \"provider\" }]}" +request.body = "{"connection_id": "{yourConnectionId}", "format": "csv", "limit": 5, "fields": [{"name": "email"}, { "name": "identities[0].connection", "export_as": "provider" }]}" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "authorization": "Bearer {yourMgmtAPIAccessToken}", @@ -249,20 +270,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + La réponse devrait ressembler à ceci : @@ -324,18 +334,24 @@ Par exemple, pour des métadonnées structurées comme ceci. La demande d’exportation (pour les trois champs) ressemblerait à ceci. -export const codeExample11 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/api/v2/jobs/users-exports' \ --header 'authorization: Bearer {yourMgmtAPIAccessToken}' \ --header 'content-type: application/json' \ - --data '{"connection_id": "{yourConnectionId}", "format": "csv", "limit": 5, "fields": [{"name": "email"}, {"name": "user_metadata.consent.given"}, {"name": "user_metadata.consent.date"}, {"name": "user_metadata.consent.text_details"}]}'`; -export const codeExample12 = `var client = new RestClient("https://{yourDomain}/api/v2/jobs/users-exports"); + --data '{"connection_id": "{yourConnectionId}", "format": "csv", "limit": 5, "fields": [{"name": "email"}, {"name": "user_metadata.consent.given"}, {"name": "user_metadata.consent.date"}, {"name": "user_metadata.consent.text_details"}]}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/jobs/users-exports"); var request = new RestRequest(Method.POST); request.AddHeader("authorization", "Bearer {yourMgmtAPIAccessToken}"); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\"connection_id\": \"{yourConnectionId}\", \"format\": \"csv\", \"limit\": 5, \"fields\": [{\"name\": \"email\"}, {\"name\": \"user_metadata.consent.given\"}, {\"name\": \"user_metadata.consent.date\"}, {\"name\": \"user_metadata.consent.text_details\"}]}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample13 = `package main +request.AddParameter("application/json", "{"connection_id": "{yourConnectionId}", "format": "csv", "limit": 5, "fields": [{"name": "email"}, {"name": "user_metadata.consent.given"}, {"name": "user_metadata.consent.date"}, {"name": "user_metadata.consent.text_details"}]}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -348,7 +364,7 @@ func main() { url := "https://{yourDomain}/api/v2/jobs/users-exports" - payload := strings.NewReader("{\"connection_id\": \"{yourConnectionId}\", \"format\": \"csv\", \"limit\": 5, \"fields\": [{\"name\": \"email\"}, {\"name\": \"user_metadata.consent.given\"}, {\"name\": \"user_metadata.consent.date\"}, {\"name\": \"user_metadata.consent.text_details\"}]}") + payload := strings.NewReader("{"connection_id": "{yourConnectionId}", "format": "csv", "limit": 5, "fields": [{"name": "email"}, {"name": "user_metadata.consent.given"}, {"name": "user_metadata.consent.date"}, {"name": "user_metadata.consent.text_details"}]}") req, _ := http.NewRequest("POST", url, payload) @@ -363,13 +379,17 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample14 = `HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/jobs/users-exports") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/jobs/users-exports") .header("authorization", "Bearer {yourMgmtAPIAccessToken}") .header("content-type", "application/json") - .body("{\"connection_id\": \"{yourConnectionId}\", \"format\": \"csv\", \"limit\": 5, \"fields\": [{\"name\": \"email\"}, {\"name\": \"user_metadata.consent.given\"}, {\"name\": \"user_metadata.consent.date\"}, {\"name\": \"user_metadata.consent.text_details\"}]}") - .asString();`; -export const codeExample15 = `var axios = require("axios").default; + .body("{"connection_id": "{yourConnectionId}", "format": "csv", "limit": 5, "fields": [{"name": "email"}, {"name": "user_metadata.consent.given"}, {"name": "user_metadata.consent.date"}, {"name": "user_metadata.consent.text_details"}]}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -395,8 +415,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample16 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer {yourMgmtAPIAccessToken}", @"content-type": @"application/json" }; @@ -424,8 +446,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/jobs/users-exports", @@ -435,7 +459,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{\"connection_id\": \"{yourConnectionId}\", \"format\": \"csv\", \"limit\": 5, \"fields\": [{\"name\": \"email\"}, {\"name\": \"user_metadata.consent.given\"}, {\"name\": \"user_metadata.consent.date\"}, {\"name\": \"user_metadata.consent.text_details\"}]}", + CURLOPT_POSTFIELDS => "{"connection_id": "{yourConnectionId}", "format": "csv", "limit": 5, "fields": [{"name": "email"}, {"name": "user_metadata.consent.given"}, {"name": "user_metadata.consent.date"}, {"name": "user_metadata.consent.text_details"}]}", CURLOPT_HTTPHEADER => [ "authorization: Bearer {yourMgmtAPIAccessToken}", "content-type: application/json" @@ -451,12 +475,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"connection_id\": \"{yourConnectionId}\", \"format\": \"csv\", \"limit\": 5, \"fields\": [{\"name\": \"email\"}, {\"name\": \"user_metadata.consent.given\"}, {\"name\": \"user_metadata.consent.date\"}, {\"name\": \"user_metadata.consent.text_details\"}]}" +payload = "{"connection_id": "{yourConnectionId}", "format": "csv", "limit": 5, "fields": [{"name": "email"}, {"name": "user_metadata.consent.given"}, {"name": "user_metadata.consent.date"}, {"name": "user_metadata.consent.text_details"}]}" headers = { 'authorization': "Bearer {yourMgmtAPIAccessToken}", @@ -468,8 +494,10 @@ conn.request("POST", "/{yourDomain}/api/v2/jobs/users-exports", payload, headers res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -482,11 +510,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["authorization"] = 'Bearer {yourMgmtAPIAccessToken}' request["content-type"] = 'application/json' -request.body = "{\"connection_id\": \"{yourConnectionId}\", \"format\": \"csv\", \"limit\": 5, \"fields\": [{\"name\": \"email\"}, {\"name\": \"user_metadata.consent.given\"}, {\"name\": \"user_metadata.consent.date\"}, {\"name\": \"user_metadata.consent.text_details\"}]}" +request.body = "{"connection_id": "{yourConnectionId}", "format": "csv", "limit": 5, "fields": [{"name": "email"}, {"name": "user_metadata.consent.given"}, {"name": "user_metadata.consent.date"}, {"name": "user_metadata.consent.text_details"}]}" response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "authorization": "Bearer {yourMgmtAPIAccessToken}", @@ -518,20 +548,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + @@ -555,18 +574,24 @@ Avant de pouvoir importer des utilisateurs en utilisant un export généré par Dans ce cas, pour le même exemple que nous avons utilisé précédemment, la requête ressemblerait à ceci : -export const codeExample21 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/api/v2/jobs/users-exports' \ --header 'authorization: Bearer {yourMgmtAPIAccessToken}' \ --header 'content-type: application/json' \ - --data '{"connection_id": "{yourConnectionId}", "format": "json", "limit": 5, "fields": [{"name": "email"}, {"name": "user_metadata.consent"}]}'`; -export const codeExample22 = `var client = new RestClient("https://{yourDomain}/api/v2/jobs/users-exports"); + --data '{"connection_id": "{yourConnectionId}", "format": "json", "limit": 5, "fields": [{"name": "email"}, {"name": "user_metadata.consent"}]}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/jobs/users-exports"); var request = new RestRequest(Method.POST); request.AddHeader("authorization", "Bearer {yourMgmtAPIAccessToken}"); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\"connection_id\": \"{yourConnectionId}\", \"format\": \"json\", \"limit\": 5, \"fields\": [{\"name\": \"email\"}, {\"name\": \"user_metadata.consent\"}]}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample23 = `package main +request.AddParameter("application/json", "{"connection_id": "{yourConnectionId}", "format": "json", "limit": 5, "fields": [{"name": "email"}, {"name": "user_metadata.consent"}]}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -579,7 +604,7 @@ func main() { url := "https://{yourDomain}/api/v2/jobs/users-exports" - payload := strings.NewReader("{\"connection_id\": \"{yourConnectionId}\", \"format\": \"json\", \"limit\": 5, \"fields\": [{\"name\": \"email\"}, {\"name\": \"user_metadata.consent\"}]}") + payload := strings.NewReader("{"connection_id": "{yourConnectionId}", "format": "json", "limit": 5, "fields": [{"name": "email"}, {"name": "user_metadata.consent"}]}") req, _ := http.NewRequest("POST", url, payload) @@ -594,13 +619,17 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample24 = `HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/jobs/users-exports") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/jobs/users-exports") .header("authorization", "Bearer {yourMgmtAPIAccessToken}") .header("content-type", "application/json") - .body("{\"connection_id\": \"{yourConnectionId}\", \"format\": \"json\", \"limit\": 5, \"fields\": [{\"name\": \"email\"}, {\"name\": \"user_metadata.consent\"}]}") - .asString();`; -export const codeExample25 = `var axios = require("axios").default; + .body("{"connection_id": "{yourConnectionId}", "format": "json", "limit": 5, "fields": [{"name": "email"}, {"name": "user_metadata.consent"}]}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -621,8 +650,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample26 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer {yourMgmtAPIAccessToken}", @"content-type": @"application/json" }; @@ -650,8 +681,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample27 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/jobs/users-exports", @@ -661,7 +694,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{\"connection_id\": \"{yourConnectionId}\", \"format\": \"json\", \"limit\": 5, \"fields\": [{\"name\": \"email\"}, {\"name\": \"user_metadata.consent\"}]}", + CURLOPT_POSTFIELDS => "{"connection_id": "{yourConnectionId}", "format": "json", "limit": 5, "fields": [{"name": "email"}, {"name": "user_metadata.consent"}]}", CURLOPT_HTTPHEADER => [ "authorization: Bearer {yourMgmtAPIAccessToken}", "content-type: application/json" @@ -677,12 +710,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample28 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"connection_id\": \"{yourConnectionId}\", \"format\": \"json\", \"limit\": 5, \"fields\": [{\"name\": \"email\"}, {\"name\": \"user_metadata.consent\"}]}" +payload = "{"connection_id": "{yourConnectionId}", "format": "json", "limit": 5, "fields": [{"name": "email"}, {"name": "user_metadata.consent"}]}" headers = { 'authorization': "Bearer {yourMgmtAPIAccessToken}", @@ -694,8 +729,10 @@ conn.request("POST", "/{yourDomain}/api/v2/jobs/users-exports", payload, headers res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample29 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -708,11 +745,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["authorization"] = 'Bearer {yourMgmtAPIAccessToken}' request["content-type"] = 'application/json' -request.body = "{\"connection_id\": \"{yourConnectionId}\", \"format\": \"json\", \"limit\": 5, \"fields\": [{\"name\": \"email\"}, {\"name\": \"user_metadata.consent\"}]}" +request.body = "{"connection_id": "{yourConnectionId}", "format": "json", "limit": 5, "fields": [{"name": "email"}, {"name": "user_metadata.consent"}]}" response = http.request(request) -puts response.read_body`; -export const codeExample30 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "authorization": "Bearer {yourMgmtAPIAccessToken}", @@ -744,20 +783,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ## Vérifier le statut de l’exportation @@ -767,14 +795,20 @@ Indiquez l’ID de la tâche (que vous avez reçu dans la réponse lors de la cr Permissions requises : `create:users`, `read:users`, `create:passwords_checking_job` -export const codeExample31 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/jobs/%7ByourJobId%7D' \ - --header 'authorization: Bearer {yourMgmtAPIAccessToken}'`; -export const codeExample32 = `var client = new RestClient("https://{yourDomain}/api/v2/jobs/%7ByourJobId%7D"); + --header 'authorization: Bearer {yourMgmtAPIAccessToken}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/jobs/%7ByourJobId%7D"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer {yourMgmtAPIAccessToken}"); -IRestResponse response = client.Execute(request);`; -export const codeExample33 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -798,11 +832,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample34 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/jobs/%7ByourJobId%7D") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/jobs/%7ByourJobId%7D") .header("authorization", "Bearer {yourMgmtAPIAccessToken}") - .asString();`; -export const codeExample35 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -814,8 +852,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample36 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer {yourMgmtAPIAccessToken}" }; @@ -835,8 +875,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample37 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/jobs/%7ByourJobId%7D", @@ -860,8 +902,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample38 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -872,8 +916,10 @@ conn.request("GET", "/{yourDomain}/api/v2/jobs/%7ByourJobId%7D", headers=headers res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample39 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -887,8 +933,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer {yourMgmtAPIAccessToken}' response = http.request(request) -puts response.read_body`; -export const codeExample40 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer {yourMgmtAPIAccessToken}"] @@ -908,20 +956,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + Vous devriez obtenir une réponse similaire à : diff --git a/main/docs/fr-ca/manage-users/user-migration/bulk-user-imports.mdx b/main/docs/fr-ca/manage-users/user-migration/bulk-user-imports.mdx index b9afba194..55929f92b 100644 --- a/main/docs/fr-ca/manage-users/user-migration/bulk-user-imports.mdx +++ b/main/docs/fr-ca/manage-users/user-migration/bulk-user-imports.mdx @@ -10,6 +10,7 @@ permalink: "bulk-user-imports" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Vous pouvez importer les données des utilisateurs en lot dans Auth0 à l’aide du point de terminaison [Création d’une tâche d’importation d’utilisateurs](/docs/fr-ca/api/management/v2#!/Jobs/post_users_imports). Les importations en lots sont utiles pour migrer les utilisateurs d’une base de données ou d’un service existant vers Auth0. @@ -54,19 +55,39 @@ La limite de la taille des fichiers pour une importation en bloc est de 500 Ko. Pour lancer un travail d’importation d’utilisateurs en lots, faites une requête `POST` au point de terminaison [Créer une tâche d’importation d’utilisateurs](https://auth0.com/docs/api/management/v2#!/Jobs/post_users_imports). Veillez à remplacer les valeurs fictives `MGMT_API_ACCESS_TOKEN`, `USERS_IMPORT_FILE.json`, `CONNECTION_ID` et `EXTERNAL_ID` par votre jeton d’accès de Management API, le fichier JSON des utilisateurs, le [connection ID](/docs/fr-ca/authenticate/identity-providers/locate-the-connection-id) à la base de données et l’ID externe, respectivement. -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/api/v2/jobs/users-imports' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --form users=@USERS_IMPORT_FILE.json \ --form connection_id=CONNECTION_ID \ - --form external_id=EXTERNAL_ID`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/jobs/users-imports"); + --form external_id=EXTERNAL_ID +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/jobs/users-imports"); var request = new RestRequest(Method.POST); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("content-type", "multipart/form-data; boundary=---011000010111000001101001"); -request.AddParameter("multipart/form-data; boundary=---011000010111000001101001", "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"users\"; filename=\"USERS_IMPORT_FILE.json\"\r\nContent-Type: text/json\r\n\r\n\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"connection_id\"\r\n\r\nCONNECTION_ID\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"external_id\"\r\n\r\nEXTERNAL_ID\r\n-----011000010111000001101001--\r\n", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("multipart/form-data; boundary=---011000010111000001101001", "-----011000010111000001101001\r +Content-Disposition: form-data; name="users"; filename="USERS_IMPORT_FILE.json"\r +Content-Type: text/json\r +\r +\r +-----011000010111000001101001\r +Content-Disposition: form-data; name="connection_id"\r +\r +CONNECTION_ID\r +-----011000010111000001101001\r +Content-Disposition: form-data; name="external_id"\r +\r +EXTERNAL_ID\r +-----011000010111000001101001--\r +", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -79,7 +100,21 @@ func main() { url := "https://{yourDomain}/api/v2/jobs/users-imports" - payload := strings.NewReader("-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"users\"; filename=\"USERS_IMPORT_FILE.json\"\r\nContent-Type: text/json\r\n\r\n\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"connection_id\"\r\n\r\nCONNECTION_ID\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"external_id\"\r\n\r\nEXTERNAL_ID\r\n-----011000010111000001101001--\r\n") + payload := strings.NewReader("-----011000010111000001101001\r +Content-Disposition: form-data; name="users"; filename="USERS_IMPORT_FILE.json"\r +Content-Type: text/json\r +\r +\r +-----011000010111000001101001\r +Content-Disposition: form-data; name="connection_id"\r +\r +CONNECTION_ID\r +-----011000010111000001101001\r +Content-Disposition: form-data; name="external_id"\r +\r +EXTERNAL_ID\r +-----011000010111000001101001--\r +") req, _ := http.NewRequest("POST", url, payload) @@ -94,13 +129,31 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/jobs/users-imports") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/jobs/users-imports") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("content-type", "multipart/form-data; boundary=---011000010111000001101001") - .body("-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"users\"; filename=\"USERS_IMPORT_FILE.json\"\r\nContent-Type: text/json\r\n\r\n\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"connection_id\"\r\n\r\nCONNECTION_ID\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"external_id\"\r\n\r\nEXTERNAL_ID\r\n-----011000010111000001101001--\r\n") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("-----011000010111000001101001\r +Content-Disposition: form-data; name="users"; filename="USERS_IMPORT_FILE.json"\r +Content-Type: text/json\r +\r +\r +-----011000010111000001101001\r +Content-Disposition: form-data; name="connection_id"\r +\r +CONNECTION_ID\r +-----011000010111000001101001\r +Content-Disposition: form-data; name="external_id"\r +\r +EXTERNAL_ID\r +-----011000010111000001101001--\r +") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -109,15 +162,31 @@ var options = { authorization: 'Bearer MGMT_API_ACCESS_TOKEN', 'content-type': 'multipart/form-data; boundary=---011000010111000001101001' }, - data: '-----011000010111000001101001\r\nContent-Disposition: form-data; name="users"; filename="USERS_IMPORT_FILE.json"\r\nContent-Type: text/json\r\n\r\n\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name="connection_id"\r\n\r\nCONNECTION_ID\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name="external_id"\r\n\r\nEXTERNAL_ID\r\n-----011000010111000001101001--\r\n' + data: '-----011000010111000001101001\r +Content-Disposition: form-data; name="users"; filename="USERS_IMPORT_FILE.json"\r +Content-Type: text/json\r +\r +\r +-----011000010111000001101001\r +Content-Disposition: form-data; name="connection_id"\r +\r +CONNECTION_ID\r +-----011000010111000001101001\r +Content-Disposition: form-data; name="external_id"\r +\r +EXTERNAL_ID\r +-----011000010111000001101001--\r +' }; axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @"content-type": @"multipart/form-data; boundary=---011000010111000001101001" }; @@ -129,20 +198,28 @@ NSString *boundary = @"---011000010111000001101001"; NSError *error; NSMutableString *body = [NSMutableString string]; for (NSDictionary *param in parameters) { - [body appendFormat:@"--%@\r\n", boundary]; + [body appendFormat:@"--%@\r +", boundary]; if (param[@"fileName"]) { - [body appendFormat:@"Content-Disposition:form-data; name=\"%@\"; filename=\"%@\"\r\n", param[@"name"], param[@"fileName"]]; - [body appendFormat:@"Content-Type: %@\r\n\r\n", param[@"contentType"]]; + [body appendFormat:@"Content-Disposition:form-data; name="%@"; filename="%@"\r +", param[@"name"], param[@"fileName"]]; + [body appendFormat:@"Content-Type: %@\r +\r +", param[@"contentType"]]; [body appendFormat:@"%@", [NSString stringWithContentsOfFile:param[@"fileName"] encoding:NSUTF8StringEncoding error:&error]]; if (error) { NSLog(@"%@", error); } } else { - [body appendFormat:@"Content-Disposition:form-data; name=\"%@\"\r\n\r\n", param[@"name"]]; + [body appendFormat:@"Content-Disposition:form-data; name="%@"\r +\r +", param[@"name"]]; [body appendFormat:@"%@", param[@"value"]]; } } -[body appendFormat:@"\r\n--%@--\r\n", boundary]; +[body appendFormat:@"\r +--%@--\r +", boundary]; NSData *postData = [body dataUsingEncoding:NSUTF8StringEncoding]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://{yourDomain}/api/v2/jobs/users-imports"] @@ -162,8 +239,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/jobs/users-imports", @@ -173,7 +252,21 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"users\"; filename=\"USERS_IMPORT_FILE.json\"\r\nContent-Type: text/json\r\n\r\n\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"connection_id\"\r\n\r\nCONNECTION_ID\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"external_id\"\r\n\r\nEXTERNAL_ID\r\n-----011000010111000001101001--\r\n", + CURLOPT_POSTFIELDS => "-----011000010111000001101001\r +Content-Disposition: form-data; name="users"; filename="USERS_IMPORT_FILE.json"\r +Content-Type: text/json\r +\r +\r +-----011000010111000001101001\r +Content-Disposition: form-data; name="connection_id"\r +\r +CONNECTION_ID\r +-----011000010111000001101001\r +Content-Disposition: form-data; name="external_id"\r +\r +EXTERNAL_ID\r +-----011000010111000001101001--\r +", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "content-type: multipart/form-data; boundary=---011000010111000001101001" @@ -189,12 +282,28 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"users\"; filename=\"USERS_IMPORT_FILE.json\"\r\nContent-Type: text/json\r\n\r\n\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"connection_id\"\r\n\r\nCONNECTION_ID\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"external_id\"\r\n\r\nEXTERNAL_ID\r\n-----011000010111000001101001--\r\n" +payload = "-----011000010111000001101001\r +Content-Disposition: form-data; name="users"; filename="USERS_IMPORT_FILE.json"\r +Content-Type: text/json\r +\r +\r +-----011000010111000001101001\r +Content-Disposition: form-data; name="connection_id"\r +\r +CONNECTION_ID\r +-----011000010111000001101001\r +Content-Disposition: form-data; name="external_id"\r +\r +EXTERNAL_ID\r +-----011000010111000001101001--\r +" headers = { 'authorization': "Bearer MGMT_API_ACCESS_TOKEN", @@ -206,8 +315,10 @@ conn.request("POST", "/{yourDomain}/api/v2/jobs/users-imports", payload, headers res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -220,11 +331,27 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["content-type"] = 'multipart/form-data; boundary=---011000010111000001101001' -request.body = "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"users\"; filename=\"USERS_IMPORT_FILE.json\"\r\nContent-Type: text/json\r\n\r\n\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"connection_id\"\r\n\r\nCONNECTION_ID\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"external_id\"\r\n\r\nEXTERNAL_ID\r\n-----011000010111000001101001--\r\n" +request.body = "-----011000010111000001101001\r +Content-Disposition: form-data; name="users"; filename="USERS_IMPORT_FILE.json"\r +Content-Type: text/json\r +\r +\r +-----011000010111000001101001\r +Content-Disposition: form-data; name="connection_id"\r +\r +CONNECTION_ID\r +-----011000010111000001101001\r +Content-Disposition: form-data; name="external_id"\r +\r +EXTERNAL_ID\r +-----011000010111000001101001--\r +" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "authorization": "Bearer MGMT_API_ACCESS_TOKEN", @@ -252,19 +379,25 @@ var body = "" var error: NSError? = nil for param in parameters { let paramName = param["name"]! - body += "--\(boundary)\r\n" - body += "Content-Disposition:form-data; name=\"\(paramName)\"" + body += "--\(boundary)\r +" + body += "Content-Disposition:form-data; name="\(paramName)"" if let filename = param["fileName"] { let contentType = param["content-type"]! let fileContent = String(contentsOfFile: filename, encoding: String.Encoding.utf8) if (error != nil) { print(error) } - body += "; filename=\"\(filename)\"\r\n" - body += "Content-Type: \(contentType)\r\n\r\n" + body += "; filename="\(filename)"\r +" + body += "Content-Type: \(contentType)\r +\r +" body += fileContent } else if let paramValue = param["value"] { - body += "\r\n\r\n\(paramValue)" + body += "\r +\r +\(paramValue)" } } @@ -285,20 +418,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
@@ -365,16 +487,22 @@ Le point de terminaison [Créer une tâche d’importation d’utilisateurs](htt Pour vérifier l’état d’une tâche, faites une requête `GET` au point de terminaison [Obtenir une tâche](https://auth0.com/docs/api/management/v2#!/Jobs/get_jobs_by_id). Assurez-vous de remplacer les valeurs fictives `MGMT_API_ACCESS_TOKEN` et `JOB_ID` avec votre jeton d’accès à Management API et l’ID de la tâche d’importation d’utilisateurs. -export const codeExample11 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/jobs/JOB_ID' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ - --header 'content-type: application/json'`; -export const codeExample12 = `var client = new RestClient("https://{yourDomain}/api/v2/jobs/JOB_ID"); + --header 'content-type: application/json' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/jobs/JOB_ID"); var request = new RestRequest(Method.GET); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); -IRestResponse response = client.Execute(request);`; -export const codeExample13 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -399,12 +527,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample14 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/jobs/JOB_ID") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/jobs/JOB_ID") .header("content-type", "application/json") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") - .asString();`; -export const codeExample15 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -419,8 +551,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample16 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN" }; @@ -441,8 +575,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/jobs/JOB_ID", @@ -467,8 +603,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -482,8 +620,10 @@ conn.request("GET", "/{yourDomain}/api/v2/jobs/JOB_ID", headers=headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -498,8 +638,10 @@ request["content-type"] = 'application/json' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -522,20 +664,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + Vous recevrez une réponse semblable à l’une des suivantes, en fonction de l’état de la tâche d’importation d’utilisateurs : @@ -606,16 +737,22 @@ Toutes les données relatives au travail sont automatiquement supprimées au bou Si des erreurs se sont produites dans la tâche d’importation d’utilisateurs, vous pouvez obtenir les détails de l’erreur en effectuant une requête `GET` au point de terminaison [Obtenir le détail des erreurs de la tâche](/docs/fr-ca/api/management/v2#!/Jobs/get_errors). Assurez-vous de remplacer les valeurs fictives `MGMT_API_ACCESS_TOKEN` et `JOB_ID` avec votre jeton d’accès à Management API et l’ID de la tâche d’importation d’utilisateurs. -export const codeExample21 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/jobs/JOB_ID/errors' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ - --header 'content-type: application/json'`; -export const codeExample22 = `var client = new RestClient("https://{yourDomain}/api/v2/jobs/JOB_ID/errors"); + --header 'content-type: application/json' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/jobs/JOB_ID/errors"); var request = new RestRequest(Method.GET); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); -IRestResponse response = client.Execute(request);`; -export const codeExample23 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -640,12 +777,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample24 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/jobs/JOB_ID/errors") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/jobs/JOB_ID/errors") .header("content-type", "application/json") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") - .asString();`; -export const codeExample25 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -660,8 +801,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample26 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN" }; @@ -682,8 +825,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample27 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/jobs/JOB_ID/errors", @@ -708,8 +853,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample28 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -723,8 +870,10 @@ conn.request("GET", "/{yourDomain}/api/v2/jobs/JOB_ID/errors", headers=headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample29 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -739,8 +888,10 @@ request["content-type"] = 'application/json' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' response = http.request(request) -puts response.read_body`; -export const codeExample30 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -763,20 +914,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + Vous recevrez une réponse semblable à celle qui suit si la requête réussit : Les champs à caractère confidentiel, tels que `hash.value` seront masqués dans la réponse. diff --git a/main/docs/fr-ca/manage-users/user-search/retrieve-users-with-get-users-by-email-endpoint.mdx b/main/docs/fr-ca/manage-users/user-search/retrieve-users-with-get-users-by-email-endpoint.mdx index 0ac245c2b..b340b8497 100644 --- a/main/docs/fr-ca/manage-users/user-search/retrieve-users-with-get-users-by-email-endpoint.mdx +++ b/main/docs/fr-ca/manage-users/user-search/retrieve-users-with-get-users-by-email-endpoint.mdx @@ -10,6 +10,7 @@ permalink: "retrieve-users-with-get-users-by-email-endpoint" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Le point de terminaison [`GET /api/v2/users-by-email`](/docs/fr-ca/api/management/v2#!/Users_By_Email/get_users_by_email) vous permet de chercher des utilisateurs en utilisant leur adresse courriel. La recherche cible une correspondance exacte pour l’adresse courriel saisie et est sensible à la casse. @@ -24,14 +25,20 @@ La requête doit inclure [un jeton d’accès à Management API](/docs/fr-ca/sec Permissions requises : `read:users` -export const codeExample1 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/users-by-email?email=%7BuserEmailAddress%7D' \ - --header 'authorization: Bearer {yourMgmtApiAccessToken}'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/users-by-email?email=%7BuserEmailAddress%7D"); + --header 'authorization: Bearer {yourMgmtApiAccessToken}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users-by-email?email=%7BuserEmailAddress%7D"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer {yourMgmtApiAccessToken}"); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -55,11 +62,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/users-by-email?email=%7BuserEmailAddress%7D") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/users-by-email?email=%7BuserEmailAddress%7D") .header("authorization", "Bearer {yourMgmtApiAccessToken}") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -72,8 +83,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer {yourMgmtApiAccessToken}" }; @@ -93,8 +106,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users-by-email?email=%7BuserEmailAddress%7D", @@ -118,8 +133,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -130,8 +147,10 @@ conn.request("GET", "/{yourDomain}/api/v2/users-by-email?email=%7BuserEmailAddre res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -145,8 +164,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer {yourMgmtApiAccessToken}' response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer {yourMgmtApiAccessToken}"] @@ -166,20 +187,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ```json lines [ diff --git a/main/docs/fr-ca/manage-users/user-search/retrieve-users-with-get-users-by-id-endpoint.mdx b/main/docs/fr-ca/manage-users/user-search/retrieve-users-with-get-users-by-id-endpoint.mdx index 5ddff379a..a12864972 100644 --- a/main/docs/fr-ca/manage-users/user-search/retrieve-users-with-get-users-by-id-endpoint.mdx +++ b/main/docs/fr-ca/manage-users/user-search/retrieve-users-with-get-users-by-id-endpoint.mdx @@ -10,6 +10,7 @@ permalink: "retrieve-users-with-get-users-by-id-endpoint" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Le [point de terminaison `GET /api/v2/users/{id}`](https://auth0.com/docs/api/management/v2#!/Users/get_users_by_id) vous permet de chercher des utilisateurs en utilisant leur ID utilisateur Auth0. @@ -26,14 +27,20 @@ La requête doit inclure [un jeton d’accès à Management API](/docs/fr-ca/sec Permissions requises : `read:users` -export const codeExample1 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/users/%7BuserId%7D' \ - --header 'authorization: Bearer {yourMgmtApiAccessToken}'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/users/%7BuserId%7D"); + --header 'authorization: Bearer {yourMgmtApiAccessToken}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users/%7BuserId%7D"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer {yourMgmtApiAccessToken}"); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -57,11 +64,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/users/%7BuserId%7D") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/users/%7BuserId%7D") .header("authorization", "Bearer {yourMgmtApiAccessToken}") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -73,8 +84,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer {yourMgmtApiAccessToken}" }; @@ -94,8 +107,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users/%7BuserId%7D", @@ -119,8 +134,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -131,8 +148,10 @@ conn.request("GET", "/{yourDomain}/api/v2/users/%7BuserId%7D", headers=headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -146,8 +165,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer {yourMgmtApiAccessToken}' response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer {yourMgmtApiAccessToken}"] @@ -167,20 +188,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ```json lines { diff --git a/main/docs/fr-ca/manage-users/user-search/retrieve-users-with-get-users-endpoint.mdx b/main/docs/fr-ca/manage-users/user-search/retrieve-users-with-get-users-endpoint.mdx index eab9cf4b5..ea22d5d8c 100644 --- a/main/docs/fr-ca/manage-users/user-search/retrieve-users-with-get-users-endpoint.mdx +++ b/main/docs/fr-ca/manage-users/user-search/retrieve-users-with-get-users-endpoint.mdx @@ -10,6 +10,7 @@ permalink: "retrieve-users-with-get-users-endpoint" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Le point de terminaison [`GET /api/v2/users`](/docs/fr-ca/api/management/v2#!/Users/get_users) vous permet de récupérer une liste d’utilisateurs. Ce point de terminaison permet ce qui suit : @@ -25,14 +26,20 @@ Pour rechercher des utilisateurs, faites une requête `GET` au point de terminai Par exemple, pour rechercher un utilisateur dont le courriel est exactement `jane@exampleco.com`, utilisez `q=email:"jane@exampleco.com »` : -export const codeExample1 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/users?q=email%3A%22jane%40exampleco.com%22&search_engine=v3' \ - --header 'authorization: Bearer {yourMgmtApiAccessToken}'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/users?q=email%3A%22jane%40exampleco.com%22&search_engine=v3"); + --header 'authorization: Bearer {yourMgmtApiAccessToken}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users?q=email%3A%22jane%40exampleco.com%22&search_engine=v3"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer {yourMgmtApiAccessToken}"); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -56,11 +63,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/users?q=email%3A%22jane%40exampleco.com%22&search_engine=v3") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/users?q=email%3A%22jane%40exampleco.com%22&search_engine=v3") .header("authorization", "Bearer {yourMgmtApiAccessToken}") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -73,8 +84,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer {yourMgmtApiAccessToken}" }; @@ -94,8 +107,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users?q=email%3A%22jane%40exampleco.com%22&search_engine=v3", @@ -119,8 +134,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -131,8 +148,10 @@ conn.request("GET", "/{yourDomain}/api/v2/users?q=email%3A%22jane%40exampleco.co res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -146,8 +165,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer {yourMgmtApiAccessToken}' response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer {yourMgmtApiAccessToken}"] @@ -167,20 +188,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + Si la recherche aboutit, vous recevrez une réponse semblable à celle-ci : diff --git a/main/docs/fr-ca/manage-users/user-search/sort-search-results.mdx b/main/docs/fr-ca/manage-users/user-search/sort-search-results.mdx index 5746e0214..90cf184db 100644 --- a/main/docs/fr-ca/manage-users/user-search/sort-search-results.mdx +++ b/main/docs/fr-ca/manage-users/user-search/sort-search-results.mdx @@ -10,6 +10,7 @@ permalink: "sort-search-results" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Pour trier les résultats de recherche, passez une valeur `field:order` au paramètre `sort` lorsque vous effectuez votre requête. Le `field` est le nom du champ de tri, alors que order peut être défini sur `1` pour un ordre croissant et `-1` pour un ordre décroissant. @@ -17,14 +18,20 @@ Le tri par `app_metadata` ou `user_metadata` n’est pas pris en charge. Par exemple, pour trier les utilisateurs par ordre croissant en fonction du champ `created_at`, vous pouvez indiquer la valeur `created_at:1` pour le paramètre `sort`: -export const codeExample1 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/users?q=logins_count%3A%5B100%20TO%20200%5D&sort=created_at%3A1&search_engine=v3' \ - --header 'authorization: Bearer {yourMgmtApiAccessToken}'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/users?q=logins_count%3A%5B100%20TO%20200%5D&sort=created_at%3A1&search_engine=v3"); + --header 'authorization: Bearer {yourMgmtApiAccessToken}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users?q=logins_count%3A%5B100%20TO%20200%5D&sort=created_at%3A1&search_engine=v3"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer {yourMgmtApiAccessToken}"); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -48,11 +55,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/users?q=logins_count%3A%5B100%20TO%20200%5D&sort=created_at%3A1&search_engine=v3") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/users?q=logins_count%3A%5B100%20TO%20200%5D&sort=created_at%3A1&search_engine=v3") .header("authorization", "Bearer {yourMgmtApiAccessToken}") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -65,8 +76,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer {yourMgmtApiAccessToken}" }; @@ -86,8 +99,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users?q=logins_count%3A%5B100%20TO%20200%5D&sort=created_at%3A1&search_engine=v3", @@ -111,8 +126,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -123,8 +140,10 @@ conn.request("GET", "/{yourDomain}/api/v2/users?q=logins_count%3A%5B100%20TO%202 res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -138,8 +157,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer {yourMgmtApiAccessToken}' response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer {yourMgmtApiAccessToken}"] @@ -159,19 +180,8 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + Pour en savoir plus sur le paramètre `sort` et d’autres paramètres, consultez la documentation de [Management API Explorer](https://auth0.com/docs/api/management/v2#!/Users/get_users). \ No newline at end of file diff --git a/main/docs/fr-ca/manage-users/user-search/user-search-query-syntax.mdx b/main/docs/fr-ca/manage-users/user-search/user-search-query-syntax.mdx index c0e65a4e0..c5f76bd33 100644 --- a/main/docs/fr-ca/manage-users/user-search/user-search-query-syntax.mdx +++ b/main/docs/fr-ca/manage-users/user-search/user-search-query-syntax.mdx @@ -10,6 +10,7 @@ permalink: "user-search-query-syntax" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; @@ -112,14 +113,20 @@ Pour trouver des correspondances exactes, utilisez des guillemets doubles : `na Par exemple, pour trouver les utilisateurs portant le nom `jane smith`, utilisez `q=name:"jane smith"` : -export const codeExample1 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/users?q=name%3A%22jane%20smith%22&search_engine=v3' \ - --header 'authorization: Bearer {yourMgmtApiAccessToken}'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/users?q=name%3A%22jane%20smith%22&search_engine=v3"); + --header 'authorization: Bearer {yourMgmtApiAccessToken}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users?q=name%3A%22jane%20smith%22&search_engine=v3"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer {yourMgmtApiAccessToken}"); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -143,11 +150,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/users?q=name%3A%22jane%20smith%22&search_engine=v3") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/users?q=name%3A%22jane%20smith%22&search_engine=v3") .header("authorization", "Bearer {yourMgmtApiAccessToken}") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -160,8 +171,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer {yourMgmtApiAccessToken}" }; @@ -181,8 +194,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users?q=name%3A%22jane%20smith%22&search_engine=v3", @@ -206,8 +221,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -218,8 +235,10 @@ conn.request("GET", "/{yourDomain}/api/v2/users?q=name%3A%22jane%20smith%22&sear res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -233,8 +252,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer {yourMgmtApiAccessToken}' response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer {yourMgmtApiAccessToken}"] @@ -254,20 +275,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ## Recherche générique @@ -280,14 +290,20 @@ Les recherches par caractères de remplacement peuvent être effectuées sur les * `q=name:john*` renvoie tous les utilisateurs dont le nom commence par `john`. * Pour la correspondance des suffixes, les éléments littéraux doivent comporter trois caractères ou plus. Par exemple, `name:*usa` est autorisé, mais `name:*sa` ne l’est pas. -export const codeExample11 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/users?q=name%3Ajohn*&search_engine=v3' \ - --header 'authorization: Bearer {yourMgmtApiAccessToken}'`; -export const codeExample12 = `var client = new RestClient("https://{yourDomain}/api/v2/users?q=name%3Ajohn\*&search_engine=v3"); + --header 'authorization: Bearer {yourMgmtApiAccessToken}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users?q=name%3Ajohn\*&search_engine=v3"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer {yourMgmtApiAccessToken}"); -IRestResponse response = client.Execute(request);`; -export const codeExample13 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -311,11 +327,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample14 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/users?q=name%3Ajohn*&search_engine=v3") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/users?q=name%3Ajohn*&search_engine=v3") .header("authorization", "Bearer {yourMgmtApiAccessToken}") - .asString();`; -export const codeExample15 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -328,8 +348,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample16 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer {yourMgmtApiAccessToken}" }; @@ -349,8 +371,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users?q=name%3Ajohn*&search_engine=v3", @@ -374,8 +398,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -386,8 +412,10 @@ conn.request("GET", "/{yourDomain}/api/v2/users?q=name%3Ajohn*&search_engine=v3" res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -401,8 +429,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer {yourMgmtApiAccessToken}' response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer {yourMgmtApiAccessToken}"] @@ -422,20 +452,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ## Plages @@ -446,14 +465,20 @@ Vous pouvez utiliser des plages dans vos requêtes de recherche d’utilisateurs * Les crochets et les apostrophes courbes peuvent être combinés dans la même expression de plage : `logins_count:[100 TO 200}`. * Utilisez les plages en combinaison avec des caractères de remplacement. Par exemple, pour trouver tous les utilisateurs ayant plus de 100 connexions, utilisez `q=logins_count:{100 TO *]`. -export const codeExample21 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/users?q=logins_count%3A%7B100%20TO%20*%5D&search_engine=v3' \ - --header 'authorization: Bearer {yourMgmtApiAccessToken}'`; -export const codeExample22 = `var client = new RestClient("https://{yourDomain}/api/v2/users?q=logins_count%3A%7B100%20TO%20\*%5D&search_engine=v3"); + --header 'authorization: Bearer {yourMgmtApiAccessToken}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users?q=logins_count%3A%7B100%20TO%20\*%5D&search_engine=v3"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer {yourMgmtApiAccessToken}"); -IRestResponse response = client.Execute(request);`; -export const codeExample23 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -477,11 +502,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample24 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/users?q=logins_count%3A%7B100%20TO%20*%5D&search_engine=v3") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/users?q=logins_count%3A%7B100%20TO%20*%5D&search_engine=v3") .header("authorization", "Bearer {yourMgmtApiAccessToken}") - .asString();`; -export const codeExample25 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -494,8 +523,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample26 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer {yourMgmtApiAccessToken}" }; @@ -515,8 +546,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample27 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users?q=logins_count%3A%7B100%20TO%20*%5D&search_engine=v3", @@ -540,8 +573,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample28 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -552,8 +587,10 @@ conn.request("GET", "/{yourDomain}/api/v2/users?q=logins_count%3A%7B100%20TO%20* res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample29 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -567,8 +604,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer {yourMgmtApiAccessToken}' response = http.request(request) -puts response.read_body`; -export const codeExample30 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer {yourMgmtApiAccessToken}"] @@ -588,20 +627,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ## Exemples d’attributs de profil pouvant faire l’objet d’une recherche diff --git a/main/docs/fr-ca/manage-users/user-search/view-search-results-by-page.mdx b/main/docs/fr-ca/manage-users/user-search/view-search-results-by-page.mdx index cc1df706f..c47a14dc4 100644 --- a/main/docs/fr-ca/manage-users/user-search/view-search-results-by-page.mdx +++ b/main/docs/fr-ca/manage-users/user-search/view-search-results-by-page.mdx @@ -10,6 +10,7 @@ permalink: "view-search-results-by-page" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Pour paginer les résultats de la recherche de l’utilisateur, utilisez les paramètres `page`, `per_page` et `include_totals` dans votre demande. @@ -37,14 +38,20 @@ Pour paginer les résultats de la recherche de l’utilisateur, utilisez les par ## Exemple de demande -export const codeExample1 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/users?q=logins_count%3A%5B100%20TO%20200%5D&page=2&per_page=10&include_totals=true&search_engine=v3' \ - --header 'authorization: Bearer {yourMgmtApiAccessToken}'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/users?q=logins_count%3A%5B100%20TO%20200%5D&page=2&per_page=10&include_totals=true&search_engine=v3"); + --header 'authorization: Bearer {yourMgmtApiAccessToken}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users?q=logins_count%3A%5B100%20TO%20200%5D&page=2&per_page=10&include_totals=true&search_engine=v3"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer {yourMgmtApiAccessToken}"); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -68,11 +75,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/users?q=logins_count%3A%5B100%20TO%20200%5D&page=2&per_page=10&include_totals=true&search_engine=v3") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/users?q=logins_count%3A%5B100%20TO%20200%5D&page=2&per_page=10&include_totals=true&search_engine=v3") .header("authorization", "Bearer {yourMgmtApiAccessToken}") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -91,8 +102,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer {yourMgmtApiAccessToken}" }; @@ -112,8 +125,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users?q=logins_count%3A%5B100%20TO%20200%5D&page=2&per_page=10&include_totals=true&search_engine=v3", @@ -137,8 +152,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -149,8 +166,10 @@ conn.request("GET", "/{yourDomain}/api/v2/users?q=logins_count%3A%5B100%20TO%202 res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -164,8 +183,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer {yourMgmtApiAccessToken}' response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer {yourMgmtApiAccessToken}"] @@ -185,20 +206,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ## Exemple de réponse diff --git a/main/docs/fr-ca/quickstart/backend/aspnet-core-webapi/interactive.mdx b/main/docs/fr-ca/quickstart/backend/aspnet-core-webapi/interactive.mdx index 9933d0f79..fbe797c7c 100644 --- a/main/docs/fr-ca/quickstart/backend/aspnet-core-webapi/interactive.mdx +++ b/main/docs/fr-ca/quickstart/backend/aspnet-core-webapi/interactive.mdx @@ -1,492 +1,494 @@ ---- -title: "Ajouter une autorisation à votre application API ASP.NET Core Web" -permalink: "interactive" -'description': "Ce tutoriel explique comment ajouter une autorisation à une application API ASP.NET Core Web en utilisant le logiciel médiateur JWT standard." -'og:title': "Ajouter une autorisation à votre application API ASP.NET Core Web" -'og:description': "Ce tutoriel explique comment ajouter une autorisation à une application API ASP.NET Core Web en utilisant le logiciel médiateur JWT standard." -'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/asp.png" -'twitter:title': "Ajouter une autorisation à votre application API ASP.NET Core Web" -'twitter:description': "Ce tutoriel explique comment ajouter une autorisation à une application API ASP.NET Core Web en utilisant le logiciel médiateur JWT standard." -sidebarTitle: ASP.NET Core Web API ---- - -import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; -import { LoggedInForm } from "/snippets/Login.jsx"; -import Appsettings from "/snippets/quickstart/backend/aspnet-core-webapi/appsettings.json.mdx"; -import Program from "/snippets/quickstart/backend/aspnet-core-webapi/Program.cs.mdx"; -import Hasscopehandler from "/snippets/quickstart/backend/aspnet-core-webapi/HasScopeHandler.cs.mdx"; -import Hasscoperequirement from "/snippets/quickstart/backend/aspnet-core-webapi/HasScopeRequirement.cs.mdx"; -import Apicontroller from "/snippets/quickstart/backend/aspnet-core-webapi/ApiController.cs.mdx"; - -export const sections = [ - { id: "définir-les-autorisations", title: "Définir les autorisations" }, - { id: "installer-les-dépendances", title: "Installer les dépendances" }, - { id: "configurer-le-logiciel-médiateur", title: "Configurer le logiciel médiateur" }, - { id: "valider-les-permissions", title: "Valider les permissions" }, - { id: "protéger-les-points-de-terminaison-des-api", title: "Protéger les points de terminaison des API" }, - { id: "appeler-votre-api", title: "Appeler votre API" } -] - - - - Auth0 vous permet d’ajouter rapidement l’authentification et d’accéder aux informations relatives au profil de l’utilisateur dans presque tous les types d’applications. Ce guide explique comment intégrer Auth0 à n’importe quelle application API ASP.NET Web, nouvelle ou existante, à l’aide du package `Microsoft.AspNetCore.Authentication.JwtBearer` . - - Si vous n’avez pas encore créé d’API dans votre Auth0 Dashboard, vous pouvez utiliser le sélecteur interactif pour créer une nouvelle API Auth0 ou sélectionner une API existante qui représente le projet avec lequel vous souhaitez effectuer l’intégration. - - Vous pouvez également consulter notre guide de démarrage, qui vous aidera à configurer votre première API via Auth0 Dashboard. - - Notez que chaque API dans Auth0 est configurée à l’aide d’un identifiant d’API; votre code d’application utilisera l’identifiant d’API comme Public pour valider le jeton d’accès. - - - **Vous ne connaissez pas Auth0 ?** Découvrez Auth0 et l’implémentation de l’authentification et de l’autorisation d’API en utilisant le cadre d’applications OAuth 2.0. - - -
- Les autorisations vous permettent de définir comment les ressources peuvent être accessibles au nom de l’utilisateur avec un jeton d’accès donné. Par exemple, vous pouvez choisir d’accorder un accès en lecture à la ressource `messages` si les utilisateurs ont le niveau d’accès gestionnaire et accorder un accès en écriture à cette ressource s’ils ont le niveau d’accès administrateur. - - Vous pouvez définir les autorisations autorisées dans la vue **Permissions (Autorisations)** de la section [API](https://manage.auth0.com/#/apis) d’Auth0 Dashboard. L’exemple suivant utilise la permission `read:messages`. - - ![Auth0 Dashboard> Applications > APIs (API) > [Specific API (API précise)] > Onglet Permissions (Autorisations)](/docs/images/fr-ca/cdy7uua7fh8z/1s3Yp5zqJiKiSWqbPSezNO/677a3405b2853f5fdf9e42f6e83ceba7/Quickstarts_API_-_French.png) -
- -
- Pour permettre à votre application de valider les jetons d’accès, ajoutez une référence au package NuGet `Microsoft.AspNetCore.Authentication.JwtBearer` : - - ``` - Install-Package Microsoft.AspNetCore.Authentication.JwtBearer - ``` -
- -
- Configurez le logiciel médiateur d’authentification dans le fichier `Program.cs` de votre application : - - 1. Enregistrez les services d’authentification en appelant la méthode `AddAuthentication`. Configurez `JwtBearerDefaults.AuthenticationScheme` comme schéma par défaut. - 2. Enregistrez le schéma d’authentification du porteur JWT en faisant un appel à la méthode `AddJwtBearer`. Configurez votre domaine Auth0 comme autorité et votre identifiant API Auth0 comme public, et assurez-vous que votre domaine Auth0 et votre identifiant API sont définis dans le fichier **appsettings.json** de votre application. - - - Dans certains cas, le jeton d’accès n’aura pas de `sub` demande; dans ce cas, le nom `User.Identity.Name` sera `null`. Si vous souhaitez mapper une demande différente à `User.Identity.Name`, ajoutez-la aux `options.TokenValidationParameters` dans l’appel `AddJwtBearer()`. - - - . - 3. Ajoutez l’authentification et l’autorisation de le logiciel médiateur au pipeline du logiciel médiateur en ajoutant des appels aux méthodes `UseAuthentication` et `UseAuthorization` sous la méthode `var app = builder.Build();` . -
- -
- Pour s’assurer qu’un jeton d’accès contient les permissions adéquates, utilisez [Policy-Based Authorization (Autorisation basée sur une politique)](https://docs.microsoft.com/en-us/aspnet/core/security/authorization/policies) dans ASP.NET Core : - - 1. Créez une nouvelle exigence d’autorisation appelée `HasScopeRequirement`, qui vérifiera si la demande de `scope` émise par votre locataire Auth0 est présente et, le cas échéant, vérifiera que la demande contient la permission demandée. - 2. Dans la méthode `var builder = WebApplication.CreateBuilder(args);` du fichier `Program.cs`, ajoutez un appel à la méthode `app.AddAuthorization`. - 3. Ajoutez des politiques pour les permissions en appelant `AddPolicy` pour chaque permission. - 4. Enregistrez un singleton pour la classe `HasScopeHandler`. -
- -
- Le logiciel médiateur JWT s’intègre aux mécanismes d’[authentification](https://docs.microsoft.com/en-us/aspnet/core/security/authentication/) et d’[autorisation](https://docs.microsoft.com/en-us/aspnet/core/security/authorization/) standard de ASP.NET Core. - - Pour sécuriser un point de terminaison, ajoutez l’attribut `[Authorize]` à votre action de contrôleur (ou à tout le contrôleur si vous souhaitez protéger toutes ses actions). - - Lors de la sécurisation des points de terminaison qui nécessitent des permissions particulières, assurez-vous que la bonne permission est présente dans `access_token`. Pour ce faire, ajoutez l’attribut `Authorize` à l’action `Scoped` et passez `read:messages` comme paramètre de la `policy`. -
- -
- La façon dont vous appelez votre API dépend du type d’application que vous développez et du cadre que vous utilisez. Pour en savoir plus, lire le Guide rapide de l’application concernée : - - - [Applications à page unique](/docs/quickstart/spa) - - [Application mobile/native](/docs/quickstart/native) - - ### Obtenir un jeton d’accès - - Quel que soit le type d’application que vous développez ou le cadre que vous utilisez, vous aurez besoin d’un jeton d’accès pour appeler votre API. - - Si vous appelez votre API à partir d’une application à page unique (SPA) ou native, vous recevrez un jeton d’accès une fois l’autorisation obtenue. - - Si vous appelez l’API à partir d’un outil de ligne de commande ou d’un autre service sans identifiants utilisateur, utilisez le [Flux des identifiants client d’OAuth](https://auth0.com/docs/api/authentication#client-credentials). Pour ce faire, enregistrez une [Application de communication entre machines](https://manage.auth0.com/#/applications) et incluez les valeurs suivantes à votre requête : - - - **ID client** comme paramètre `client_id`. - - **Secret client** comme paramètre `client_secret`. - - **Identifiant API** (la même valeur utilisée pour configurer l’intergiciel plus tôt dans ce guide rapide) comme paramètre `audience`. - - - Pour en savoir plus sur l’obtention de l’identificateur client et du secret client pour votre application de communication entre machines, lisez la section Paramètres de l’application. - - - - ```sh cURL lines - curl --request post \ - --url 'https://dev-gja8kxz4ndtex3rq.us.auth0.com/oauth/token' \ - --header 'content-type: application/x-www-form-urlencoded' - ``` - - ```cs C# lines - var client = new RestClient("https://dev-gja8kxz4ndtex3rq.us.auth0.com/oauth/token"); - var request = new RestRequest(Method.POST); - request.AddHeader("content-type", "application/x-www-form-urlencoded"); - IRestResponse response = client.Execute(request); - ``` - - ```go Go lines - package main - import ( - "fmt" - "net/http" - "io/ioutil" - ) - func main() { - url := "https://dev-gja8kxz4ndtex3rq.us.auth0.com/oauth/token" - req, _ := http.NewRequest("post", url, nil) - req.Header.Add("content-type", "application/x-www-form-urlencoded") - res, _ := http.DefaultClient.Do(req) - defer res.Body.Close() - body, _ := ioutil.ReadAll(res.Body) - fmt.Println(res) - fmt.Println(string(body)) - } - ``` - - ```java Java lines - HttpResponse response = Unirest.post("https://dev-gja8kxz4ndtex3rq.us.auth0.com/oauth/token") - .header("content-type", "application/x-www-form-urlencoded") - .asString(); - ``` - - ```js Node.JS lines - var axios = require("axios").default; - var options = { - method: 'post', - url: 'https://dev-gja8kxz4ndtex3rq.us.auth0.com/oauth/token', - headers: {'content-type': 'application/x-www-form-urlencoded'} - }; - axios.request(options).then(function (response) { - console.log(response.data); - }).catch(function (error) { - console.error(error); - }); - ``` - - ```obj-c Obj-C lines - #import - NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; - NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://dev-gja8kxz4ndtex3rq.us.auth0.com/oauth/token"] - cachePolicy:NSURLRequestUseProtocolCachePolicy - - timeoutInterval:10.0]; - - [request setHTTPMethod:@"post"]; - [request setAllHTTPHeaderFields:headers]; - NSURLSession *session = [NSURLSession sharedSession]; - NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request - completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { - - if (error) { - - NSLog(@"%@", error); - - } else { - - NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response; - - NSLog(@"%@", httpResponse); - - } - - }]; - - [dataTask resume]; - ``` - - ```php PHP lines - $curl = curl_init(); - curl_setopt_array($curl, [ - CURLOPT_URL => "https://dev-gja8kxz4ndtex3rq.us.auth0.com/oauth/token", - CURLOPT_RETURNTRANSFER => true, - CURLOPT_ENCODING => "", - CURLOPT_MAXREDIRS => 10, - CURLOPT_TIMEOUT => 30, - CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, - CURLOPT_CUSTOMREQUEST => "post", - CURLOPT_HTTPHEADER => [ - "content-type: application/x-www-form-urlencoded" - - ], - ]); - $response = curl_exec($curl); - $err = curl_error($curl); - curl_close($curl); - if ($err) { - echo "cURL Error #:" . $err; - } else { - echo $response; - } - ``` - - ```python Python lines - import http.client - conn = http.client.HTTPSConnection("") - headers = { 'content-type': "application/x-www-form-urlencoded" } - conn.request("post", "/dev-gja8kxz4ndtex3rq.us.auth0.com/oauth/token", headers=headers) - res = conn.getresponse() - data = res.read() - print(data.decode("utf-8")) - ``` - - ```rb Ruby lines - require 'uri' - require 'net/http' - require 'openssl' - url = URI("https://dev-gja8kxz4ndtex3rq.us.auth0.com/oauth/token") - http = Net::HTTP.new(url.host, url.port) - http.use_ssl = true - http.verify_mode = OpenSSL::SSL::VERIFY_NONE - request = Net::HTTP::Post.new(url) - request["content-type"] = 'application/x-www-form-urlencoded' - response = http.request(request) - puts response.read_body - ``` - - ```swift Swift lines - require 'uri' - require 'net/http' - require 'openssl' - url = URI("https://dev-gja8kxz4ndtex3rq.us.auth0.com/oauth/token") - http = Net::HTTP.new(url.host, url.port) - http.use_ssl = true - http.verify_mode = OpenSSL::SSL::VERIFY_NONE - request = Net::HTTP::Post.new(url) - request["content-type"] = 'application/x-www-form-urlencoded' - response = http.request(request) - puts response.read_body - ``` - - - - - ### Appeler un point de terminaison sécurisé - - Maintenant que vous avez un jeton d’accès, vous pouvez l’utiliser pour appeler des points de terminaison API sécurisés. Lorsque vous appelez un point de terminaison sécurisé, vous devez inclure le jeton d’accès en tant que jeton de porteur dans l’en-tête **Authorization** de la requête. Par exemple, vous pouvez faire une requête au point de terminaison `/api/private` : - - - ```sh cURL lines - curl --request get \ - --url http://localhost:3010/api/private \ - --header 'authorization: Bearer YOUR_ACCESS_TOKEN' - ``` - - ```cs C# lines - var client = new RestClient("http://localhost:3010/api/private"); - var request = new RestRequest(Method.GET); - request.AddHeader("authorization", "Bearer YOUR_ACCESS_TOKEN"); - IRestResponse response = client.Execute(request); - ``` - - ```go Go lines - package main - import ( - "fmt" - "net/http" - "io/ioutil" - ) - func main() { - url := "http://localhost:3010/api/private" - req, _ := http.NewRequest("get", url, nil) - req.Header.Add("authorization", "Bearer YOUR_ACCESS_TOKEN") - res, _ := http.DefaultClient.Do(req) - defer res.Body.Close() - body, _ := ioutil.ReadAll(res.Body) - fmt.Println(res) - fmt.Println(string(body)) - } - ``` - - ```java Java lines - HttpResponse response = Unirest.get("http://localhost:3010/api/private") - .header("authorization", "Bearer YOUR_ACCESS_TOKEN") - .asString(); - ``` - - ```js Node.JS lines - var axios = require("axios").default; - var options = { - method: 'get', - url: 'http://localhost:3010/api/private', - headers: {authorization: 'Bearer YOUR_ACCESS_TOKEN'} - }; - axios.request(options).then(function (response) { - console.log(response.data); - }).catch(function (error) { - console.error(error); - }); - ``` - - ```obj-c Obj-C lines - #import - NSDictionary *headers = @{ @"authorization": @"Bearer YOUR_ACCESS_TOKEN" }; - NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://localhost:3010/api/private"] - cachePolicy:NSURLRequestUseProtocolCachePolicy - - timeoutInterval:10.0]; - - [request setHTTPMethod:@"get"]; - [request setAllHTTPHeaderFields:headers]; - NSURLSession *session = [NSURLSession sharedSession]; - NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request - completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { - - if (error) { - - NSLog(@"%@", error); - - } else { - - NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response; - - NSLog(@"%@", httpResponse); - - } - - }]; - - [dataTask resume]; - ``` - - ```php PHP lines - $curl = curl_init(); - curl_setopt_array($curl, [ - CURLOPT_PORT => "3010", - CURLOPT_URL => "http://localhost:3010/api/private", - CURLOPT_RETURNTRANSFER => true, - CURLOPT_ENCODING => "", - CURLOPT_MAXREDIRS => 10, - CURLOPT_TIMEOUT => 30, - CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, - CURLOPT_CUSTOMREQUEST => "get", - CURLOPT_HTTPHEADER => [ - "authorization: Bearer YOUR_ACCESS_TOKEN" - - ], - ]); - $response = curl_exec($curl); - $err = curl_error($curl); - curl_close($curl); - if ($err) { - echo "cURL Error #:" . $err; - } else { - echo $response; - } - ``` - - ```python Python lines - import http.client - conn = http.client.HTTPConnection("localhost:3010") - headers = { 'authorization': "Bearer YOUR_ACCESS_TOKEN" } - conn.request("get", "/api/private", headers=headers) - res = conn.getresponse() - data = res.read() - print(data.decode("utf-8")) - ``` - - ```rb Ruby lines - require 'uri' - require 'net/http' - url = URI("http://localhost:3010/api/private") - http = Net::HTTP.new(url.host, url.port) - request = Net::HTTP::Get.new(url) - request["authorization"] = 'Bearer YOUR_ACCESS_TOKEN' - response = http.request(request) - puts response.read_body - ``` - - ```swift Swift lines - import Foundation - let headers = ["authorization": "Bearer YOUR_ACCESS_TOKEN"] - let request = NSMutableURLRequest(url: NSURL(string: "http://localhost:3010/api/private")! as URL, - cachePolicy: .useProtocolCachePolicy, - - timeoutInterval: 10.0) - - request.httpMethod = "get" - request.allHTTPHeaderFields = headers - let session = URLSession.shared - let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in - if (error != nil) { - print(error) - - } else { - let httpResponse = response as? HTTPURLResponse - - print(httpResponse) - - } - }) - dataTask.resume() - ``` - - - - - - Appelez le point de terminaison `/api/private-scoped` de manière similaire, mais assurez-vous que les autorisations API sont configurées correctement et que le jeton d’accès inclut la permission `read:messages`. - - - ##### Point de contrôle - Vous devriez maintenant pouvoir appeler les points de terminaison `/api/private` et `/api/private-scoped`. - Exécutez votre application et vérifiez que : - `GET /api/private` est disponible pour les demandes authentifiées. - `GET /api/private-scoped` est disponible pour les demandes authentifiées contenant un jeton d’accès avec la permission `read:messages`. - -
- - ## Étapes suivantes - - Beau travail! Si vous en êtes arrivé là, vous devriez avoir la connexion, la déconnexion et les informations de profil utilisateur actives dans votre application. - - Cela conclut notre tutoriel de démarrage rapide, mais il y a tellement plus à explorer. Pour en savoir plus sur ce que vous pouvez faire avec Auth0, consultez : - - * [Auth0 Dashboard](https://manage.auth0.com/#) : apprenez à configurer et gérer votre locataire et vos applications Auth0 - * [Auth0 Marketplace](https://marketplace.auth0.com/) : découvrez des intégrations que vous pouvez activer pour étendre les fonctionnalités d’Auth0 -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+--- +title: "Ajouter une autorisation à votre application API ASP.NET Core Web" +permalink: "interactive" +'description': "Ce tutoriel explique comment ajouter une autorisation à une application API ASP.NET Core Web en utilisant le logiciel médiateur JWT standard." +'og:title': "Ajouter une autorisation à votre application API ASP.NET Core Web" +'og:description': "Ce tutoriel explique comment ajouter une autorisation à une application API ASP.NET Core Web en utilisant le logiciel médiateur JWT standard." +'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/asp.png" +'twitter:title': "Ajouter une autorisation à votre application API ASP.NET Core Web" +'twitter:description': "Ce tutoriel explique comment ajouter une autorisation à une application API ASP.NET Core Web en utilisant le logiciel médiateur JWT standard." +sidebarTitle: ASP.NET Core Web API +--- + +import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; +import { LoggedInForm } from "/snippets/Login.jsx"; +import Appsettings from "/snippets/quickstart/backend/aspnet-core-webapi/appsettings.json.mdx"; +import Program from "/snippets/quickstart/backend/aspnet-core-webapi/Program.cs.mdx"; +import Hasscopehandler from "/snippets/quickstart/backend/aspnet-core-webapi/HasScopeHandler.cs.mdx"; +import Hasscoperequirement from "/snippets/quickstart/backend/aspnet-core-webapi/HasScopeRequirement.cs.mdx"; +import Apicontroller from "/snippets/quickstart/backend/aspnet-core-webapi/ApiController.cs.mdx"; + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + +export const sections = [ + { id: "définir-les-autorisations", title: "Définir les autorisations" }, + { id: "installer-les-dépendances", title: "Installer les dépendances" }, + { id: "configurer-le-logiciel-médiateur", title: "Configurer le logiciel médiateur" }, + { id: "valider-les-permissions", title: "Valider les permissions" }, + { id: "protéger-les-points-de-terminaison-des-api", title: "Protéger les points de terminaison des API" }, + { id: "appeler-votre-api", title: "Appeler votre API" } +] + + + + Auth0 vous permet d’ajouter rapidement l’authentification et d’accéder aux informations relatives au profil de l’utilisateur dans presque tous les types d’applications. Ce guide explique comment intégrer Auth0 à n’importe quelle application API ASP.NET Web, nouvelle ou existante, à l’aide du package `Microsoft.AspNetCore.Authentication.JwtBearer` . + + Si vous n’avez pas encore créé d’API dans votre Auth0 Dashboard, vous pouvez utiliser le sélecteur interactif pour créer une nouvelle API Auth0 ou sélectionner une API existante qui représente le projet avec lequel vous souhaitez effectuer l’intégration. + + Vous pouvez également consulter notre guide de démarrage, qui vous aidera à configurer votre première API via Auth0 Dashboard. + + Notez que chaque API dans Auth0 est configurée à l’aide d’un identifiant d’API; votre code d’application utilisera l’identifiant d’API comme Public pour valider le jeton d’accès. + + + **Vous ne connaissez pas Auth0 ?** Découvrez Auth0 et l’implémentation de l’authentification et de l’autorisation d’API en utilisant le cadre d’applications OAuth 2.0. + + +
+ Les autorisations vous permettent de définir comment les ressources peuvent être accessibles au nom de l’utilisateur avec un jeton d’accès donné. Par exemple, vous pouvez choisir d’accorder un accès en lecture à la ressource `messages` si les utilisateurs ont le niveau d’accès gestionnaire et accorder un accès en écriture à cette ressource s’ils ont le niveau d’accès administrateur. + + Vous pouvez définir les autorisations autorisées dans la vue **Permissions (Autorisations)** de la section [API](https://manage.auth0.com/#/apis) d’Auth0 Dashboard. L’exemple suivant utilise la permission `read:messages`. + + ![Auth0 Dashboard> Applications > APIs (API) > [Specific API (API précise)] > Onglet Permissions (Autorisations)](/docs/images/fr-ca/cdy7uua7fh8z/1s3Yp5zqJiKiSWqbPSezNO/677a3405b2853f5fdf9e42f6e83ceba7/Quickstarts_API_-_French.png) +
+ +
+ Pour permettre à votre application de valider les jetons d’accès, ajoutez une référence au package NuGet `Microsoft.AspNetCore.Authentication.JwtBearer` : + + ``` + Install-Package Microsoft.AspNetCore.Authentication.JwtBearer + ``` +
+ +
+ Configurez le logiciel médiateur d’authentification dans le fichier `Program.cs` de votre application : + + 1. Enregistrez les services d’authentification en appelant la méthode `AddAuthentication`. Configurez `JwtBearerDefaults.AuthenticationScheme` comme schéma par défaut. + 2. Enregistrez le schéma d’authentification du porteur JWT en faisant un appel à la méthode `AddJwtBearer`. Configurez votre domaine Auth0 comme autorité et votre identifiant API Auth0 comme public, et assurez-vous que votre domaine Auth0 et votre identifiant API sont définis dans le fichier **appsettings.json** de votre application. + + + Dans certains cas, le jeton d’accès n’aura pas de `sub` demande; dans ce cas, le nom `User.Identity.Name` sera `null`. Si vous souhaitez mapper une demande différente à `User.Identity.Name`, ajoutez-la aux `options.TokenValidationParameters` dans l’appel `AddJwtBearer()`. + + + . + 3. Ajoutez l’authentification et l’autorisation de le logiciel médiateur au pipeline du logiciel médiateur en ajoutant des appels aux méthodes `UseAuthentication` et `UseAuthorization` sous la méthode `var app = builder.Build();` . +
+ +
+ Pour s’assurer qu’un jeton d’accès contient les permissions adéquates, utilisez [Policy-Based Authorization (Autorisation basée sur une politique)](https://docs.microsoft.com/en-us/aspnet/core/security/authorization/policies) dans ASP.NET Core : + + 1. Créez une nouvelle exigence d’autorisation appelée `HasScopeRequirement`, qui vérifiera si la demande de `scope` émise par votre locataire Auth0 est présente et, le cas échéant, vérifiera que la demande contient la permission demandée. + 2. Dans la méthode `var builder = WebApplication.CreateBuilder(args);` du fichier `Program.cs`, ajoutez un appel à la méthode `app.AddAuthorization`. + 3. Ajoutez des politiques pour les permissions en appelant `AddPolicy` pour chaque permission. + 4. Enregistrez un singleton pour la classe `HasScopeHandler`. +
+ +
+ Le logiciel médiateur JWT s’intègre aux mécanismes d’[authentification](https://docs.microsoft.com/en-us/aspnet/core/security/authentication/) et d’[autorisation](https://docs.microsoft.com/en-us/aspnet/core/security/authorization/) standard de ASP.NET Core. + + Pour sécuriser un point de terminaison, ajoutez l’attribut `[Authorize]` à votre action de contrôleur (ou à tout le contrôleur si vous souhaitez protéger toutes ses actions). + + Lors de la sécurisation des points de terminaison qui nécessitent des permissions particulières, assurez-vous que la bonne permission est présente dans `access_token`. Pour ce faire, ajoutez l’attribut `Authorize` à l’action `Scoped` et passez `read:messages` comme paramètre de la `policy`. +
+ +
+ La façon dont vous appelez votre API dépend du type d’application que vous développez et du cadre que vous utilisez. Pour en savoir plus, lire le Guide rapide de l’application concernée : + + - [Applications à page unique](/docs/quickstart/spa) + - [Application mobile/native](/docs/quickstart/native) + + ### Obtenir un jeton d’accès + + Quel que soit le type d’application que vous développez ou le cadre que vous utilisez, vous aurez besoin d’un jeton d’accès pour appeler votre API. + + Si vous appelez votre API à partir d’une application à page unique (SPA) ou native, vous recevrez un jeton d’accès une fois l’autorisation obtenue. + + Si vous appelez l’API à partir d’un outil de ligne de commande ou d’un autre service sans identifiants utilisateur, utilisez le [Flux des identifiants client d’OAuth](https://auth0.com/docs/api/authentication#client-credentials). Pour ce faire, enregistrez une [Application de communication entre machines](https://manage.auth0.com/#/applications) et incluez les valeurs suivantes à votre requête : + + - **ID client** comme paramètre `client_id`. + - **Secret client** comme paramètre `client_secret`. + - **Identifiant API** (la même valeur utilisée pour configurer l’intergiciel plus tôt dans ce guide rapide) comme paramètre `audience`. + + + Pour en savoir plus sur l’obtention de l’identificateur client et du secret client pour votre application de communication entre machines, lisez la section Paramètres de l’application. + + + + ```sh cURL lines + curl --request post \ + --url 'https://dev-gja8kxz4ndtex3rq.us.auth0.com/oauth/token' \ + --header 'content-type: application/x-www-form-urlencoded' + ``` + + ```cs C# lines + var client = new RestClient("https://dev-gja8kxz4ndtex3rq.us.auth0.com/oauth/token"); + var request = new RestRequest(Method.POST); + request.AddHeader("content-type", "application/x-www-form-urlencoded"); + IRestResponse response = client.Execute(request); + ``` + + ```go Go lines + package main + import ( + "fmt" + "net/http" + "io/ioutil" + ) + func main() { + url := "https://dev-gja8kxz4ndtex3rq.us.auth0.com/oauth/token" + req, _ := http.NewRequest("post", url, nil) + req.Header.Add("content-type", "application/x-www-form-urlencoded") + res, _ := http.DefaultClient.Do(req) + defer res.Body.Close() + body, _ := ioutil.ReadAll(res.Body) + fmt.Println(res) + fmt.Println(string(body)) + } + ``` + + ```java Java lines + HttpResponse response = Unirest.post("https://dev-gja8kxz4ndtex3rq.us.auth0.com/oauth/token") + .header("content-type", "application/x-www-form-urlencoded") + .asString(); + ``` + + ```js Node.JS lines + var axios = require("axios").default; + var options = { + method: 'post', + url: 'https://dev-gja8kxz4ndtex3rq.us.auth0.com/oauth/token', + headers: {'content-type': 'application/x-www-form-urlencoded'} + }; + axios.request(options).then(function (response) { + console.log(response.data); + }).catch(function (error) { + console.error(error); + }); + ``` + + ```obj-c Obj-C lines + #import + NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; + NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://dev-gja8kxz4ndtex3rq.us.auth0.com/oauth/token"] + cachePolicy:NSURLRequestUseProtocolCachePolicy + + timeoutInterval:10.0]; + + [request setHTTPMethod:@"post"]; + [request setAllHTTPHeaderFields:headers]; + NSURLSession *session = [NSURLSession sharedSession]; + NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request + completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { + + if (error) { + + NSLog(@"%@", error); + + } else { + + NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response; + + NSLog(@"%@", httpResponse); + + } + + }]; + + [dataTask resume]; + ``` + + ```php PHP lines + $curl = curl_init(); + curl_setopt_array($curl, [ + CURLOPT_URL => "https://dev-gja8kxz4ndtex3rq.us.auth0.com/oauth/token", + CURLOPT_RETURNTRANSFER => true, + CURLOPT_ENCODING => "", + CURLOPT_MAXREDIRS => 10, + CURLOPT_TIMEOUT => 30, + CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, + CURLOPT_CUSTOMREQUEST => "post", + CURLOPT_HTTPHEADER => [ + "content-type: application/x-www-form-urlencoded" + + ], + ]); + $response = curl_exec($curl); + $err = curl_error($curl); + curl_close($curl); + if ($err) { + echo "cURL Error #:" . $err; + } else { + echo $response; + } + ``` + + ```python Python lines + import http.client + conn = http.client.HTTPSConnection("") + headers = { 'content-type': "application/x-www-form-urlencoded" } + conn.request("post", "/dev-gja8kxz4ndtex3rq.us.auth0.com/oauth/token", headers=headers) + res = conn.getresponse() + data = res.read() + print(data.decode("utf-8")) + ``` + + ```rb Ruby lines + require 'uri' + require 'net/http' + require 'openssl' + url = URI("https://dev-gja8kxz4ndtex3rq.us.auth0.com/oauth/token") + http = Net::HTTP.new(url.host, url.port) + http.use_ssl = true + http.verify_mode = OpenSSL::SSL::VERIFY_NONE + request = Net::HTTP::Post.new(url) + request["content-type"] = 'application/x-www-form-urlencoded' + response = http.request(request) + puts response.read_body + ``` + + ```swift Swift lines + require 'uri' + require 'net/http' + require 'openssl' + url = URI("https://dev-gja8kxz4ndtex3rq.us.auth0.com/oauth/token") + http = Net::HTTP.new(url.host, url.port) + http.use_ssl = true + http.verify_mode = OpenSSL::SSL::VERIFY_NONE + request = Net::HTTP::Post.new(url) + request["content-type"] = 'application/x-www-form-urlencoded' + response = http.request(request) + puts response.read_body + ``` + + + + + ### Appeler un point de terminaison sécurisé + + Maintenant que vous avez un jeton d’accès, vous pouvez l’utiliser pour appeler des points de terminaison API sécurisés. Lorsque vous appelez un point de terminaison sécurisé, vous devez inclure le jeton d’accès en tant que jeton de porteur dans l’en-tête **Authorization** de la requête. Par exemple, vous pouvez faire une requête au point de terminaison `/api/private` : + + + ```sh cURL lines + curl --request get \ + --url http://localhost:3010/api/private \ + --header 'authorization: Bearer YOUR_ACCESS_TOKEN' + ``` + + ```cs C# lines + var client = new RestClient("http://localhost:3010/api/private"); + var request = new RestRequest(Method.GET); + request.AddHeader("authorization", "Bearer YOUR_ACCESS_TOKEN"); + IRestResponse response = client.Execute(request); + ``` + + ```go Go lines + package main + import ( + "fmt" + "net/http" + "io/ioutil" + ) + func main() { + url := "http://localhost:3010/api/private" + req, _ := http.NewRequest("get", url, nil) + req.Header.Add("authorization", "Bearer YOUR_ACCESS_TOKEN") + res, _ := http.DefaultClient.Do(req) + defer res.Body.Close() + body, _ := ioutil.ReadAll(res.Body) + fmt.Println(res) + fmt.Println(string(body)) + } + ``` + + ```java Java lines + HttpResponse response = Unirest.get("http://localhost:3010/api/private") + .header("authorization", "Bearer YOUR_ACCESS_TOKEN") + .asString(); + ``` + + ```js Node.JS lines + var axios = require("axios").default; + var options = { + method: 'get', + url: 'http://localhost:3010/api/private', + headers: {authorization: 'Bearer YOUR_ACCESS_TOKEN'} + }; + axios.request(options).then(function (response) { + console.log(response.data); + }).catch(function (error) { + console.error(error); + }); + ``` + + ```obj-c Obj-C lines + #import + NSDictionary *headers = @{ @"authorization": @"Bearer YOUR_ACCESS_TOKEN" }; + NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://localhost:3010/api/private"] + cachePolicy:NSURLRequestUseProtocolCachePolicy + + timeoutInterval:10.0]; + + [request setHTTPMethod:@"get"]; + [request setAllHTTPHeaderFields:headers]; + NSURLSession *session = [NSURLSession sharedSession]; + NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request + completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { + + if (error) { + + NSLog(@"%@", error); + + } else { + + NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response; + + NSLog(@"%@", httpResponse); + + } + + }]; + + [dataTask resume]; + ``` + + ```php PHP lines + $curl = curl_init(); + curl_setopt_array($curl, [ + CURLOPT_PORT => "3010", + CURLOPT_URL => "http://localhost:3010/api/private", + CURLOPT_RETURNTRANSFER => true, + CURLOPT_ENCODING => "", + CURLOPT_MAXREDIRS => 10, + CURLOPT_TIMEOUT => 30, + CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, + CURLOPT_CUSTOMREQUEST => "get", + CURLOPT_HTTPHEADER => [ + "authorization: Bearer YOUR_ACCESS_TOKEN" + + ], + ]); + $response = curl_exec($curl); + $err = curl_error($curl); + curl_close($curl); + if ($err) { + echo "cURL Error #:" . $err; + } else { + echo $response; + } + ``` + + ```python Python lines + import http.client + conn = http.client.HTTPConnection("localhost:3010") + headers = { 'authorization': "Bearer YOUR_ACCESS_TOKEN" } + conn.request("get", "/api/private", headers=headers) + res = conn.getresponse() + data = res.read() + print(data.decode("utf-8")) + ``` + + ```rb Ruby lines + require 'uri' + require 'net/http' + url = URI("http://localhost:3010/api/private") + http = Net::HTTP.new(url.host, url.port) + request = Net::HTTP::Get.new(url) + request["authorization"] = 'Bearer YOUR_ACCESS_TOKEN' + response = http.request(request) + puts response.read_body + ``` + + ```swift Swift lines + import Foundation + let headers = ["authorization": "Bearer YOUR_ACCESS_TOKEN"] + let request = NSMutableURLRequest(url: NSURL(string: "http://localhost:3010/api/private")! as URL, + cachePolicy: .useProtocolCachePolicy, + + timeoutInterval: 10.0) + + request.httpMethod = "get" + request.allHTTPHeaderFields = headers + let session = URLSession.shared + let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in + if (error != nil) { + print(error) + + } else { + let httpResponse = response as? HTTPURLResponse + + print(httpResponse) + + } + }) + dataTask.resume() + ``` + + + + + + Appelez le point de terminaison `/api/private-scoped` de manière similaire, mais assurez-vous que les autorisations API sont configurées correctement et que le jeton d’accès inclut la permission `read:messages`. + + + ##### Point de contrôle + Vous devriez maintenant pouvoir appeler les points de terminaison `/api/private` et `/api/private-scoped`. + Exécutez votre application et vérifiez que : + `GET /api/private` est disponible pour les demandes authentifiées. + `GET /api/private-scoped` est disponible pour les demandes authentifiées contenant un jeton d’accès avec la permission `read:messages`. + +
+ + ## Étapes suivantes + + Beau travail! Si vous en êtes arrivé là, vous devriez avoir la connexion, la déconnexion et les informations de profil utilisateur actives dans votre application. + + Cela conclut notre tutoriel de démarrage rapide, mais il y a tellement plus à explorer. Pour en savoir plus sur ce que vous pouvez faire avec Auth0, consultez : + + * [Auth0 Dashboard](https://manage.auth0.com/#) : apprenez à configurer et gérer votre locataire et vos applications Auth0 + * [Auth0 Marketplace](https://marketplace.auth0.com/) : découvrez des intégrations que vous pouvez activer pour étendre les fonctionnalités d’Auth0 +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
diff --git a/main/docs/fr-ca/quickstart/backend/django/interactive.mdx b/main/docs/fr-ca/quickstart/backend/django/interactive.mdx index 7fff7daf9..9cab3d909 100644 --- a/main/docs/fr-ca/quickstart/backend/django/interactive.mdx +++ b/main/docs/fr-ca/quickstart/backend/django/interactive.mdx @@ -1,297 +1,299 @@ ---- -title: "Ajouter une autorisation à votre application API Django" -permalink: "interactive" -'description': "Ce tutoriel explique comment ajouter une autorisation à une API Python développée avec Django." -'og:title': "Ajouter une autorisation à votre application API Django" -'og:description': "Ce tutoriel explique comment ajouter une autorisation à une API Python développée avec Django." -'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/django.png" -'twitter:title': "Ajouter une autorisation à votre application API Django" -'twitter:description': "Ce tutoriel explique comment ajouter une autorisation à une API Python développée avec Django." -sidebarTitle: Django API ---- - -import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; -import { LoggedInForm } from "/snippets/Login.jsx"; -import Validator from "/snippets/quickstart/backend/django/validator.py.mdx"; -import Views from "/snippets/quickstart/backend/django/views.py.mdx"; -import Urls from "/snippets/quickstart/backend/django/urls.py.mdx"; - -export const sections = [ - { id: "définir-les-autorisations", title: "Définir les autorisations" }, - { id: "configurer-django-pour-utiliser-auth0", title: "Configurer Django pour utiliser Auth0" }, - { id: "créer-le-validateur-jwt", title: "Créer le validateur JWT" }, - { id: "créer-les-vues-api", title: "Créer les vues API" }, - { id: "ajouter-des-mappages-d-url", title: "Ajouter des mappages d’URL" } -] - - - - Ce guide explique comment intégrer Auth0 à n’importe quelle API Python, nouvelle ou ancienne, développée avec [Django](https://www.djangoproject.com/). - - Si vous n’avez pas encore créé d’API dans votre Auth0 Dashboard, vous pouvez utiliser le sélecteur interactif pour créer une nouvelle API Auth0 ou sélectionner une API existante qui représente le projet avec lequel vous souhaitez vous intégrer. - - Vous pouvez également lire notre guide de démarrage, qui vous aidera à configurer votre première API via Auth0 Dashboard. - - Toute API dans Auth0 est configurée à l’aide d’un identifiant d’API que votre code d’application utilisera comme Audience pour valider le jeton d’accès. - - - **Vous ne connaissez pas Auth0 ?** Découvrez Auth0 et l’implémentation de l’authentification et de l’autorisation d’API en utilisant le cadre d’applications OAuth 2.0. - - -
- Les autorisations vous permettent de définir comment les ressources peuvent être accessibles au nom de l’utilisateur avec un jeton d’accès donné. Par exemple, vous pouvez choisir d’accorder un accès en lecture à la ressource `messages` si les utilisateurs ont le niveau d’accès gestionnaire et accorder un accès en écriture à cette ressource s’ils ont le niveau d’accès administrateur. - - Vous pouvez définir les autorisations autorisées dans la vue **Permissions (Autorisations)** de la section [API](https://manage.auth0.com/#/apis) du Auth0 Dashboard. L’exemple suivant utilise la permission `read:messages`. - - ![Auth0 Dashboard> Applications > APIs (API) > [Specific API (API précise)] > Onglet Permissions (Autorisations)](/docs/images/fr-ca/cdy7uua7fh8z/1s3Yp5zqJiKiSWqbPSezNO/677a3405b2853f5fdf9e42f6e83ceba7/Quickstarts_API_-_French.png) -
- -
- ### Installez des dépendances - - 1. Ajoutez les dépendances suivantes à votre `requirements.txt` : - 2. Exécutez `pip install -r requirements.txt` - - ### Créez une application Django -
- -
- Vous utiliserez une bibliothèque appelée [Authlib](https://github.com/lepture/authlib) pour créer un [ResourceProtector](https://docs.authlib.org/en/latest/flask/1/resource-server.html), qui est un type de [Django view decorator (Décorateur de vue Django)](https://docs.djangoproject.com/en/4.0/topics/http/decorators/) qui protège vos ressources (vues API) avec un validateur donné. - - Le validateur vérifiera le jeton d’accès que vous passez à la ressource en vérifiant qu’il a une signature et des demandes valides. - - Vous pouvez utiliser le validateur `JWTBearerTokenValidator` d’AuthLib avec quelques ajustements pour vous assurer qu’il est conforme à nos exigences de [validation des jetons d’accès](https://auth0.com/docs/secure/tokens/access-tokens/validate-access-tokens). - - Pour créer votre `Auth0JWTBearerTokenValidator`, vous devez le passer à votre `domaine` et à votre `public` (Identificateur API). Il obtiendra alors la clé publique nécessaire pour vérifier la signature du jeton et la passera à la classe `JWTBearerTokenValidator`. - - Vous remplacerez ensuite les `claims_options` de la classe pour vous assurer que les demandes `expiry`, `audience` et `issue` du jeton sont validées selon nos exigences. - - Créez le fichier `apiexample/validator.py` en utilisant le code du panneau interactif. -
- -
- Ensuite, vous allez créer trois vues API dans `apiexample/views.py` : - - - `/api/public` : point de terminaison public qui ne nécessite aucune authentification. - - `/api/private` : point de terminaison privé qui nécessite un JWT de jeton d’accès valide. - - `/api/private-scoped` : termpoint de terminaison inal privé qui nécessite un JWT de jeton d’accès valide contenant la `scope` donnée. - - Les routes protégées auront un "decorator" `require_auth`, qui est un `ResourceProtector` qui utilise le `Auth0JWTBearerTokenValidator` que vous avez créé précédemment. - - Pour créer le `Auth0JWTBearerTokenValidator`, vous devez le transmettre au domaine de votre locataire et à l’identificateur de l’API que vous avez créé précédemment. - - Le decorator `require_auth` sur la route `private_scoped` prend en charge un argument supplémentaire `"read:messages"` qui vérifie la permission du jeton d’accès que vous avez créé précédemment. -
- -
- Dans les étapes précédentes, vous avez ajouté des méthodes au fichier `views.py` . Mappez à présent ces méthodes aux URL en utilisant le [URL Dispatcher (Répartiteur d’URL)](https://docs.djangoproject.com/en/4.0/topics/http/urls/) de Django, qui vous permet de mapper les modèles d’URL aux vues. - - Ajoutez les modèles d’URL à votre fichier `apiexample/urls.py`. - - ### Faites un appel à votre API - - Pour appeler votre API, vous aurez besoin d’un jeton d’accès. Vous pouvez récupérer un jeton d’accès à des fins de test dans la vue **Test** dans vos [API Settings (Paramètres API)](https://manage.auth0.com/#/apis). - - ![Auth0 Dashboard> Applications > API > [API specifique] > Onglet Test](/docs/images/fr-ca/cdy7uua7fh8z/6jeVBuypOGX5qMRXeJn5ow/8aa621c6d95e3f21115493a19ab05f7a/Quickstart_Example_App_-_API.png) - - Fournissez le jeton d’accès comme en-tête `Authorization` dans vos requêtes. - - - ```bash cURL lines - curl --request get \ - --url 'http:///%7ByourDomain%7D.com/api_path' \ - --header 'authorization: Bearer YOUR_ACCESS_TOKEN_HERE' - ``` - ```csharp C# lines - var client = new RestClient("http:///%7ByourDomain%7D.com/api_path"); - var request = new RestRequest(Method.GET); - request.AddHeader("authorization", "Bearer YOUR_ACCESS_TOKEN_HERE"); - IRestResponse response = client.Execute(request); - ``` - - ```go Go lines - package main - import ( - "fmt" - "net/http" - "io/ioutil" - ) - func main() { - url := "http:///%7ByourDomain%7D.com/api_path" - req, _ := http.NewRequest("get", url, nil) - req.Header.Add("authorization", "Bearer YOUR_ACCESS_TOKEN_HERE") - res, _ := http.DefaultClient.Do(req) - defer res.Body.Close() - body, _ := ioutil.ReadAll(res.Body) - fmt.Println(res) - fmt.Println(string(body)) - } - ``` - - ```java Java lines - HttpResponse response = Unirest.get("http:///%7ByourDomain%7D.com/api_path") - .header("authorization", "Bearer YOUR_ACCESS_TOKEN_HERE") - .asString(); - ``` - - ```javascript Node.JS lines - var axios = require("axios").default; - var options = { - method: 'get', - url: 'http:///%7ByourDomain%7D.com/api_path', - headers: {authorization: 'Bearer YOUR_ACCESS_TOKEN_HERE'} - }; - axios.request(options).then(function (response) { - console.log(response.data); - }).catch(function (error) { - console.error(error); - }); - ``` - ```obj-c Obj-C lines - #import - NSDictionary *headers = @{ @"authorization": @"Bearer YOUR_ACCESS_TOKEN_HERE" }; - NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http:///%7ByourDomain%7D.com/api_path"] - cachePolicy:NSURLRequestUseProtocolCachePolicy - - timeoutInterval:10.0]; - - [request setHTTPMethod:@"get"]; - [request setAllHTTPHeaderFields:headers]; - NSURLSession *session = [NSURLSession sharedSession]; - NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request - completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { - - if (error) { - - NSLog(@"%@", error); - - } else { - - NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response; - - NSLog(@"%@", httpResponse); - - } - - }]; - - [dataTask resume]; - ``` - - ```php PHP lines - $curl = curl_init(); - curl_setopt_array($curl, [ - CURLOPT_URL => "http:///%7ByourDomain%7D.com/api_path", - CURLOPT_RETURNTRANSFER => true, - CURLOPT_ENCODING => "", - CURLOPT_MAXREDIRS => 10, - CURLOPT_TIMEOUT => 30, - CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, - CURLOPT_CUSTOMREQUEST => "get", - CURLOPT_HTTPHEADER => [ - "authorization: Bearer YOUR_ACCESS_TOKEN_HERE" - - ], - ]); - $response = curl_exec($curl); - $err = curl_error($curl); - curl_close($curl); - if ($err) { - echo "cURL Error #:" . $err; - } else { - echo $response; - } - ``` - ```python Python lines - import http.client - conn = http.client.HTTPConnection("") - headers = { 'authorization': "Bearer YOUR_ACCESS_TOKEN_HERE" } - conn.request("get", "/dev-gja8kxz4ndtex3rq.us.auth0.com.com/api_path", headers=headers) - res = conn.getresponse() - data = res.read() - print(data.decode("utf-8")) - ``` - - ```ruby Ruby lines - require 'uri' - require 'net/http' - url = URI("http:///%7ByourDomain%7D.com/api_path") - http = Net::HTTP.new(url.host, url.port) - request = Net::HTTP::Get.new(url) - request["authorization"] = 'Bearer YOUR_ACCESS_TOKEN_HERE' - response = http.request(request) - puts response.read_body - ``` - ```swift Swift lines - import Foundation - let headers = ["authorization": "Bearer YOUR_ACCESS_TOKEN_HERE"] - let request = NSMutableURLRequest(url: NSURL(string: "http:///%7ByourDomain%7D.com/api_path")! as URL, - cachePolicy: .useProtocolCachePolicy, - - timeoutInterval: 10.0) - - request.httpMethod = "get" - request.allHTTPHeaderFields = headers - let session = URLSession.shared - let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in - if (error != nil) { - print(error) - - } else { - let httpResponse = response as? HTTPURLResponse - - print(httpResponse) - - } - }) - dataTask.resume() - ``` - - -
- - ## Étapes suivantes - - Beau travail! Si vous en êtes arrivé là, vous devriez avoir la connexion, la déconnexion et les informations de profil utilisateur actives dans votre application. - - Cela conclut notre tutoriel de démarrage rapide, mais il y a tellement plus à explorer. Pour en savoir plus sur ce que vous pouvez faire avec Auth0, consultez : - - * [Auth0 Dashboard](https://manage.auth0.com/#) : apprenez à configurer et gérer votre locataire et vos applications Auth0 - * [Auth0 Marketplace](https://marketplace.auth0.com/) : découvrez des intégrations que vous pouvez activer pour étendre les fonctionnalités d’Auth0 -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+--- +title: "Ajouter une autorisation à votre application API Django" +permalink: "interactive" +'description': "Ce tutoriel explique comment ajouter une autorisation à une API Python développée avec Django." +'og:title': "Ajouter une autorisation à votre application API Django" +'og:description': "Ce tutoriel explique comment ajouter une autorisation à une API Python développée avec Django." +'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/django.png" +'twitter:title': "Ajouter une autorisation à votre application API Django" +'twitter:description': "Ce tutoriel explique comment ajouter une autorisation à une API Python développée avec Django." +sidebarTitle: Django API +--- + +import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; +import { LoggedInForm } from "/snippets/Login.jsx"; +import Validator from "/snippets/quickstart/backend/django/validator.py.mdx"; +import Views from "/snippets/quickstart/backend/django/views.py.mdx"; +import Urls from "/snippets/quickstart/backend/django/urls.py.mdx"; + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + +export const sections = [ + { id: "définir-les-autorisations", title: "Définir les autorisations" }, + { id: "configurer-django-pour-utiliser-auth0", title: "Configurer Django pour utiliser Auth0" }, + { id: "créer-le-validateur-jwt", title: "Créer le validateur JWT" }, + { id: "créer-les-vues-api", title: "Créer les vues API" }, + { id: "ajouter-des-mappages-d-url", title: "Ajouter des mappages d’URL" } +] + + + + Ce guide explique comment intégrer Auth0 à n’importe quelle API Python, nouvelle ou ancienne, développée avec [Django](https://www.djangoproject.com/). + + Si vous n’avez pas encore créé d’API dans votre Auth0 Dashboard, vous pouvez utiliser le sélecteur interactif pour créer une nouvelle API Auth0 ou sélectionner une API existante qui représente le projet avec lequel vous souhaitez vous intégrer. + + Vous pouvez également lire notre guide de démarrage, qui vous aidera à configurer votre première API via Auth0 Dashboard. + + Toute API dans Auth0 est configurée à l’aide d’un identifiant d’API que votre code d’application utilisera comme Audience pour valider le jeton d’accès. + + + **Vous ne connaissez pas Auth0 ?** Découvrez Auth0 et l’implémentation de l’authentification et de l’autorisation d’API en utilisant le cadre d’applications OAuth 2.0. + + +
+ Les autorisations vous permettent de définir comment les ressources peuvent être accessibles au nom de l’utilisateur avec un jeton d’accès donné. Par exemple, vous pouvez choisir d’accorder un accès en lecture à la ressource `messages` si les utilisateurs ont le niveau d’accès gestionnaire et accorder un accès en écriture à cette ressource s’ils ont le niveau d’accès administrateur. + + Vous pouvez définir les autorisations autorisées dans la vue **Permissions (Autorisations)** de la section [API](https://manage.auth0.com/#/apis) du Auth0 Dashboard. L’exemple suivant utilise la permission `read:messages`. + + ![Auth0 Dashboard> Applications > APIs (API) > [Specific API (API précise)] > Onglet Permissions (Autorisations)](/docs/images/fr-ca/cdy7uua7fh8z/1s3Yp5zqJiKiSWqbPSezNO/677a3405b2853f5fdf9e42f6e83ceba7/Quickstarts_API_-_French.png) +
+ +
+ ### Installez des dépendances + + 1. Ajoutez les dépendances suivantes à votre `requirements.txt` : + 2. Exécutez `pip install -r requirements.txt` + + ### Créez une application Django +
+ +
+ Vous utiliserez une bibliothèque appelée [Authlib](https://github.com/lepture/authlib) pour créer un [ResourceProtector](https://docs.authlib.org/en/latest/flask/1/resource-server.html), qui est un type de [Django view decorator (Décorateur de vue Django)](https://docs.djangoproject.com/en/4.0/topics/http/decorators/) qui protège vos ressources (vues API) avec un validateur donné. + + Le validateur vérifiera le jeton d’accès que vous passez à la ressource en vérifiant qu’il a une signature et des demandes valides. + + Vous pouvez utiliser le validateur `JWTBearerTokenValidator` d’AuthLib avec quelques ajustements pour vous assurer qu’il est conforme à nos exigences de [validation des jetons d’accès](https://auth0.com/docs/secure/tokens/access-tokens/validate-access-tokens). + + Pour créer votre `Auth0JWTBearerTokenValidator`, vous devez le passer à votre `domaine` et à votre `public` (Identificateur API). Il obtiendra alors la clé publique nécessaire pour vérifier la signature du jeton et la passera à la classe `JWTBearerTokenValidator`. + + Vous remplacerez ensuite les `claims_options` de la classe pour vous assurer que les demandes `expiry`, `audience` et `issue` du jeton sont validées selon nos exigences. + + Créez le fichier `apiexample/validator.py` en utilisant le code du panneau interactif. +
+ +
+ Ensuite, vous allez créer trois vues API dans `apiexample/views.py` : + + - `/api/public` : point de terminaison public qui ne nécessite aucune authentification. + - `/api/private` : point de terminaison privé qui nécessite un JWT de jeton d’accès valide. + - `/api/private-scoped` : termpoint de terminaison inal privé qui nécessite un JWT de jeton d’accès valide contenant la `scope` donnée. + + Les routes protégées auront un "decorator" `require_auth`, qui est un `ResourceProtector` qui utilise le `Auth0JWTBearerTokenValidator` que vous avez créé précédemment. + + Pour créer le `Auth0JWTBearerTokenValidator`, vous devez le transmettre au domaine de votre locataire et à l’identificateur de l’API que vous avez créé précédemment. + + Le decorator `require_auth` sur la route `private_scoped` prend en charge un argument supplémentaire `"read:messages"` qui vérifie la permission du jeton d’accès que vous avez créé précédemment. +
+ +
+ Dans les étapes précédentes, vous avez ajouté des méthodes au fichier `views.py` . Mappez à présent ces méthodes aux URL en utilisant le [URL Dispatcher (Répartiteur d’URL)](https://docs.djangoproject.com/en/4.0/topics/http/urls/) de Django, qui vous permet de mapper les modèles d’URL aux vues. + + Ajoutez les modèles d’URL à votre fichier `apiexample/urls.py`. + + ### Faites un appel à votre API + + Pour appeler votre API, vous aurez besoin d’un jeton d’accès. Vous pouvez récupérer un jeton d’accès à des fins de test dans la vue **Test** dans vos [API Settings (Paramètres API)](https://manage.auth0.com/#/apis). + + ![Auth0 Dashboard> Applications > API > [API specifique] > Onglet Test](/docs/images/fr-ca/cdy7uua7fh8z/6jeVBuypOGX5qMRXeJn5ow/8aa621c6d95e3f21115493a19ab05f7a/Quickstart_Example_App_-_API.png) + + Fournissez le jeton d’accès comme en-tête `Authorization` dans vos requêtes. + + + ```bash cURL lines + curl --request get \ + --url 'http:///%7ByourDomain%7D.com/api_path' \ + --header 'authorization: Bearer YOUR_ACCESS_TOKEN_HERE' + ``` + ```csharp C# lines + var client = new RestClient("http:///%7ByourDomain%7D.com/api_path"); + var request = new RestRequest(Method.GET); + request.AddHeader("authorization", "Bearer YOUR_ACCESS_TOKEN_HERE"); + IRestResponse response = client.Execute(request); + ``` + + ```go Go lines + package main + import ( + "fmt" + "net/http" + "io/ioutil" + ) + func main() { + url := "http:///%7ByourDomain%7D.com/api_path" + req, _ := http.NewRequest("get", url, nil) + req.Header.Add("authorization", "Bearer YOUR_ACCESS_TOKEN_HERE") + res, _ := http.DefaultClient.Do(req) + defer res.Body.Close() + body, _ := ioutil.ReadAll(res.Body) + fmt.Println(res) + fmt.Println(string(body)) + } + ``` + + ```java Java lines + HttpResponse response = Unirest.get("http:///%7ByourDomain%7D.com/api_path") + .header("authorization", "Bearer YOUR_ACCESS_TOKEN_HERE") + .asString(); + ``` + + ```javascript Node.JS lines + var axios = require("axios").default; + var options = { + method: 'get', + url: 'http:///%7ByourDomain%7D.com/api_path', + headers: {authorization: 'Bearer YOUR_ACCESS_TOKEN_HERE'} + }; + axios.request(options).then(function (response) { + console.log(response.data); + }).catch(function (error) { + console.error(error); + }); + ``` + ```obj-c Obj-C lines + #import + NSDictionary *headers = @{ @"authorization": @"Bearer YOUR_ACCESS_TOKEN_HERE" }; + NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http:///%7ByourDomain%7D.com/api_path"] + cachePolicy:NSURLRequestUseProtocolCachePolicy + + timeoutInterval:10.0]; + + [request setHTTPMethod:@"get"]; + [request setAllHTTPHeaderFields:headers]; + NSURLSession *session = [NSURLSession sharedSession]; + NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request + completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { + + if (error) { + + NSLog(@"%@", error); + + } else { + + NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response; + + NSLog(@"%@", httpResponse); + + } + + }]; + + [dataTask resume]; + ``` + + ```php PHP lines + $curl = curl_init(); + curl_setopt_array($curl, [ + CURLOPT_URL => "http:///%7ByourDomain%7D.com/api_path", + CURLOPT_RETURNTRANSFER => true, + CURLOPT_ENCODING => "", + CURLOPT_MAXREDIRS => 10, + CURLOPT_TIMEOUT => 30, + CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, + CURLOPT_CUSTOMREQUEST => "get", + CURLOPT_HTTPHEADER => [ + "authorization: Bearer YOUR_ACCESS_TOKEN_HERE" + + ], + ]); + $response = curl_exec($curl); + $err = curl_error($curl); + curl_close($curl); + if ($err) { + echo "cURL Error #:" . $err; + } else { + echo $response; + } + ``` + ```python Python lines + import http.client + conn = http.client.HTTPConnection("") + headers = { 'authorization': "Bearer YOUR_ACCESS_TOKEN_HERE" } + conn.request("get", "/dev-gja8kxz4ndtex3rq.us.auth0.com.com/api_path", headers=headers) + res = conn.getresponse() + data = res.read() + print(data.decode("utf-8")) + ``` + + ```ruby Ruby lines + require 'uri' + require 'net/http' + url = URI("http:///%7ByourDomain%7D.com/api_path") + http = Net::HTTP.new(url.host, url.port) + request = Net::HTTP::Get.new(url) + request["authorization"] = 'Bearer YOUR_ACCESS_TOKEN_HERE' + response = http.request(request) + puts response.read_body + ``` + ```swift Swift lines + import Foundation + let headers = ["authorization": "Bearer YOUR_ACCESS_TOKEN_HERE"] + let request = NSMutableURLRequest(url: NSURL(string: "http:///%7ByourDomain%7D.com/api_path")! as URL, + cachePolicy: .useProtocolCachePolicy, + + timeoutInterval: 10.0) + + request.httpMethod = "get" + request.allHTTPHeaderFields = headers + let session = URLSession.shared + let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in + if (error != nil) { + print(error) + + } else { + let httpResponse = response as? HTTPURLResponse + + print(httpResponse) + + } + }) + dataTask.resume() + ``` + + +
+ + ## Étapes suivantes + + Beau travail! Si vous en êtes arrivé là, vous devriez avoir la connexion, la déconnexion et les informations de profil utilisateur actives dans votre application. + + Cela conclut notre tutoriel de démarrage rapide, mais il y a tellement plus à explorer. Pour en savoir plus sur ce que vous pouvez faire avec Auth0, consultez : + + * [Auth0 Dashboard](https://manage.auth0.com/#) : apprenez à configurer et gérer votre locataire et vos applications Auth0 + * [Auth0 Marketplace](https://marketplace.auth0.com/) : découvrez des intégrations que vous pouvez activer pour étendre les fonctionnalités d’Auth0 +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
diff --git a/main/docs/fr-ca/quickstart/backend/golang/interactive.mdx b/main/docs/fr-ca/quickstart/backend/golang/interactive.mdx index 851e0d035..605d4eacf 100644 --- a/main/docs/fr-ca/quickstart/backend/golang/interactive.mdx +++ b/main/docs/fr-ca/quickstart/backend/golang/interactive.mdx @@ -1,324 +1,326 @@ ---- -title: "Ajouter une autorisation à votre application Go" -permalink: "interactive" -'description': "Ce tutoriel explique comment ajouter une autorisation à une API Go." -'og:title': "Ajouter une autorisation à votre application Go" -'og:description': "Ce tutoriel explique comment ajouter une autorisation à une API Go." -'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/golang.png" -'twitter:title': "Ajouter une autorisation à votre application Go" -'twitter:description': "Ce tutoriel explique comment ajouter une autorisation à une API Go." -sidebarTitle: Go API ---- - -import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; -import { LoggedInForm } from "/snippets/Login.jsx"; -import Jwt from "/snippets/quickstart/backend/golang/jwt.go.mdx"; -import Main from "/snippets/quickstart/backend/golang/main.go.mdx"; - -export const sections = [ - { id: "définir-les-autorisations", title: "Définir les autorisations" }, - { id: "installer-les-dépendances", title: "Installer les dépendances" }, - { id: "configuration-de-votre-application", title: "Configuration de votre application" }, - { id: "créer-un-logiciel-médiateur-pour-valider-les-jetons-d-accès", title: "Créer un logiciel médiateur pour valider les jetons d’accès" }, - { id: "protéger-les-points-de-terminaison-des-api", title: "Protéger les points de terminaison des API" } -] - - - - Ce guide explique comment intégrer Auth0 à n’importe quelle application API Go, nouvelle ou ancienne, en utilisant le package [go-jwt-middleware](https://github.com/auth0/go-jwt-middleware). - - Si vous n’avez pas encore créé d’API dans votre Auth0 Dashboard, vous pouvez utiliser le sélecteur interactif pour créer une nouvelle API Auth0 ou sélectionner une API existante pour votre projet. - - Pour configurer votre première API via Auth0 Dashboard, consultez notre guide de démarrage. - - Chaque API Auth0 utilise l’identificateur API, dont votre application a besoin pour valider le jeton d’accès. - - - **Vous ne connaissez pas Auth0 ?** Découvrez Auth0 et l’implémentation de l’authentification et de l’autorisation d’API en utilisant le cadre d’applications OAuth 2.0. - - -
- Les autorisations vous permettent de définir comment les ressources peuvent être accessibles au nom de l’utilisateur avec un jeton d’accès donné. Par exemple, vous pouvez choisir d’accorder un accès en lecture à la ressource `messages` si les utilisateurs ont le niveau d’accès gestionnaire et un accès en écriture à cette ressource s’ils ont le niveau d’accès administrateur. - - Vous pouvez définir les autorisations autorisées dans la vue **Permissions (Autorisations)** de la section [API](https://manage.auth0.com/#/apis) d’Auth0 Dashboard. L’exemple suivant utilise la permission `read:messages`. - - ![Auth0 Dashboard> Applications > APIs (API) > [Specific API (API précise)] > Onglet Permissions (Autorisations)](/docs/images/fr-ca/cdy7uua7fh8z/1s3Yp5zqJiKiSWqbPSezNO/677a3405b2853f5fdf9e42f6e83ceba7/Quickstarts_API_-_French.png) -
- -
- Ajoutez un fichier `go.mod` pour répertorier toutes les dépendances nécessaires. - - ``` - // go.mod - module 01-Authorization-RS256 - go 1.21 - require ( - github.com/auth0/go-jwt-middleware/v2 v2.2.0 - - github.com/joho/godotenv v1.5.1 - - ) - ``` - - Téléchargez les dépendances en exécutant la commande shell suivante : - - ``` - go mod download - ``` -
- -
- Créez un fichier `.env` à la racine de votre répertoire de projet pour stocker la configuration de l’application. Renseignez ensuite les variables d’environnement : - - ``` - # The URL of our Auth0 Tenant Domain. - If you're using a Custom Domain, be sure to set this to that value instead. - AUTH0_DOMAIN='{yourDomain}' - Our Auth0 API's Identifier. - AUTH0_AUDIENCE='{yourApiIdentifier}' - ``` -
- -
- La fonction de logiciel médiateur `EnsureValidToken` valide le jeton d’accès. Vous pouvez appliquer cette fonction à tous les points de terminaison que vous souhaitez protéger. Si le jeton est valide, le point de terminaison libère les ressources. Si le jeton n’est pas valide, l’API renvoie une erreur `401 Authorization (Autorisation 401)`. - - Configurez le logiciel médiateur **go-jwt-middleware** pour vérifier les jetons d’accès des demandes entrantes. - - Par défaut, votre API sera configurée pour utiliser RS256 comme algorithme de signature des jetons. Puisque RS256 fonctionne en utilisant une paire de clés privée/publique, les jetons peuvent être vérifiés par rapport à la clé publique pour votre compte Auth0. Cette clé publique est accessible à [https://{yourDomain}/.well-known/jwks.json](https://%7Byourdomain%7D/.well-known/jwks.json). - - Inclure un mécanisme pour vérifier que le jeton a une **scope (permission)** suffisante pour accéder aux ressources demandées. - - Créer une fonction `HasScope` pour vérifier et s’assurer que le jeton d’accès a la bonne permission avant de renvoyer une réponse réussie. -
- -
- Dans cet exemple, vous allez créer un point de terminaison `/api/public` qui n’utilise pas le logiciel médiateur `EnsureToken` car il est accessible aux requêtes non authentifiées. - - Créez un point de terminaison `/api/private` qui nécessite le logiciel médiateur `EnsureToken` car il n’est disponible que pour les requêtes authentifiées contenant un jeton d’accès, sans permission supplémentaire. - - Créez un point de terminaison `/api/private` qui nécessite le logiciel médiateur `EnsureToken` et `HasScope` car il n’est disponible que pour les requêtes authentifiées contenant un jeton d’accès dont la permission `read:messages` est accordée. - - - Seule la portée `read:messages` est vérifiée par la fonction `HasScope`. Vous pouvez l’étendre ou en faire un logiciel médiateur autonome qui accepte plusieurs permissions pour s’adapter à votre cas d’utilisation. - - - ### Faire un appel à votre API - - Pour appeler votre API, vous avez besoin d’un jeton d’accès. Vous pouvez obtenir un jeton d’accès à des fins de test dans la vue **Test** dans vos [API settings (Paramètres API)](https://manage.auth0.com/#/apis). - - ![Auth0 Dashboard> Applications > API > [API specifique] > Onglet Test](/docs/images/fr-ca/cdy7uua7fh8z/6jeVBuypOGX5qMRXeJn5ow/8aa621c6d95e3f21115493a19ab05f7a/Quickstart_Example_App_-_API.png) - - Fournissez le Jeton d’accès comme un en-tête `Authorization (Autorisation)` dans vos requêtes. - - - ```bash cURL lines - curl --request get \ - --url 'http:///%7ByourDomain%7D/api_path' \ - --header 'authorization: Bearer YOUR_ACCESS_TOKEN_HERE' - ``` - - ```csharp C# lines - var client = new RestClient("http:///%7ByourDomain%7D/api_path"); - var request = new RestRequest(Method.GET); - request.AddHeader("authorization", "Bearer YOUR_ACCESS_TOKEN_HERE"); - IRestResponse response = client.Execute(request); - ``` - - ```go Go lines - package main - import ( - "fmt" - "net/http" - "io/ioutil" - ) - func main() { - url := "http:///%7ByourDomain%7D/api_path" - req, _ := http.NewRequest("get", url, nil) - req.Header.Add("authorization", "Bearer YOUR_ACCESS_TOKEN_HERE") - res, _ := http.DefaultClient.Do(req) - defer res.Body.Close() - body, _ := ioutil.ReadAll(res.Body) - fmt.Println(res) - fmt.Println(string(body)) - } - ``` - - ```java Java lines - HttpResponse response = Unirest.get("http:///%7ByourDomain%7D/api_path") - .header("authorization", "Bearer YOUR_ACCESS_TOKEN_HERE") - .asString(); - ``` - - ```javascript Node.JS lines - var axios = require("axios").default; - var options = { - method: 'get', - url: 'http:///%7ByourDomain%7D/api_path', - headers: {authorization: 'Bearer YOUR_ACCESS_TOKEN_HERE'} - }; - axios.request(options).then(function (response) { - console.log(response.data); - }).catch(function (error) { - console.error(error); - }); - ``` - - ```obj-c Obj-C lines - #import - NSDictionary *headers = @{ @"authorization": @"Bearer YOUR_ACCESS_TOKEN_HERE" }; - NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http:///%7ByourDomain%7D/api_path"] - cachePolicy:NSURLRequestUseProtocolCachePolicy - - timeoutInterval:10.0]; - - [request setHTTPMethod:@"get"]; - [request setAllHTTPHeaderFields:headers]; - NSURLSession *session = [NSURLSession sharedSession]; - NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request - completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { - - if (error) { - - NSLog(@"%@", error); - - } else { - - NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response; - - NSLog(@"%@", httpResponse); - - } - - }]; - - [dataTask resume]; - ``` - - ```php PHP lines - #import - NSDictionary *headers = @{ @"authorization": @"Bearer YOUR_ACCESS_TOKEN_HERE" }; - NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http:///%7ByourDomain%7D/api_path"] - cachePolicy:NSURLRequestUseProtocolCachePolicy - - timeoutInterval:10.0]; - - [request setHTTPMethod:@"get"]; - [request setAllHTTPHeaderFields:headers]; - NSURLSession *session = [NSURLSession sharedSession]; - NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request - completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { - - if (error) { - - NSLog(@"%@", error); - - } else { - - NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response; - - NSLog(@"%@", httpResponse); - - } - - }]; - - [dataTask resume]; - ``` - - ```python Python lines - import http.client - conn = http.client.HTTPConnection("") - headers = { 'authorization': "Bearer YOUR_ACCESS_TOKEN_HERE" } - conn.request("get", "/dev-gja8kxz4ndtex3rq.us.auth0.com/api_path", headers=headers) - res = conn.getresponse() - data = res.read() - print(data.decode("utf-8")) - ``` - - ```ruby Ruby lines - require 'uri' - require 'net/http' - url = URI("http:///%7ByourDomain%7D/api_path") - http = Net::HTTP.new(url.host, url.port) - request = Net::HTTP::Get.new(url) - request["authorization"] = 'Bearer YOUR_ACCESS_TOKEN_HERE' - response = http.request(request) - puts response.read_body - ``` - - ```swift Swift lines - import Foundation - let headers = ["authorization": "Bearer YOUR_ACCESS_TOKEN_HERE"] - let request = NSMutableURLRequest(url: NSURL(string: "http:///%7ByourDomain%7D/api_path")! as URL, - cachePolicy: .useProtocolCachePolicy, - - timeoutInterval: 10.0) - - request.httpMethod = "get" - request.allHTTPHeaderFields = headers - let session = URLSession.shared - let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in - if (error != nil) { - print(error) - - } else { - let httpResponse = response as? HTTPURLResponse - - print(httpResponse) - - } - }) - dataTask.resume() - ``` - - - - - ##### Point de contrôle - Maintenant que vous avez configuré votre application, lancez votre application et vérifiez que : - `GET /api/public` est disponible pour les demandes non authentifiées. - `GET /api/private` est disponible pour les demandes authentifiées. - `GET /api/private-scoped` est disponible pour les demandes authentifiées contenant un jeton d’accès avec la permission `read:messages`. - -
- - ## Étapes suivantes - - Beau travail! Si vous en êtes arrivé là, vous devriez avoir la connexion, la déconnexion et les informations de profil utilisateur actives dans votre application. - - Cela conclut notre tutoriel de démarrage rapide, mais il y a tellement plus à explorer. Pour en savoir plus sur ce que vous pouvez faire avec Auth0, consultez : - - * [Auth0 Dashboard](https://manage.auth0.com/#) : apprenez à configurer et gérer votre locataire et vos applications Auth0 - * [Trousse SDK go-jwt-middleware](https://github.com/auth0/go-jwt-middleware) : explorez en détail la trousse SDK utilisée dans ce tutoriel - * [Auth0 Marketplace](https://marketplace.auth0.com/) : découvrez des intégrations que vous pouvez activer pour étendre les fonctionnalités d’Auth0 -
- - - - - - - - - - - - - - - - - -
- - - - - -
- - - - - - +--- +title: "Ajouter une autorisation à votre application Go" +permalink: "interactive" +'description': "Ce tutoriel explique comment ajouter une autorisation à une API Go." +'og:title': "Ajouter une autorisation à votre application Go" +'og:description': "Ce tutoriel explique comment ajouter une autorisation à une API Go." +'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/golang.png" +'twitter:title': "Ajouter une autorisation à votre application Go" +'twitter:description': "Ce tutoriel explique comment ajouter une autorisation à une API Go." +sidebarTitle: Go API +--- + +import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; +import { LoggedInForm } from "/snippets/Login.jsx"; +import Jwt from "/snippets/quickstart/backend/golang/jwt.go.mdx"; +import Main from "/snippets/quickstart/backend/golang/main.go.mdx"; + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + +export const sections = [ + { id: "définir-les-autorisations", title: "Définir les autorisations" }, + { id: "installer-les-dépendances", title: "Installer les dépendances" }, + { id: "configuration-de-votre-application", title: "Configuration de votre application" }, + { id: "créer-un-logiciel-médiateur-pour-valider-les-jetons-d-accès", title: "Créer un logiciel médiateur pour valider les jetons d’accès" }, + { id: "protéger-les-points-de-terminaison-des-api", title: "Protéger les points de terminaison des API" } +] + + + + Ce guide explique comment intégrer Auth0 à n’importe quelle application API Go, nouvelle ou ancienne, en utilisant le package [go-jwt-middleware](https://github.com/auth0/go-jwt-middleware). + + Si vous n’avez pas encore créé d’API dans votre Auth0 Dashboard, vous pouvez utiliser le sélecteur interactif pour créer une nouvelle API Auth0 ou sélectionner une API existante pour votre projet. + + Pour configurer votre première API via Auth0 Dashboard, consultez notre guide de démarrage. + + Chaque API Auth0 utilise l’identificateur API, dont votre application a besoin pour valider le jeton d’accès. + + + **Vous ne connaissez pas Auth0 ?** Découvrez Auth0 et l’implémentation de l’authentification et de l’autorisation d’API en utilisant le cadre d’applications OAuth 2.0. + + +
+ Les autorisations vous permettent de définir comment les ressources peuvent être accessibles au nom de l’utilisateur avec un jeton d’accès donné. Par exemple, vous pouvez choisir d’accorder un accès en lecture à la ressource `messages` si les utilisateurs ont le niveau d’accès gestionnaire et un accès en écriture à cette ressource s’ils ont le niveau d’accès administrateur. + + Vous pouvez définir les autorisations autorisées dans la vue **Permissions (Autorisations)** de la section [API](https://manage.auth0.com/#/apis) d’Auth0 Dashboard. L’exemple suivant utilise la permission `read:messages`. + + ![Auth0 Dashboard> Applications > APIs (API) > [Specific API (API précise)] > Onglet Permissions (Autorisations)](/docs/images/fr-ca/cdy7uua7fh8z/1s3Yp5zqJiKiSWqbPSezNO/677a3405b2853f5fdf9e42f6e83ceba7/Quickstarts_API_-_French.png) +
+ +
+ Ajoutez un fichier `go.mod` pour répertorier toutes les dépendances nécessaires. + + ``` + // go.mod + module 01-Authorization-RS256 + go 1.21 + require ( + github.com/auth0/go-jwt-middleware/v2 v2.2.0 + + github.com/joho/godotenv v1.5.1 + + ) + ``` + + Téléchargez les dépendances en exécutant la commande shell suivante : + + ``` + go mod download + ``` +
+ +
+ Créez un fichier `.env` à la racine de votre répertoire de projet pour stocker la configuration de l’application. Renseignez ensuite les variables d’environnement : + + ``` + # The URL of our Auth0 Tenant Domain. + If you're using a Custom Domain, be sure to set this to that value instead. + AUTH0_DOMAIN='{yourDomain}' + Our Auth0 API's Identifier. + AUTH0_AUDIENCE='{yourApiIdentifier}' + ``` +
+ +
+ La fonction de logiciel médiateur `EnsureValidToken` valide le jeton d’accès. Vous pouvez appliquer cette fonction à tous les points de terminaison que vous souhaitez protéger. Si le jeton est valide, le point de terminaison libère les ressources. Si le jeton n’est pas valide, l’API renvoie une erreur `401 Authorization (Autorisation 401)`. + + Configurez le logiciel médiateur **go-jwt-middleware** pour vérifier les jetons d’accès des demandes entrantes. + + Par défaut, votre API sera configurée pour utiliser RS256 comme algorithme de signature des jetons. Puisque RS256 fonctionne en utilisant une paire de clés privée/publique, les jetons peuvent être vérifiés par rapport à la clé publique pour votre compte Auth0. Cette clé publique est accessible à [https://{yourDomain}/.well-known/jwks.json](https://%7Byourdomain%7D/.well-known/jwks.json). + + Inclure un mécanisme pour vérifier que le jeton a une **scope (permission)** suffisante pour accéder aux ressources demandées. + + Créer une fonction `HasScope` pour vérifier et s’assurer que le jeton d’accès a la bonne permission avant de renvoyer une réponse réussie. +
+ +
+ Dans cet exemple, vous allez créer un point de terminaison `/api/public` qui n’utilise pas le logiciel médiateur `EnsureToken` car il est accessible aux requêtes non authentifiées. + + Créez un point de terminaison `/api/private` qui nécessite le logiciel médiateur `EnsureToken` car il n’est disponible que pour les requêtes authentifiées contenant un jeton d’accès, sans permission supplémentaire. + + Créez un point de terminaison `/api/private` qui nécessite le logiciel médiateur `EnsureToken` et `HasScope` car il n’est disponible que pour les requêtes authentifiées contenant un jeton d’accès dont la permission `read:messages` est accordée. + + + Seule la portée `read:messages` est vérifiée par la fonction `HasScope`. Vous pouvez l’étendre ou en faire un logiciel médiateur autonome qui accepte plusieurs permissions pour s’adapter à votre cas d’utilisation. + + + ### Faire un appel à votre API + + Pour appeler votre API, vous avez besoin d’un jeton d’accès. Vous pouvez obtenir un jeton d’accès à des fins de test dans la vue **Test** dans vos [API settings (Paramètres API)](https://manage.auth0.com/#/apis). + + ![Auth0 Dashboard> Applications > API > [API specifique] > Onglet Test](/docs/images/fr-ca/cdy7uua7fh8z/6jeVBuypOGX5qMRXeJn5ow/8aa621c6d95e3f21115493a19ab05f7a/Quickstart_Example_App_-_API.png) + + Fournissez le Jeton d’accès comme un en-tête `Authorization (Autorisation)` dans vos requêtes. + + + ```bash cURL lines + curl --request get \ + --url 'http:///%7ByourDomain%7D/api_path' \ + --header 'authorization: Bearer YOUR_ACCESS_TOKEN_HERE' + ``` + + ```csharp C# lines + var client = new RestClient("http:///%7ByourDomain%7D/api_path"); + var request = new RestRequest(Method.GET); + request.AddHeader("authorization", "Bearer YOUR_ACCESS_TOKEN_HERE"); + IRestResponse response = client.Execute(request); + ``` + + ```go Go lines + package main + import ( + "fmt" + "net/http" + "io/ioutil" + ) + func main() { + url := "http:///%7ByourDomain%7D/api_path" + req, _ := http.NewRequest("get", url, nil) + req.Header.Add("authorization", "Bearer YOUR_ACCESS_TOKEN_HERE") + res, _ := http.DefaultClient.Do(req) + defer res.Body.Close() + body, _ := ioutil.ReadAll(res.Body) + fmt.Println(res) + fmt.Println(string(body)) + } + ``` + + ```java Java lines + HttpResponse response = Unirest.get("http:///%7ByourDomain%7D/api_path") + .header("authorization", "Bearer YOUR_ACCESS_TOKEN_HERE") + .asString(); + ``` + + ```javascript Node.JS lines + var axios = require("axios").default; + var options = { + method: 'get', + url: 'http:///%7ByourDomain%7D/api_path', + headers: {authorization: 'Bearer YOUR_ACCESS_TOKEN_HERE'} + }; + axios.request(options).then(function (response) { + console.log(response.data); + }).catch(function (error) { + console.error(error); + }); + ``` + + ```obj-c Obj-C lines + #import + NSDictionary *headers = @{ @"authorization": @"Bearer YOUR_ACCESS_TOKEN_HERE" }; + NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http:///%7ByourDomain%7D/api_path"] + cachePolicy:NSURLRequestUseProtocolCachePolicy + + timeoutInterval:10.0]; + + [request setHTTPMethod:@"get"]; + [request setAllHTTPHeaderFields:headers]; + NSURLSession *session = [NSURLSession sharedSession]; + NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request + completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { + + if (error) { + + NSLog(@"%@", error); + + } else { + + NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response; + + NSLog(@"%@", httpResponse); + + } + + }]; + + [dataTask resume]; + ``` + + ```php PHP lines + #import + NSDictionary *headers = @{ @"authorization": @"Bearer YOUR_ACCESS_TOKEN_HERE" }; + NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http:///%7ByourDomain%7D/api_path"] + cachePolicy:NSURLRequestUseProtocolCachePolicy + + timeoutInterval:10.0]; + + [request setHTTPMethod:@"get"]; + [request setAllHTTPHeaderFields:headers]; + NSURLSession *session = [NSURLSession sharedSession]; + NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request + completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { + + if (error) { + + NSLog(@"%@", error); + + } else { + + NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response; + + NSLog(@"%@", httpResponse); + + } + + }]; + + [dataTask resume]; + ``` + + ```python Python lines + import http.client + conn = http.client.HTTPConnection("") + headers = { 'authorization': "Bearer YOUR_ACCESS_TOKEN_HERE" } + conn.request("get", "/dev-gja8kxz4ndtex3rq.us.auth0.com/api_path", headers=headers) + res = conn.getresponse() + data = res.read() + print(data.decode("utf-8")) + ``` + + ```ruby Ruby lines + require 'uri' + require 'net/http' + url = URI("http:///%7ByourDomain%7D/api_path") + http = Net::HTTP.new(url.host, url.port) + request = Net::HTTP::Get.new(url) + request["authorization"] = 'Bearer YOUR_ACCESS_TOKEN_HERE' + response = http.request(request) + puts response.read_body + ``` + + ```swift Swift lines + import Foundation + let headers = ["authorization": "Bearer YOUR_ACCESS_TOKEN_HERE"] + let request = NSMutableURLRequest(url: NSURL(string: "http:///%7ByourDomain%7D/api_path")! as URL, + cachePolicy: .useProtocolCachePolicy, + + timeoutInterval: 10.0) + + request.httpMethod = "get" + request.allHTTPHeaderFields = headers + let session = URLSession.shared + let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in + if (error != nil) { + print(error) + + } else { + let httpResponse = response as? HTTPURLResponse + + print(httpResponse) + + } + }) + dataTask.resume() + ``` + + + + + ##### Point de contrôle + Maintenant que vous avez configuré votre application, lancez votre application et vérifiez que : + `GET /api/public` est disponible pour les demandes non authentifiées. + `GET /api/private` est disponible pour les demandes authentifiées. + `GET /api/private-scoped` est disponible pour les demandes authentifiées contenant un jeton d’accès avec la permission `read:messages`. + +
+ + ## Étapes suivantes + + Beau travail! Si vous en êtes arrivé là, vous devriez avoir la connexion, la déconnexion et les informations de profil utilisateur actives dans votre application. + + Cela conclut notre tutoriel de démarrage rapide, mais il y a tellement plus à explorer. Pour en savoir plus sur ce que vous pouvez faire avec Auth0, consultez : + + * [Auth0 Dashboard](https://manage.auth0.com/#) : apprenez à configurer et gérer votre locataire et vos applications Auth0 + * [Trousse SDK go-jwt-middleware](https://github.com/auth0/go-jwt-middleware) : explorez en détail la trousse SDK utilisée dans ce tutoriel + * [Auth0 Marketplace](https://marketplace.auth0.com/) : découvrez des intégrations que vous pouvez activer pour étendre les fonctionnalités d’Auth0 +
+ + + + + + + + + + + + + + + + + +
+ + + + + +
+ + + + + + diff --git a/main/docs/fr-ca/quickstart/backend/java-spring-security5/interactive.mdx b/main/docs/fr-ca/quickstart/backend/java-spring-security5/interactive.mdx index 5869f514a..7aea33acd 100644 --- a/main/docs/fr-ca/quickstart/backend/java-spring-security5/interactive.mdx +++ b/main/docs/fr-ca/quickstart/backend/java-spring-security5/interactive.mdx @@ -1,225 +1,227 @@ ---- -title: "Ajouter l’autorisation à votre application Spring Boot" -permalink: "interactive" -'description': "Ce guide explique comment intégrer Auth0 à n’importe quelle application Spring Boot, nouvelle ou ancienne." -'og:title': "Ajouter l’autorisation à votre application Spring Boot" -'og:description': "Ce guide explique comment intégrer Auth0 à n’importe quelle application Spring Boot, nouvelle ou ancienne." -'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/java.png" -'twitter:title': "Ajouter l’autorisation à votre application Spring Boot" -'twitter:description': "Ce guide explique comment intégrer Auth0 à n’importe quelle application Spring Boot, nouvelle ou ancienne." -sidebarTitle: Spring Boot API ---- - -import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; -import { LoggedInForm } from "/snippets/Login.jsx"; -import Application from "/snippets/quickstart/backend/java-spring-security5/application.yml.mdx"; -import Securityconfig from "/snippets/quickstart/backend/java-spring-security5/SecurityConfig.java.mdx"; -import Apicontroller from "/snippets/quickstart/backend/java-spring-security5/APIController.java.mdx"; - -export const sections = [ - { id: "définir-les-autorisations", title: "Définir les autorisations" }, - { id: "configurer-l-exemple-de-projet", title: "Configurer l’exemple de projet" }, - { id: "installer-les-dépendances", title: "Installer les dépendances" }, - { id: "configurer-le-serveur-de-ressources", title: "Configurer le serveur de ressources" }, - { id: "créer-l-objet-de-domaine", title: "Créer l’objet de domaine" }, - { id: "créer-le-contrôleur-d-api", title: "Créer le contrôleur d’API" }, - { id: "exécuter-l-application", title: "Exécuter l’application" } -] - - - - Auth0 vous permet d’ajouter rapidement une autorisation à votre application. Ce guide explique comment intégrer Auth0 à n’importe quelle application Spring Boot, nouvelle ou ancienne. - - Si vous n’avez pas encore créé d’API dans votre Auth0 Dashboard, vous pouvez utiliser le sélecteur interactif pour créer une nouvelle API Auth0 ou sélectionner une API existante qui représente le projet avec lequel vous souhaitez vous intégrer. - - Consultez [notre guide de démarrage](https://auth0.com/docs/get-started/auth0-overview/set-up-apis) pour configurer votre première API via Auth0 Dashboard. - - Chaque API Auth0 utilise l’identificateur API, dont votre application a besoin pour valider le jeton d’accès. - - - **Vous ne connaissez pas Auth0?** Découvrez [Auth0](https://auth0.com/docs/overview) et [l’implémentation de l’authentification et de l’autorisation d’API](https://auth0.com/docs/api-auth) en utilisant le cadre d’applications OAuth 2.0. - - -
- Les autorisations vous permettent de définir comment les ressources peuvent être accessibles au nom de l’utilisateur avec un jeton d’accès donné. Par exemple, vous pouvez choisir d’accorder un accès en lecture à la ressource `messages` si les utilisateurs ont le niveau d’accès gestionnaire et un accès en écriture à cette ressource s’ils ont le niveau d’accès administrateur. - - Vous pouvez définir les autorisations autorisées dans la vue **Permissions (Autorisations)** de la section [API](https://manage.auth0.com/dashboard/us/dev-1-2s2aq0/apis) d’Auth0 Dashboard. - - ![Auth0 Dashboard> Applications > APIs (API) > [Specific API (API précise)] > Onglet Permissions (Autorisations)](/docs/images/fr-ca/cdy7uua7fh8z/1s3Yp5zqJiKiSWqbPSezNO/677a3405b2853f5fdf9e42f6e83ceba7/Quickstarts_API_-_French.png) - - - Cet exemple utilise la permission `read:messages`. - -
- -
- L’exemple de projet utilise un fichier `/src/main/resources/application.yml`, qui le configure pour utiliser le **domaine** et l’**identificateur API** Auth0 corrects pour votre API. Si vous téléchargez le code à partir de cette page, il sera automatiquement configuré. En revanche, si vous clonez l’exemple à partir de GitHub, vous devrez le remplir manuellement. -
- -
- Si vous utilisez Gradle, vous pouvez ajouter les dépendances nécessaires en utilisant le [plugiciel Gradle de Spring Boot](https://docs.spring.io/spring-boot/docs/current/gradle-plugin/reference/html/) et le [plugiciel de gestion des dépendances](https://docs.spring.io/dependency-management-plugin/docs/current/reference/html/) pour résoudre les problèmes de versions de dépendances : - - ``` - // build.gradle - plugins { - - id 'java' - - id 'org.springframework.boot' - - version '3.1.5' - - id 'io.spring.dependency-management' - - version '1.1.3' - - } - - dependencies { - - implementation 'org.springframework.boot:spring-boot-starter-web' - - implementation 'com.okta.spring:okta-spring-boot-starter:3.0.5' - - } - ``` - - Si vous utilisez Maven, ajoutez les dépendances Spring à votre fichier `pom.xml` : - - ```xml - // pom.xml - - org.springframework.boot - spring-boot-starter-parent - 3.1.5 - - - - - org.springframework.boot - spring-boot-starter-web - - - com.okta.spring - okta-spring-boot-starter - 3.0.5 - - - ``` -
- -
- Pour configurer l’application en tant que serveur de ressources et valider les JWT, créez une classe qui fournira une instance `SecurityFilterChain` et ajoutez l’annotation `@Configuration`. - - ### Protéger les points de terminaison des API - - Les routes ci-dessous sont disponibles pour les demandes suivantes : - - - `GET /api/public` : disponible pour les demandes non authentifiées - - `GET /api/private` : disponible pour les demandes authentifiées contenant un jeton d’accès sans permission supplémentaire - - `GET /api/private-scoped` : disponible pour les demandes authentifiées contenant un jeton d’accès dont la permission `read:messages` est accordée - - L’exemple ci-dessous montre comment sécuriser les méthodes de l’API à l’aide de l’objet `HttpSecurity` fourni dans la méthode `filterChain()` de la classe `SecurityConfig`. Les adaptateurs de routes limitent l’accès en fonction du niveau d’autorisation requis. - - - Par défaut, Spring Security crée une `GrantedAuthority` pour chaque permission dans la demande `scope` du JWT. Cette permission permet d’utiliser la méthode `hasAuthority("SCOPE\_read:messages")` pour restreindre l’accès à un JWT valide qui contient la permission `read:messages`. - -
- -
- Pour que votre point de terminaison renvoie un objet JSON, utilisez un enregistrement Java. Les variables membres de cet objet sont sérialisées dans la valeur clé de votre objet JSON. Créez un nouvel enregistrement appelé `Message` comme exemple d’objet de domaine à renvoyer lors des appels à l’API. -
- -
- Créez une nouvelle classe appelée `APIController` pour gérer les demandes vers les points de terminaison. L’`APIController` possède trois routes définies dans la section [Protéger les points de terminaison des API](https://auth0.com/docs/quickstart/backend/java-spring-security5/interactive#configure-the-resource-server). Dans cet exemple, toutes les origines sont autorisées par l’annotation `@CrossOrigin`. Les applications réelles doivent configurer `CORS` en fonction de leur cas d’utilisation. -
- -
- Pour développer et exécuter le projet exemple, exécutez la tâche Gradle `bootRun`. - - Linux ou macOS : - - `./gradlew bootRun` - - Windows : - - `gradlew.bat bootRun` - - Si vous configurez votre propre application en utilisant Maven et le plugiciel [Spring Boot Maven Plugin](https://docs.spring.io/spring-boot/docs/current/reference/html/build-tool-plugins-maven-plugin.html), vous pouvez exécuter l’objectif `spring-boot:run`. - - Linux ou macOS : - - `mvn spring-boot:run` - - Windows : - - `mvn.cmd spring-boot:run` - - - ##### Point de contrôle - L’exemple d’application sera accessible à l’adresse `http://localhost:3010/`. Pour en savoir plus sur la manière de tester et d’utiliser votre API, consultez [Utiliser votre API](https://auth0.com/docs/quickstart/backend/java-spring-security5/02-using). - -
- - ## Étapes suivantes - - Beau travail! Si vous en êtes arrivé là, vous devriez avoir la connexion, la déconnexion et les informations de profil utilisateur actives dans votre application. - - Cela conclut notre tutoriel de démarrage rapide, mais il y a tellement plus à explorer. Pour en savoir plus sur ce que vous pouvez faire avec Auth0, consultez : - - * [Auth0 Dashboard](https://manage.auth0.com/#) : apprenez à configurer et gérer votre locataire et vos applications Auth0 - * [Trousse SDK Okta Spring Boot Starter](https://github.com/okta/okta-spring-boot/) : explorez en détail la trousse SDK utilisée dans ce tutoriel - * [Auth0 Marketplace](https://marketplace.auth0.com/) : découvrez des intégrations que vous pouvez activer pour étendre les fonctionnalités d’Auth0 -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+--- +title: "Ajouter l’autorisation à votre application Spring Boot" +permalink: "interactive" +'description': "Ce guide explique comment intégrer Auth0 à n’importe quelle application Spring Boot, nouvelle ou ancienne." +'og:title': "Ajouter l’autorisation à votre application Spring Boot" +'og:description': "Ce guide explique comment intégrer Auth0 à n’importe quelle application Spring Boot, nouvelle ou ancienne." +'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/java.png" +'twitter:title': "Ajouter l’autorisation à votre application Spring Boot" +'twitter:description': "Ce guide explique comment intégrer Auth0 à n’importe quelle application Spring Boot, nouvelle ou ancienne." +sidebarTitle: Spring Boot API +--- + +import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; +import { LoggedInForm } from "/snippets/Login.jsx"; +import Application from "/snippets/quickstart/backend/java-spring-security5/application.yml.mdx"; +import Securityconfig from "/snippets/quickstart/backend/java-spring-security5/SecurityConfig.java.mdx"; +import Apicontroller from "/snippets/quickstart/backend/java-spring-security5/APIController.java.mdx"; + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + +export const sections = [ + { id: "définir-les-autorisations", title: "Définir les autorisations" }, + { id: "configurer-l-exemple-de-projet", title: "Configurer l’exemple de projet" }, + { id: "installer-les-dépendances", title: "Installer les dépendances" }, + { id: "configurer-le-serveur-de-ressources", title: "Configurer le serveur de ressources" }, + { id: "créer-l-objet-de-domaine", title: "Créer l’objet de domaine" }, + { id: "créer-le-contrôleur-d-api", title: "Créer le contrôleur d’API" }, + { id: "exécuter-l-application", title: "Exécuter l’application" } +] + + + + Auth0 vous permet d’ajouter rapidement une autorisation à votre application. Ce guide explique comment intégrer Auth0 à n’importe quelle application Spring Boot, nouvelle ou ancienne. + + Si vous n’avez pas encore créé d’API dans votre Auth0 Dashboard, vous pouvez utiliser le sélecteur interactif pour créer une nouvelle API Auth0 ou sélectionner une API existante qui représente le projet avec lequel vous souhaitez vous intégrer. + + Consultez [notre guide de démarrage](https://auth0.com/docs/get-started/auth0-overview/set-up-apis) pour configurer votre première API via Auth0 Dashboard. + + Chaque API Auth0 utilise l’identificateur API, dont votre application a besoin pour valider le jeton d’accès. + + + **Vous ne connaissez pas Auth0?** Découvrez [Auth0](https://auth0.com/docs/overview) et [l’implémentation de l’authentification et de l’autorisation d’API](https://auth0.com/docs/api-auth) en utilisant le cadre d’applications OAuth 2.0. + + +
+ Les autorisations vous permettent de définir comment les ressources peuvent être accessibles au nom de l’utilisateur avec un jeton d’accès donné. Par exemple, vous pouvez choisir d’accorder un accès en lecture à la ressource `messages` si les utilisateurs ont le niveau d’accès gestionnaire et un accès en écriture à cette ressource s’ils ont le niveau d’accès administrateur. + + Vous pouvez définir les autorisations autorisées dans la vue **Permissions (Autorisations)** de la section [API](https://manage.auth0.com/dashboard/us/dev-1-2s2aq0/apis) d’Auth0 Dashboard. + + ![Auth0 Dashboard> Applications > APIs (API) > [Specific API (API précise)] > Onglet Permissions (Autorisations)](/docs/images/fr-ca/cdy7uua7fh8z/1s3Yp5zqJiKiSWqbPSezNO/677a3405b2853f5fdf9e42f6e83ceba7/Quickstarts_API_-_French.png) + + + Cet exemple utilise la permission `read:messages`. + +
+ +
+ L’exemple de projet utilise un fichier `/src/main/resources/application.yml`, qui le configure pour utiliser le **domaine** et l’**identificateur API** Auth0 corrects pour votre API. Si vous téléchargez le code à partir de cette page, il sera automatiquement configuré. En revanche, si vous clonez l’exemple à partir de GitHub, vous devrez le remplir manuellement. +
+ +
+ Si vous utilisez Gradle, vous pouvez ajouter les dépendances nécessaires en utilisant le [plugiciel Gradle de Spring Boot](https://docs.spring.io/spring-boot/docs/current/gradle-plugin/reference/html/) et le [plugiciel de gestion des dépendances](https://docs.spring.io/dependency-management-plugin/docs/current/reference/html/) pour résoudre les problèmes de versions de dépendances : + + ``` + // build.gradle + plugins { + + id 'java' + + id 'org.springframework.boot' + + version '3.1.5' + + id 'io.spring.dependency-management' + + version '1.1.3' + + } + + dependencies { + + implementation 'org.springframework.boot:spring-boot-starter-web' + + implementation 'com.okta.spring:okta-spring-boot-starter:3.0.5' + + } + ``` + + Si vous utilisez Maven, ajoutez les dépendances Spring à votre fichier `pom.xml` : + + ```xml + // pom.xml + + org.springframework.boot + spring-boot-starter-parent + 3.1.5 + + + + + org.springframework.boot + spring-boot-starter-web + + + com.okta.spring + okta-spring-boot-starter + 3.0.5 + + + ``` +
+ +
+ Pour configurer l’application en tant que serveur de ressources et valider les JWT, créez une classe qui fournira une instance `SecurityFilterChain` et ajoutez l’annotation `@Configuration`. + + ### Protéger les points de terminaison des API + + Les routes ci-dessous sont disponibles pour les demandes suivantes : + + - `GET /api/public` : disponible pour les demandes non authentifiées + - `GET /api/private` : disponible pour les demandes authentifiées contenant un jeton d’accès sans permission supplémentaire + - `GET /api/private-scoped` : disponible pour les demandes authentifiées contenant un jeton d’accès dont la permission `read:messages` est accordée + + L’exemple ci-dessous montre comment sécuriser les méthodes de l’API à l’aide de l’objet `HttpSecurity` fourni dans la méthode `filterChain()` de la classe `SecurityConfig`. Les adaptateurs de routes limitent l’accès en fonction du niveau d’autorisation requis. + + + Par défaut, Spring Security crée une `GrantedAuthority` pour chaque permission dans la demande `scope` du JWT. Cette permission permet d’utiliser la méthode `hasAuthority("SCOPE\_read:messages")` pour restreindre l’accès à un JWT valide qui contient la permission `read:messages`. + +
+ +
+ Pour que votre point de terminaison renvoie un objet JSON, utilisez un enregistrement Java. Les variables membres de cet objet sont sérialisées dans la valeur clé de votre objet JSON. Créez un nouvel enregistrement appelé `Message` comme exemple d’objet de domaine à renvoyer lors des appels à l’API. +
+ +
+ Créez une nouvelle classe appelée `APIController` pour gérer les demandes vers les points de terminaison. L’`APIController` possède trois routes définies dans la section [Protéger les points de terminaison des API](https://auth0.com/docs/quickstart/backend/java-spring-security5/interactive#configure-the-resource-server). Dans cet exemple, toutes les origines sont autorisées par l’annotation `@CrossOrigin`. Les applications réelles doivent configurer `CORS` en fonction de leur cas d’utilisation. +
+ +
+ Pour développer et exécuter le projet exemple, exécutez la tâche Gradle `bootRun`. + + Linux ou macOS : + + `./gradlew bootRun` + + Windows : + + `gradlew.bat bootRun` + + Si vous configurez votre propre application en utilisant Maven et le plugiciel [Spring Boot Maven Plugin](https://docs.spring.io/spring-boot/docs/current/reference/html/build-tool-plugins-maven-plugin.html), vous pouvez exécuter l’objectif `spring-boot:run`. + + Linux ou macOS : + + `mvn spring-boot:run` + + Windows : + + `mvn.cmd spring-boot:run` + + + ##### Point de contrôle + L’exemple d’application sera accessible à l’adresse `http://localhost:3010/`. Pour en savoir plus sur la manière de tester et d’utiliser votre API, consultez [Utiliser votre API](https://auth0.com/docs/quickstart/backend/java-spring-security5/02-using). + +
+ + ## Étapes suivantes + + Beau travail! Si vous en êtes arrivé là, vous devriez avoir la connexion, la déconnexion et les informations de profil utilisateur actives dans votre application. + + Cela conclut notre tutoriel de démarrage rapide, mais il y a tellement plus à explorer. Pour en savoir plus sur ce que vous pouvez faire avec Auth0, consultez : + + * [Auth0 Dashboard](https://manage.auth0.com/#) : apprenez à configurer et gérer votre locataire et vos applications Auth0 + * [Trousse SDK Okta Spring Boot Starter](https://github.com/okta/okta-spring-boot/) : explorez en détail la trousse SDK utilisée dans ce tutoriel + * [Auth0 Marketplace](https://marketplace.auth0.com/) : découvrez des intégrations que vous pouvez activer pour étendre les fonctionnalités d’Auth0 +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
diff --git a/main/docs/fr-ca/quickstart/backend/nodejs/interactive.mdx b/main/docs/fr-ca/quickstart/backend/nodejs/interactive.mdx index 0df8c1031..0c8e7716b 100644 --- a/main/docs/fr-ca/quickstart/backend/nodejs/interactive.mdx +++ b/main/docs/fr-ca/quickstart/backend/nodejs/interactive.mdx @@ -15,6 +15,8 @@ import { LoggedInForm } from "/snippets/Login.jsx"; import Server from "/snippets/quickstart/backend/nodejs/server.js.mdx"; import Server2 from "/snippets/quickstart/backend/nodejs/server.js2.mdx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + export const sections = [ { id: "définir-les-autorisations", title: "Définir les autorisations" }, { id: "installer-les-dépendances", title: "Installer les dépendances" }, @@ -79,7 +81,7 @@ export const sections = [ Fournir le Jeton d’accès comme un en-tête `Authorization` dans vos demandes. - + ```bash cURL lines curl --request get \ --url 'http:///%7ByourDomain%7D/api_path' \ @@ -239,7 +241,7 @@ export const sections = [ }) dataTask.resume() ``` - + diff --git a/main/docs/fr-ca/quickstart/backend/php/interactive.mdx b/main/docs/fr-ca/quickstart/backend/php/interactive.mdx index 2e730826c..0b5a493d7 100644 --- a/main/docs/fr-ca/quickstart/backend/php/interactive.mdx +++ b/main/docs/fr-ca/quickstart/backend/php/interactive.mdx @@ -1,171 +1,173 @@ ---- -title: "Ajouter une autorisation à votre application PHP" -permalink: "interactive" -'description': "Ce guide explique comment intégrer Auth0, ajouter une autorisation basée sur un jeton et protéger les routes de l’application en utilisant la trousse SDK Auth0 pour PHP." -'og:title': "Ajouter une autorisation à votre application PHP" -'og:description': "Ce guide explique comment intégrer Auth0, ajouter une autorisation basée sur un jeton et protéger les routes de l’application en utilisant la trousse SDK Auth0 pour PHP." -'og:image': "/docs/media/platforms/php.png" -'twitter:title': "Ajouter une autorisation à votre application PHP" -'twitter:description': "Ce guide explique comment intégrer Auth0, ajouter une autorisation basée sur un jeton et protéger les routes de l’application en utilisant la trousse SDK Auth0 pour PHP." -sidebarTitle: PHP API ---- - -import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; -import { LoggedInForm } from "/snippets/Login.jsx"; -import Index from "/snippets/quickstart/backend/php/index.php.mdx"; -import Index2 from "/snippets/quickstart/backend/php/index.php2.mdx"; -import Router from "/snippets/quickstart/backend/php/router.php.mdx"; -import Router2 from "/snippets/quickstart/backend/php/router.php2.mdx"; -import Router3 from "/snippets/quickstart/backend/php/router.php3.mdx"; - -export const sections = [ - { id: "configuration-d-auth0", title: "Configuration d’Auth0" }, - { id: "installer-la-trousse-sdk-php-auth0", title: "Installer la trousse SDK PHP Auth0" }, - { id: "détecter-les-jetons-du-porteur", title: "Détecter les jetons du porteur" }, - { id: "créer-et-configurer-des-routes", title: "Créer et configurer des routes" }, - { id: "configurer-l-autorisation-des-points-de-terminaison", title: "Configurer l’autorisation des points de terminaison" }, - { id: "autoriser-avec-des-permissions", title: "Autoriser avec des permissions" } -] - - - - Auth0 vous permet d’ajouter rapidement une autorisation de point de terminaison basée sur un jeton à presque tous les types d’application. Ce guide explique comment intégrer Auth0, ajouter une autorisation basée sur un jeton et protéger les routes de l’application en utilisant la trousse SDK Auth0 PHP. - - Pour utiliser ce guide rapide, vous devez : - - - Vous inscrire à un compte Auth0 gratuit ou vous connecter à Auth0. - - Avoir un projet PHP fonctionnel que vous souhaitez intégrer à Auth0. Vous pouvez également consulter ou télécharger une application faisant office d’exemple lorsque vous vous connectez. - -
- Pour utiliser les services Auth0, vous devez avoir une application enregistrée dans Auth0 Dashboard. L’application Auth0 est l’endroit où vous configurez le fonctionnement de l’authentification pour votre projet. - - ### Configurer une application - - Utilisez le sélecteur interactif pour créer une nouvelle application Auth0 ou sélectionnez une application existante qui représente le projet que vous souhaitez intégrer. Dans Auth0, il est attribué à chaque application un identificateur client unique alphanumérique que votre code d’application utilise pour appeler les API Auth0 via la trousse SDK. - - Tous les paramètres que vous configurez à l’aide de ce guide rapide seront automatiquement mis à jour pour votre application dans le [Dashboard](https://manage.auth0.com/#/), qui est l’endroit où vous pourrez gérer vos applications à l’avenir. - - Si vous préférez explorer une configuration complète, consultez plutôt un exemple d’application. - - ### Configurer une API - - De même, vous devez créer une nouvelle API Auth0 ou utiliser une API existante qui représente le projet que vous intégrez à partir du [Dashboard](https://manage.auth0.com/#/). Choisissez un identificateur unique pour l’API et notez-le. Cet identificateur vous sera nécessaire pour configurer votre application ci-dessous. -
- -
- Auth0 fournit une trousse [SDK PHP](https://github.com/auth0/auth0-PHP) (Auth0-PHP) pour simplifier le processus de mise en œuvre de l’authentification et de l’autorisation Auth0 dans les applications PHP. - - La trousse SDK PHP Auth0 nécessite l’installation des bibliothèques HTTP compatibles [PSR-17](https://www.php-fig.org/psr/psr-17/) et [PSR-18](https://www.php-fig.org/psr/psr-18/) pour la gestion des requêtes réseau. Si vous ne disposez pas de bibliothèques disponibles, vous pouvez installer des choix fiables en exécutant les commandes suivantes dans votre terminal : - - ``` - cd - composer require symfony/http-client nyholm/psr7 - ``` - - Installez maintenant la trousse SDK PHP Auth0 en exécutant la commande suivante dans votre terminal : - - ``` - composer require auth0/auth0-php - ``` - - ### Configurer la trousse SDK Auth0 - - Pour que la trousse SDK fonctionne correctement, vous devez définir les propriétés suivantes dans la trousse SDK Auth0 lors de l’initialisation : - - - `strategy` : La stratégie aide à orienter le comportement du SDK en ce qui concerne l’utilisation de votre application. Dans ce cas, vous souhaitez la définir sur la constante - - `Auth0\SDK\Configuration\SdkConfiguration::STRATEGY_API` - - domain : Le domaine de votre locataire Auth0. En général, vous le trouverez dans Auth0 Dashboard dans Application Settings (Paramètres d’application) dans le champ Domain (Domaine). Si vous utilisez un domaine personnalisé, définissez-le plutôt sur la valeur de votre domaine personnalisé. - - clientId : L’identifiant de l’application Auth0 que vous avez configurée précédemment dans le démarrage rapide. Vous pouvez le trouver dans Auth0 Dashboard, dans la rubrique des paramètres de votre application, dans le champ Client ID (ID client). - - clientSecret : Le secret de l’application Auth0 que vous avez créée plus tôt dans le démarrage rapide. Le secret client se trouve dans Auth0 Dashboard, dans Application Settings (Paramètres d’application) dans le champ Client Secret (Secret client). - - public : L’identificateur de l’API Auth0 que vous avez enregistré ci-dessus. Il doit être fourni sous la forme d’un tableau. - - - ##### Point de contrôle - Votre trousse SDK Auth0 est maintenant correctement configurée. Exécutez votre application pour vérifier que : - la trousse SDK s’initialise correctement, - votre application ne génère aucune erreur liée à Auth0. - -
- -
- Développez ensuite votre application pour récupérer et traiter les jetons de porteur. Les jetons de porteur sont des jetons d’accès fournis à votre API avec des demandes de clients au nom d’un utilisateur. Les jetons d’accès approuvent ou refusent l’accès aux routes de votre application. C’est ce que l’on appelle l’autorisation de point de terminaison. - - La méthode la plus simple pour récupérer les jetons d’accès à partir d’une requête est la méthode `getBearerToken()` de la trousse SDK PHP. Cette méthode récupère les jetons à partir des paramètres GET, des corps POST, des en-têtes de requête et d’autres sources. Dans ce cas, la trousse SDK PHP traite les jetons transmis par les requêtes GET dans le paramètre `token` ou dans l’en-tête HTTP `Authorization`. -
- -
- Maintenant, installez une bibliothèque de routage pour aider à diriger les requêtes entrantes vers votre application. Cette étape n’est pas obligatoire, mais elle simplifie la structure de l’application pour les besoins de ce guide rapide. - - ``` - composer require steampixel/simple-php-router - ``` - - Créez un nouveau fichier dans votre application appelé `router.php` pour définir les routes. Copiez le code du panneau interactif à droite sous l’onglet **router.php**. -
- -
- Maintenant que vous avez configuré votre application Auth0, la trousse SDK PHP Auth0, et que votre application récupère les jetons de porteur des requêtes, l’étape suivante est de configurer l’autorisation des points de terminaison pour votre projet. La méthode `getBearerToken()` que vous avez mise en œuvre ci-dessus renvoie une classe `Token` qui contient des informations sur l’accès à la requête. - - Étant donné que la méthode `getBearerToken()` valide et vérifie automatiquement la requête entrante, votre application détermine les détails du jeton d’accès en évaluant la réponse de la méthode. Si la réponse est nulle, c’est qu’aucun jeton valide n’a été fourni. Dans le cas contraire, inspectez le contenu de la réponse pour en savoir plus sur la demande. - - Dans le panneau interactif à droite, une validation de la réponse (null ou non) permet de filtrer l’accès à la route `/api/private`. -
- -
- Dans certains cas, vous pouvez souhaiter filtrer l’accès à une route particulière en fonction des permissions demandées dans un jeton d’accès. Comme le montre le panneau interactif de droite, évaluez le contenu de la propriété ’scope’ de la réponse de la méthode `getBearerToken()` pour vérifier les permissions accordées par le jeton d’accès. -
- - ## Étapes suivantes - - Beau travail! Si vous en êtes arrivé là, vous devriez avoir la connexion, la déconnexion et les informations de profil utilisateur actives dans votre application. - - Cela conclut notre tutoriel de démarrage rapide, mais il y a tellement plus à explorer. Pour en savoir plus sur ce que vous pouvez faire avec Auth0, consultez : - - * [Auth0 Dashboard](https://manage.auth0.com/#) : apprenez à configurer et gérer votre locataire et vos applications Auth0 - * [Trousse SDK Auth0-PHP](https://github.com/auth0/auth0-php) : explorez en détail la trousse SDK utilisée dans ce tutoriel - * [Auth0 Marketplace](https://marketplace.auth0.com/) : découvrez des intégrations que vous pouvez activer pour étendre les fonctionnalités d’Auth0 -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+--- +title: "Ajouter une autorisation à votre application PHP" +permalink: "interactive" +'description': "Ce guide explique comment intégrer Auth0, ajouter une autorisation basée sur un jeton et protéger les routes de l’application en utilisant la trousse SDK Auth0 pour PHP." +'og:title': "Ajouter une autorisation à votre application PHP" +'og:description': "Ce guide explique comment intégrer Auth0, ajouter une autorisation basée sur un jeton et protéger les routes de l’application en utilisant la trousse SDK Auth0 pour PHP." +'og:image': "/docs/media/platforms/php.png" +'twitter:title': "Ajouter une autorisation à votre application PHP" +'twitter:description': "Ce guide explique comment intégrer Auth0, ajouter une autorisation basée sur un jeton et protéger les routes de l’application en utilisant la trousse SDK Auth0 pour PHP." +sidebarTitle: PHP API +--- + +import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; +import { LoggedInForm } from "/snippets/Login.jsx"; +import Index from "/snippets/quickstart/backend/php/index.php.mdx"; +import Index2 from "/snippets/quickstart/backend/php/index.php2.mdx"; +import Router from "/snippets/quickstart/backend/php/router.php.mdx"; +import Router2 from "/snippets/quickstart/backend/php/router.php2.mdx"; +import Router3 from "/snippets/quickstart/backend/php/router.php3.mdx"; + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + +export const sections = [ + { id: "configuration-d-auth0", title: "Configuration d’Auth0" }, + { id: "installer-la-trousse-sdk-php-auth0", title: "Installer la trousse SDK PHP Auth0" }, + { id: "détecter-les-jetons-du-porteur", title: "Détecter les jetons du porteur" }, + { id: "créer-et-configurer-des-routes", title: "Créer et configurer des routes" }, + { id: "configurer-l-autorisation-des-points-de-terminaison", title: "Configurer l’autorisation des points de terminaison" }, + { id: "autoriser-avec-des-permissions", title: "Autoriser avec des permissions" } +] + + + + Auth0 vous permet d’ajouter rapidement une autorisation de point de terminaison basée sur un jeton à presque tous les types d’application. Ce guide explique comment intégrer Auth0, ajouter une autorisation basée sur un jeton et protéger les routes de l’application en utilisant la trousse SDK Auth0 PHP. + + Pour utiliser ce guide rapide, vous devez : + + - Vous inscrire à un compte Auth0 gratuit ou vous connecter à Auth0. + - Avoir un projet PHP fonctionnel que vous souhaitez intégrer à Auth0. Vous pouvez également consulter ou télécharger une application faisant office d’exemple lorsque vous vous connectez. + +
+ Pour utiliser les services Auth0, vous devez avoir une application enregistrée dans Auth0 Dashboard. L’application Auth0 est l’endroit où vous configurez le fonctionnement de l’authentification pour votre projet. + + ### Configurer une application + + Utilisez le sélecteur interactif pour créer une nouvelle application Auth0 ou sélectionnez une application existante qui représente le projet que vous souhaitez intégrer. Dans Auth0, il est attribué à chaque application un identificateur client unique alphanumérique que votre code d’application utilise pour appeler les API Auth0 via la trousse SDK. + + Tous les paramètres que vous configurez à l’aide de ce guide rapide seront automatiquement mis à jour pour votre application dans le [Dashboard](https://manage.auth0.com/#/), qui est l’endroit où vous pourrez gérer vos applications à l’avenir. + + Si vous préférez explorer une configuration complète, consultez plutôt un exemple d’application. + + ### Configurer une API + + De même, vous devez créer une nouvelle API Auth0 ou utiliser une API existante qui représente le projet que vous intégrez à partir du [Dashboard](https://manage.auth0.com/#/). Choisissez un identificateur unique pour l’API et notez-le. Cet identificateur vous sera nécessaire pour configurer votre application ci-dessous. +
+ +
+ Auth0 fournit une trousse [SDK PHP](https://github.com/auth0/auth0-PHP) (Auth0-PHP) pour simplifier le processus de mise en œuvre de l’authentification et de l’autorisation Auth0 dans les applications PHP. + + La trousse SDK PHP Auth0 nécessite l’installation des bibliothèques HTTP compatibles [PSR-17](https://www.php-fig.org/psr/psr-17/) et [PSR-18](https://www.php-fig.org/psr/psr-18/) pour la gestion des requêtes réseau. Si vous ne disposez pas de bibliothèques disponibles, vous pouvez installer des choix fiables en exécutant les commandes suivantes dans votre terminal : + + ``` + cd + composer require symfony/http-client nyholm/psr7 + ``` + + Installez maintenant la trousse SDK PHP Auth0 en exécutant la commande suivante dans votre terminal : + + ``` + composer require auth0/auth0-php + ``` + + ### Configurer la trousse SDK Auth0 + + Pour que la trousse SDK fonctionne correctement, vous devez définir les propriétés suivantes dans la trousse SDK Auth0 lors de l’initialisation : + + - `strategy` : La stratégie aide à orienter le comportement du SDK en ce qui concerne l’utilisation de votre application. Dans ce cas, vous souhaitez la définir sur la constante + + `Auth0\SDK\Configuration\SdkConfiguration::STRATEGY_API` + - domain : Le domaine de votre locataire Auth0. En général, vous le trouverez dans Auth0 Dashboard dans Application Settings (Paramètres d’application) dans le champ Domain (Domaine). Si vous utilisez un domaine personnalisé, définissez-le plutôt sur la valeur de votre domaine personnalisé. + - clientId : L’identifiant de l’application Auth0 que vous avez configurée précédemment dans le démarrage rapide. Vous pouvez le trouver dans Auth0 Dashboard, dans la rubrique des paramètres de votre application, dans le champ Client ID (ID client). + - clientSecret : Le secret de l’application Auth0 que vous avez créée plus tôt dans le démarrage rapide. Le secret client se trouve dans Auth0 Dashboard, dans Application Settings (Paramètres d’application) dans le champ Client Secret (Secret client). + - public : L’identificateur de l’API Auth0 que vous avez enregistré ci-dessus. Il doit être fourni sous la forme d’un tableau. + + + ##### Point de contrôle + Votre trousse SDK Auth0 est maintenant correctement configurée. Exécutez votre application pour vérifier que : + la trousse SDK s’initialise correctement, + votre application ne génère aucune erreur liée à Auth0. + +
+ +
+ Développez ensuite votre application pour récupérer et traiter les jetons de porteur. Les jetons de porteur sont des jetons d’accès fournis à votre API avec des demandes de clients au nom d’un utilisateur. Les jetons d’accès approuvent ou refusent l’accès aux routes de votre application. C’est ce que l’on appelle l’autorisation de point de terminaison. + + La méthode la plus simple pour récupérer les jetons d’accès à partir d’une requête est la méthode `getBearerToken()` de la trousse SDK PHP. Cette méthode récupère les jetons à partir des paramètres GET, des corps POST, des en-têtes de requête et d’autres sources. Dans ce cas, la trousse SDK PHP traite les jetons transmis par les requêtes GET dans le paramètre `token` ou dans l’en-tête HTTP `Authorization`. +
+ +
+ Maintenant, installez une bibliothèque de routage pour aider à diriger les requêtes entrantes vers votre application. Cette étape n’est pas obligatoire, mais elle simplifie la structure de l’application pour les besoins de ce guide rapide. + + ``` + composer require steampixel/simple-php-router + ``` + + Créez un nouveau fichier dans votre application appelé `router.php` pour définir les routes. Copiez le code du panneau interactif à droite sous l’onglet **router.php**. +
+ +
+ Maintenant que vous avez configuré votre application Auth0, la trousse SDK PHP Auth0, et que votre application récupère les jetons de porteur des requêtes, l’étape suivante est de configurer l’autorisation des points de terminaison pour votre projet. La méthode `getBearerToken()` que vous avez mise en œuvre ci-dessus renvoie une classe `Token` qui contient des informations sur l’accès à la requête. + + Étant donné que la méthode `getBearerToken()` valide et vérifie automatiquement la requête entrante, votre application détermine les détails du jeton d’accès en évaluant la réponse de la méthode. Si la réponse est nulle, c’est qu’aucun jeton valide n’a été fourni. Dans le cas contraire, inspectez le contenu de la réponse pour en savoir plus sur la demande. + + Dans le panneau interactif à droite, une validation de la réponse (null ou non) permet de filtrer l’accès à la route `/api/private`. +
+ +
+ Dans certains cas, vous pouvez souhaiter filtrer l’accès à une route particulière en fonction des permissions demandées dans un jeton d’accès. Comme le montre le panneau interactif de droite, évaluez le contenu de la propriété ’scope’ de la réponse de la méthode `getBearerToken()` pour vérifier les permissions accordées par le jeton d’accès. +
+ + ## Étapes suivantes + + Beau travail! Si vous en êtes arrivé là, vous devriez avoir la connexion, la déconnexion et les informations de profil utilisateur actives dans votre application. + + Cela conclut notre tutoriel de démarrage rapide, mais il y a tellement plus à explorer. Pour en savoir plus sur ce que vous pouvez faire avec Auth0, consultez : + + * [Auth0 Dashboard](https://manage.auth0.com/#) : apprenez à configurer et gérer votre locataire et vos applications Auth0 + * [Trousse SDK Auth0-PHP](https://github.com/auth0/auth0-php) : explorez en détail la trousse SDK utilisée dans ce tutoriel + * [Auth0 Marketplace](https://marketplace.auth0.com/) : découvrez des intégrations que vous pouvez activer pour étendre les fonctionnalités d’Auth0 +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
diff --git a/main/docs/fr-ca/quickstart/backend/python/interactive.mdx b/main/docs/fr-ca/quickstart/backend/python/interactive.mdx index 8adbc590e..49fc485ec 100644 --- a/main/docs/fr-ca/quickstart/backend/python/interactive.mdx +++ b/main/docs/fr-ca/quickstart/backend/python/interactive.mdx @@ -1,293 +1,295 @@ ---- -title: "Ajouter une autorisation à votre application API Flask" -permalink: "interactive" -'description': "Ce guide explique comment intégrer Auth0 à n’importe quelle API Python, nouvelle ou ancienne, développée avec Flask." -'og:title': "Ajouter une autorisation à votre application API Flask" -'og:description': "Ce guide explique comment intégrer Auth0 à n’importe quelle API Python, nouvelle ou ancienne, développée avec Flask." -'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/python.png" -'twitter:title': "Ajouter une autorisation à votre application API Flask" -'twitter:description': "Ce guide explique comment intégrer Auth0 à n’importe quelle API Python, nouvelle ou ancienne, développée avec Flask." -sidebarTitle: Python API ---- - -import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; -import { LoggedInForm } from "/snippets/Login.jsx"; -import Validator from "/snippets/quickstart/backend/python/validator.py.mdx"; -import Server from "/snippets/quickstart/backend/python/server.py.mdx"; - -export const sections = [ - { id: "définir-les-autorisations", title: "Définir les autorisations" }, - { id: "installer-des-dépendances", title: "Installer des dépendances" }, - { id: "créer-le-validateur-jwt", title: "Créer le validateur JWT" }, - { id: "créer-une-application-flask", title: "Créer une application Flask" } -] - - - - Ce guide explique comment intégrer Auth0 à n’importe quelle API Python, nouvelle ou ancienne, développée avec [Flask](https://flask.palletsprojects.com/). - - Si vous n’avez pas encore créé d’API dans votre Auth0 Dashboard, vous pouvez utiliser le sélecteur interactif pour créer une nouvelle API Auth0 ou sélectionner une API existante qui représente le projet avec lequel vous souhaitez vous intégrer. - - Vous pouvez également lire [notre guide de démarrage](https://auth0.com/docs/get-started/auth0-overview/set-up-apis) qui vous aide à configurer votre première API via Auth0 Dashboard. - - Toute API dans Auth0 est configurée à l’aide d’un identificateur d’API que votre code d’application utilisera comme Audience (Public) pour valider le jeton d’accès. - - - **Vous ne connaissez pas Auth0?** Découvrez [Auth0](https://auth0.com/docs/overview) et [l’implémentation de l’authentification et de l’autorisation d’API](https://auth0.com/docs/api-auth) en utilisant le cadre d’applications OAuth 2.0. - - -
- Les autorisations vous permettent de définir comment les ressources peuvent être accessibles au nom de l’utilisateur avec un jeton d’accès en particulier. Par exemple, vous pouvez choisir d’accorder un accès en lecture à la ressource `messages` si les utilisateurs ont le niveau d’accès gestionnaire et un accès en écriture à cette ressource s’ils ont le niveau d’accès administrateur. - - Vous pouvez définir les autorisations autorisées dans la vue **Permissions (Autorisations)** de la section [APIs (API)](https://manage.auth0.com/#/apis) d'Auth0 Dashboard. - - ![Auth0 Dashboard> Applications > APIs (API) > [Specific API (API précise)] > Onglet Permissions (Autorisations)](/docs/images/fr-ca/cdy7uua7fh8z/1s3Yp5zqJiKiSWqbPSezNO/677a3405b2853f5fdf9e42f6e83ceba7/Quickstarts_API_-_French.png) - - - Cet exemple utilise la permission `read:messages`. - -
- -
- Ajoutez les dépendances suivantes à votre fichier `requirements.txt` : - - ``` - # /requirements.txt - flask - - Authlib - ``` -
- -
- Nous allons utiliser une bibliothèque appelée [Authlib](https://github.com/lepture/authlib) pour créer un [ResourceProtector](https://docs.authlib.org/en/latest/flask/1/resource-server.html), qui est un type de [Flask decorator](https://flask.palletsprojects.com/patterns/viewdecorators/) qui protège nos ressources (routes API) avec un validateur donné. - - Le validateur validera le jeton d’accès que nous transmettons à la ressource en vérifiant qu’il a une signature et des demandes valides. - - Nous pouvons utiliser le validateur `JWTBearerTokenValidator` d’AuthLib avec quelques ajustements pour nous assurer qu’il est conforme à nos exigences de [validation des jetons d’accès](https://auth0.com/docs/secure/tokens/access-tokens/validate-access-tokens). - - Pour créer notre `Auth0JWTBearerTokenValidator`, nous devons lui transmettre notre `domain` et notre `audience` (Identificateur API). Il obtiendra alors la clé publique nécessaire pour vérifier la signature du jeton et la transmettra à la classe `JWTBearerTokenValidator`. - - Nous remplacerons ensuite les `claims_options` de la classe pour nous assurer que les demandes d’échéance, de public et d’émission du jeton sont validées selon nos exigences. -
- -
- Ensuite, nous allons créer une application Flask avec 3 routes API : - - - `/api/public` Un point de terminaison public qui ne nécessite aucune authentification. - - `/api/private` Un point de terminaison privé qui nécessite un jeton d’accès JWT valide. - - `/api/private-scoped` Un point de terminaison privé qui nécessite un jeton d’accès JWT valide contenant la `scope` donnée. - - Les routes protégées auront un décorateur `require_auth`, qui est un `ResourceProtector` qui utilise le `Auth0JWTBearerTokenValidator` que nous avons créé précédemment. - - Pour créer `Auth0JWTBearerTokenValidator`, nous devons lui transmettre le domaine de notre locataire et l’identificateur de l’API que nous avons créée précédemment. - - Le decorator `require_auth` sur la route `private_scoped` prend en charge un argument supplémentaire `"read:messages"`, qui vérifie la permission du jeton d’accès que nous avons créé précédemment. - - ### Faire un appel à votre API - - Pour appeler votre API, vous avez besoin d’un jeton d’accès. Vous pouvez obtenir un jeton d’accès à des fins de test dans la vue **Test** dans vos [API settings (Paramètres API)](https://manage.auth0.com/#/apis). - - ![Auth0 Dashboard> Applications > API > [API specifique] > Onglet Test](/docs/images/fr-ca/cdy7uua7fh8z/6jeVBuypOGX5qMRXeJn5ow/8aa621c6d95e3f21115493a19ab05f7a/Quickstart_Example_App_-_API.png) - - Fournir le jeton d’accès comme un en-tête `Authorization` dans vos demandes. - - - ```bash cURL lines - curl --request get \ - --url 'http:///%7ByourDomain%7D/api_path' \ - --header 'authorization: Bearer YOUR_ACCESS_TOKEN_HERE' - ``` - - ```csharp C# lines - var client = new RestClient("http:///%7ByourDomain%7D/api_path"); - var request = new RestRequest(Method.GET); - request.AddHeader("authorization", "Bearer YOUR_ACCESS_TOKEN_HERE"); - IRestResponse response = client.Execute(request); - ``` - - ```go Go lines - package main - import ( - "fmt" - "net/http" - "io/ioutil" - ) - func main() { - url := "http:///%7ByourDomain%7D/api_path" - req, _ := http.NewRequest("get", url, nil) - req.Header.Add("authorization", "Bearer YOUR_ACCESS_TOKEN_HERE") - res, _ := http.DefaultClient.Do(req) - defer res.Body.Close() - body, _ := ioutil.ReadAll(res.Body) - fmt.Println(res) - fmt.Println(string(body)) - } - ``` - - ```java Java lines - HttpResponse response = Unirest.get("http:///%7ByourDomain%7D/api_path") - .header("authorization", "Bearer YOUR_ACCESS_TOKEN_HERE") - .asString(); - ``` - - ```javascript Node.JS lines - var axios = require("axios").default; - var options = { - method: 'get', - url: 'http:///%7ByourDomain%7D/api_path', - headers: {authorization: 'Bearer YOUR_ACCESS_TOKEN_HERE'} - }; - axios.request(options).then(function (response) { - console.log(response.data); - }).catch(function (error) { - console.error(error); - }); - ``` - - ```obj-c Obj-C lines - #import - NSDictionary *headers = @{ @"authorization": @"Bearer YOUR_ACCESS_TOKEN_HERE" }; - NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http:///%7ByourDomain%7D/api_path"] - cachePolicy:NSURLRequestUseProtocolCachePolicy - - timeoutInterval:10.0]; - - [request setHTTPMethod:@"get"]; - [request setAllHTTPHeaderFields:headers]; - NSURLSession *session = [NSURLSession sharedSession]; - NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request - completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { - - if (error) { - - NSLog(@"%@", error); - - } else { - - NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response; - - NSLog(@"%@", httpResponse); - - } - - }]; - - [dataTask resume]; - ``` - - ```php PHP lines - #import - NSDictionary *headers = @{ @"authorization": @"Bearer YOUR_ACCESS_TOKEN_HERE" }; - NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http:///%7ByourDomain%7D/api_path"] - cachePolicy:NSURLRequestUseProtocolCachePolicy - - timeoutInterval:10.0]; - - [request setHTTPMethod:@"get"]; - [request setAllHTTPHeaderFields:headers]; - NSURLSession *session = [NSURLSession sharedSession]; - NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request - completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { - - if (error) { - - NSLog(@"%@", error); - - } else { - - NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response; - - NSLog(@"%@", httpResponse); - - } - - }]; - - [dataTask resume]; - ``` - - ```python Python lines - import http.client - conn = http.client.HTTPConnection("") - headers = { 'authorization': "Bearer YOUR_ACCESS_TOKEN_HERE" } - conn.request("get", "/%7ByourDomain%7D/api_path", headers=headers) - res = conn.getresponse() - data = res.read() - print(data.decode("utf-8")) - ``` - - ```ruby Ruby lines - require 'uri' - require 'net/http' - url = URI("http:///%7ByourDomain%7D/api_path") - http = Net::HTTP.new(url.host, url.port) - request = Net::HTTP::Get.new(url) - request["authorization"] = 'Bearer YOUR_ACCESS_TOKEN_HERE' - response = http.request(request) - puts response.read_body - ``` - - ```swift Swift lines - import Foundation - let headers = ["authorization": "Bearer YOUR_ACCESS_TOKEN_HERE"] - let request = NSMutableURLRequest(url: NSURL(string: "http:///%7ByourDomain%7D/api_path")! as URL, - cachePolicy: .useProtocolCachePolicy, - - timeoutInterval: 10.0) - - request.httpMethod = "get" - request.allHTTPHeaderFields = headers - let session = URLSession.shared - let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in - if (error != nil) { - print(error) - - } else { - let httpResponse = response as? HTTPURLResponse - - print(httpResponse) - - } - }) - dataTask.resume() - ``` - -
- - ## Étapes suivantes - - Beau travail! Si vous en êtes arrivé là, vous devriez avoir la connexion, la déconnexion et les informations de profil utilisateur actives dans votre application. - - Cela conclut notre tutoriel de démarrage rapide, mais il y a tellement plus à explorer. Pour en savoir plus sur ce que vous pouvez faire avec Auth0, consultez : - - * [Auth0 Dashboard](https://manage.auth0.com/#) : apprenez à configurer et gérer votre locataire et vos applications Auth0 - * [Trousse SDK auth0-python](https://github.com/auth0/auth0-python) : explorez en détail la trousse SDK utilisée dans ce tutoriel - * [Auth0 Marketplace](https://marketplace.auth0.com/) : découvrez des intégrations que vous pouvez activer pour étendre les fonctionnalités d’Auth0 -
- - - - - - - - - - - - - - - - - - - - - - - - - -
+--- +title: "Ajouter une autorisation à votre application API Flask" +permalink: "interactive" +'description': "Ce guide explique comment intégrer Auth0 à n’importe quelle API Python, nouvelle ou ancienne, développée avec Flask." +'og:title': "Ajouter une autorisation à votre application API Flask" +'og:description': "Ce guide explique comment intégrer Auth0 à n’importe quelle API Python, nouvelle ou ancienne, développée avec Flask." +'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/python.png" +'twitter:title': "Ajouter une autorisation à votre application API Flask" +'twitter:description': "Ce guide explique comment intégrer Auth0 à n’importe quelle API Python, nouvelle ou ancienne, développée avec Flask." +sidebarTitle: Python API +--- + +import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; +import { LoggedInForm } from "/snippets/Login.jsx"; +import Validator from "/snippets/quickstart/backend/python/validator.py.mdx"; +import Server from "/snippets/quickstart/backend/python/server.py.mdx"; + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + +export const sections = [ + { id: "définir-les-autorisations", title: "Définir les autorisations" }, + { id: "installer-des-dépendances", title: "Installer des dépendances" }, + { id: "créer-le-validateur-jwt", title: "Créer le validateur JWT" }, + { id: "créer-une-application-flask", title: "Créer une application Flask" } +] + + + + Ce guide explique comment intégrer Auth0 à n’importe quelle API Python, nouvelle ou ancienne, développée avec [Flask](https://flask.palletsprojects.com/). + + Si vous n’avez pas encore créé d’API dans votre Auth0 Dashboard, vous pouvez utiliser le sélecteur interactif pour créer une nouvelle API Auth0 ou sélectionner une API existante qui représente le projet avec lequel vous souhaitez vous intégrer. + + Vous pouvez également lire [notre guide de démarrage](https://auth0.com/docs/get-started/auth0-overview/set-up-apis) qui vous aide à configurer votre première API via Auth0 Dashboard. + + Toute API dans Auth0 est configurée à l’aide d’un identificateur d’API que votre code d’application utilisera comme Audience (Public) pour valider le jeton d’accès. + + + **Vous ne connaissez pas Auth0?** Découvrez [Auth0](https://auth0.com/docs/overview) et [l’implémentation de l’authentification et de l’autorisation d’API](https://auth0.com/docs/api-auth) en utilisant le cadre d’applications OAuth 2.0. + + +
+ Les autorisations vous permettent de définir comment les ressources peuvent être accessibles au nom de l’utilisateur avec un jeton d’accès en particulier. Par exemple, vous pouvez choisir d’accorder un accès en lecture à la ressource `messages` si les utilisateurs ont le niveau d’accès gestionnaire et un accès en écriture à cette ressource s’ils ont le niveau d’accès administrateur. + + Vous pouvez définir les autorisations autorisées dans la vue **Permissions (Autorisations)** de la section [APIs (API)](https://manage.auth0.com/#/apis) d'Auth0 Dashboard. + + ![Auth0 Dashboard> Applications > APIs (API) > [Specific API (API précise)] > Onglet Permissions (Autorisations)](/docs/images/fr-ca/cdy7uua7fh8z/1s3Yp5zqJiKiSWqbPSezNO/677a3405b2853f5fdf9e42f6e83ceba7/Quickstarts_API_-_French.png) + + + Cet exemple utilise la permission `read:messages`. + +
+ +
+ Ajoutez les dépendances suivantes à votre fichier `requirements.txt` : + + ``` + # /requirements.txt + flask + + Authlib + ``` +
+ +
+ Nous allons utiliser une bibliothèque appelée [Authlib](https://github.com/lepture/authlib) pour créer un [ResourceProtector](https://docs.authlib.org/en/latest/flask/1/resource-server.html), qui est un type de [Flask decorator](https://flask.palletsprojects.com/patterns/viewdecorators/) qui protège nos ressources (routes API) avec un validateur donné. + + Le validateur validera le jeton d’accès que nous transmettons à la ressource en vérifiant qu’il a une signature et des demandes valides. + + Nous pouvons utiliser le validateur `JWTBearerTokenValidator` d’AuthLib avec quelques ajustements pour nous assurer qu’il est conforme à nos exigences de [validation des jetons d’accès](https://auth0.com/docs/secure/tokens/access-tokens/validate-access-tokens). + + Pour créer notre `Auth0JWTBearerTokenValidator`, nous devons lui transmettre notre `domain` et notre `audience` (Identificateur API). Il obtiendra alors la clé publique nécessaire pour vérifier la signature du jeton et la transmettra à la classe `JWTBearerTokenValidator`. + + Nous remplacerons ensuite les `claims_options` de la classe pour nous assurer que les demandes d’échéance, de public et d’émission du jeton sont validées selon nos exigences. +
+ +
+ Ensuite, nous allons créer une application Flask avec 3 routes API : + + - `/api/public` Un point de terminaison public qui ne nécessite aucune authentification. + - `/api/private` Un point de terminaison privé qui nécessite un jeton d’accès JWT valide. + - `/api/private-scoped` Un point de terminaison privé qui nécessite un jeton d’accès JWT valide contenant la `scope` donnée. + + Les routes protégées auront un décorateur `require_auth`, qui est un `ResourceProtector` qui utilise le `Auth0JWTBearerTokenValidator` que nous avons créé précédemment. + + Pour créer `Auth0JWTBearerTokenValidator`, nous devons lui transmettre le domaine de notre locataire et l’identificateur de l’API que nous avons créée précédemment. + + Le decorator `require_auth` sur la route `private_scoped` prend en charge un argument supplémentaire `"read:messages"`, qui vérifie la permission du jeton d’accès que nous avons créé précédemment. + + ### Faire un appel à votre API + + Pour appeler votre API, vous avez besoin d’un jeton d’accès. Vous pouvez obtenir un jeton d’accès à des fins de test dans la vue **Test** dans vos [API settings (Paramètres API)](https://manage.auth0.com/#/apis). + + ![Auth0 Dashboard> Applications > API > [API specifique] > Onglet Test](/docs/images/fr-ca/cdy7uua7fh8z/6jeVBuypOGX5qMRXeJn5ow/8aa621c6d95e3f21115493a19ab05f7a/Quickstart_Example_App_-_API.png) + + Fournir le jeton d’accès comme un en-tête `Authorization` dans vos demandes. + + + ```bash cURL lines + curl --request get \ + --url 'http:///%7ByourDomain%7D/api_path' \ + --header 'authorization: Bearer YOUR_ACCESS_TOKEN_HERE' + ``` + + ```csharp C# lines + var client = new RestClient("http:///%7ByourDomain%7D/api_path"); + var request = new RestRequest(Method.GET); + request.AddHeader("authorization", "Bearer YOUR_ACCESS_TOKEN_HERE"); + IRestResponse response = client.Execute(request); + ``` + + ```go Go lines + package main + import ( + "fmt" + "net/http" + "io/ioutil" + ) + func main() { + url := "http:///%7ByourDomain%7D/api_path" + req, _ := http.NewRequest("get", url, nil) + req.Header.Add("authorization", "Bearer YOUR_ACCESS_TOKEN_HERE") + res, _ := http.DefaultClient.Do(req) + defer res.Body.Close() + body, _ := ioutil.ReadAll(res.Body) + fmt.Println(res) + fmt.Println(string(body)) + } + ``` + + ```java Java lines + HttpResponse response = Unirest.get("http:///%7ByourDomain%7D/api_path") + .header("authorization", "Bearer YOUR_ACCESS_TOKEN_HERE") + .asString(); + ``` + + ```javascript Node.JS lines + var axios = require("axios").default; + var options = { + method: 'get', + url: 'http:///%7ByourDomain%7D/api_path', + headers: {authorization: 'Bearer YOUR_ACCESS_TOKEN_HERE'} + }; + axios.request(options).then(function (response) { + console.log(response.data); + }).catch(function (error) { + console.error(error); + }); + ``` + + ```obj-c Obj-C lines + #import + NSDictionary *headers = @{ @"authorization": @"Bearer YOUR_ACCESS_TOKEN_HERE" }; + NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http:///%7ByourDomain%7D/api_path"] + cachePolicy:NSURLRequestUseProtocolCachePolicy + + timeoutInterval:10.0]; + + [request setHTTPMethod:@"get"]; + [request setAllHTTPHeaderFields:headers]; + NSURLSession *session = [NSURLSession sharedSession]; + NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request + completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { + + if (error) { + + NSLog(@"%@", error); + + } else { + + NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response; + + NSLog(@"%@", httpResponse); + + } + + }]; + + [dataTask resume]; + ``` + + ```php PHP lines + #import + NSDictionary *headers = @{ @"authorization": @"Bearer YOUR_ACCESS_TOKEN_HERE" }; + NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http:///%7ByourDomain%7D/api_path"] + cachePolicy:NSURLRequestUseProtocolCachePolicy + + timeoutInterval:10.0]; + + [request setHTTPMethod:@"get"]; + [request setAllHTTPHeaderFields:headers]; + NSURLSession *session = [NSURLSession sharedSession]; + NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request + completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { + + if (error) { + + NSLog(@"%@", error); + + } else { + + NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response; + + NSLog(@"%@", httpResponse); + + } + + }]; + + [dataTask resume]; + ``` + + ```python Python lines + import http.client + conn = http.client.HTTPConnection("") + headers = { 'authorization': "Bearer YOUR_ACCESS_TOKEN_HERE" } + conn.request("get", "/%7ByourDomain%7D/api_path", headers=headers) + res = conn.getresponse() + data = res.read() + print(data.decode("utf-8")) + ``` + + ```ruby Ruby lines + require 'uri' + require 'net/http' + url = URI("http:///%7ByourDomain%7D/api_path") + http = Net::HTTP.new(url.host, url.port) + request = Net::HTTP::Get.new(url) + request["authorization"] = 'Bearer YOUR_ACCESS_TOKEN_HERE' + response = http.request(request) + puts response.read_body + ``` + + ```swift Swift lines + import Foundation + let headers = ["authorization": "Bearer YOUR_ACCESS_TOKEN_HERE"] + let request = NSMutableURLRequest(url: NSURL(string: "http:///%7ByourDomain%7D/api_path")! as URL, + cachePolicy: .useProtocolCachePolicy, + + timeoutInterval: 10.0) + + request.httpMethod = "get" + request.allHTTPHeaderFields = headers + let session = URLSession.shared + let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in + if (error != nil) { + print(error) + + } else { + let httpResponse = response as? HTTPURLResponse + + print(httpResponse) + + } + }) + dataTask.resume() + ``` + +
+ + ## Étapes suivantes + + Beau travail! Si vous en êtes arrivé là, vous devriez avoir la connexion, la déconnexion et les informations de profil utilisateur actives dans votre application. + + Cela conclut notre tutoriel de démarrage rapide, mais il y a tellement plus à explorer. Pour en savoir plus sur ce que vous pouvez faire avec Auth0, consultez : + + * [Auth0 Dashboard](https://manage.auth0.com/#) : apprenez à configurer et gérer votre locataire et vos applications Auth0 + * [Trousse SDK auth0-python](https://github.com/auth0/auth0-python) : explorez en détail la trousse SDK utilisée dans ce tutoriel + * [Auth0 Marketplace](https://marketplace.auth0.com/) : découvrez des intégrations que vous pouvez activer pour étendre les fonctionnalités d’Auth0 +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
diff --git a/main/docs/fr-ca/quickstart/backend/rails/interactive.mdx b/main/docs/fr-ca/quickstart/backend/rails/interactive.mdx index 2413dd811..48002d653 100644 --- a/main/docs/fr-ca/quickstart/backend/rails/interactive.mdx +++ b/main/docs/fr-ca/quickstart/backend/rails/interactive.mdx @@ -1,351 +1,353 @@ ---- -title: "Ajouter une autorisation à votre API Ruby on Rails" -permalink: "interactive" -'description': "Ce tutoriel effectue la validation des jetons d’accès en utilisant le gem jwt dans une classe Auth0Client personnalisée." -'og:title': "Ajouter une autorisation à votre API Ruby on Rails" -'og:description': "Ce tutoriel effectue la validation des jetons d’accès en utilisant le gem jwt dans une classe Auth0Client personnalisée." -'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/rails.png" -'twitter:title': "Ajouter une autorisation à votre API Ruby on Rails" -'twitter:description': "Ce tutoriel effectue la validation des jetons d’accès en utilisant le gem jwt dans une classe Auth0Client personnalisée." -sidebarTitle: Ruby on Rails API ---- - -import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; -import { LoggedInForm } from "/snippets/Login.jsx"; -import ApplicationController from "/snippets/quickstart/backend/rails/application_controller.rb.mdx"; -import Auth0Client from "/snippets/quickstart/backend/rails/auth0_client.rb.mdx"; -import Secured from "/snippets/quickstart/backend/rails/secured.rb.mdx"; -import PublicController from "/snippets/quickstart/backend/rails/public_controller.rb.mdx"; -import PrivateController from "/snippets/quickstart/backend/rails/private_controller.rb.mdx"; - -export const sections = [ - { id: "définir-les-autorisations", title: "Définir les autorisations" }, - { id: "installer-les-dépendances", title: "Installer les dépendances" }, - { id: "créer-une-classe-auth0client", title: "Créer une classe Auth0Client" }, - { id: "définir-un-concern-secured", title: "Définir un concern Secured" }, - { id: "inclure-la-préoccupation-secure-dans-votre-applicationcontroller", title: "Inclure la préoccupation Secure dans votre ApplicationController" }, - { id: "créer-le-point-de-terminaison-public", title: "Créer le point de terminaison public" }, - { id: "créer-les-points-de-terminaison-privés", title: "Créer les points de terminaison privés" } -] - - - - Ce tutoriel effectue la validation des jetons d’accès en utilisant le gem [**jwt**](https://github.com/jwt/ruby-jwt) dans une classe `Auth0Client` personnalisée. Un concern appelé `Secured` est utilisé pour autoriser les points de terminaison qui nécessitent une authentification par le biais d’un jeton d’accès entrant. - - Si vous n’avez pas encore créé d’API dans votre Auth0 Dashboard, vous pouvez utiliser le sélecteur interactif pour créer une nouvelle API Auth0 ou sélectionner une API existante pour votre projet. - - Pour configurer votre première API via Auth0 Dashboard, consultez [notre guide de démarrage](https://auth0.com/docs/get-started/auth0-overview/set-up-apis). - - Chaque API Auth0 utilise l’identificateur API, dont votre application a besoin pour valider le jeton d’accès. - - - **Vous ne connaissez pas Auth0?** Découvrez [Auth0](https://auth0.com/docs/overview) et [l’implémentation de l’authentification et de l’autorisation d’API](https://auth0.com/docs/api-auth) en utilisant le cadre d’applications OAuth 2.0. - - -
- Les autorisations vous permettent de définir comment les ressources peuvent être accessibles au nom de l’utilisateur avec un jeton d’accès donné. Par exemple, vous pouvez choisir d’accorder un accès en lecture à la ressource `messages` si les utilisateurs ont le niveau d’accès gestionnaire et un accès en écriture à cette ressource s’ils ont le niveau d’accès administrateur. - - Vous pouvez définir les autorisations autorisées dans la vue **Permissions (Autorisations)** de la section [API](https://manage.auth0.com/#/apis) d’Auth0 Dashboard. - - ![Auth0 Dashboard> Applications > APIs (API) > [Specific API (API précise)] > Onglet Permissions (Autorisations)](/docs/images/fr-ca/cdy7uua7fh8z/1s3Yp5zqJiKiSWqbPSezNO/677a3405b2853f5fdf9e42f6e83ceba7/Quickstarts_API_-_French.png) - - - Cet exemple utilise la permission `read:messages`. - -
- -
- Installer le gem **jwt**. - - ``` - gem 'jwt' - bundle install - ``` -
- -
- Créez une classe appelée `Auth0Client`. Cette classe décode et vérifie le jeton d’accès entrant provenant de l’en-tête `Authorization` de la requête. - - La classe `Auth0Client` récupère la clé publique de votre locataire Auth0 et l’utilise pour vérifier la signature du jeton d’accès. La structure `Token` définit une méthode `validate_permissions` pour rechercher une `scope` particulière dans un jeton d’accès en fournissant un tableau des permissions requises et en vérifiant si elles sont présentes dans la charge utile du jeton. -
- -
- Créez un concern appelé `Secured` qui recherche le jeton d’accès dans l’en-tête `Authorization` d’une requête entrante. - - Si le jeton est présent, `Auth0Client.validate_token` utilisera le gem `jwt` pour vérifier la signature du jeton et valider les demandes du jeton. - - Outre la vérification de la validité du jeton d’accès, concern possède un mécanisme permettant de confirmer que le jeton dispose d’une **permission** suffisante pour accéder aux ressources demandées. Dans cet exemple, nous définissons une méthode `validate_permissions` qui reçoit un bloc et vérifie les autorisations en appelant la méthode `Token.validate_permissions` de la classe `Auth0Client`. - - Pour la route `/private-scoped`, les permissions définies seront croisées avec les permissions provenant de la charge utile, afin de déterminer si elle contient un ou plusieurs éléments de l’autre tableau. -
- -
- En ajoutant la préoccupation `Secure` à votre contrôleur d’application, vous n’aurez plus qu’à utiliser un filtre `before_action` dans le contrôleur qui requiert une autorisation. -
- -
- Créez un contrôleur pour gérer le point de terminaison public `/api/public`. - - Le point de terminaison `/public` ne requiert aucune autorisation et aucune `before_action` n’est donc nécessaire. -
- -
- Créez un contrôleur pour traiter les points de terminaison privés : `/api/private` et `/api/private-scoped`. - - `/api/private` est disponible pour les requêtes authentifiées contenant un jeton d’accès sans permission supplémentaire. - - `/api/private-scoped` est disponible pour les requêtes authentifiées contenant un jeton d’accès dont la permission `read:messages` est accordée. - - Les points de terminaison protégés doivent appeler la méthode `authorize` du concern `Secured`; vous devez pour cela utiliser `before_action :authorize`, ce qui assure que la méthode `Secured.authorize` est appelée avant chaque action dans le `PrivateController`. - - ### Faire un appel à votre API - - Pour appeler votre API, vous avez besoin d’un jeton d’accès. Vous pouvez obtenir un jeton d’accès à des fins de test dans la vue **Test** dans vos [API settings (Paramètres API)](https://manage.auth0.com/#/apis). - - ![Auth0 Dashboard> Applications > API > [API specifique] > Onglet Test](/docs/images/fr-ca/cdy7uua7fh8z/6jeVBuypOGX5qMRXeJn5ow/8aa621c6d95e3f21115493a19ab05f7a/Quickstart_Example_App_-_API.png) - - Fournissez le jeton d’accès comme un en-tête `Authorization` dans vos demandes. - - - ```bash cURL lines - curl --request get \ - --url 'http:///%7ByourDomain%7D/api_path' \ - --header 'authorization: Bearer YOUR_ACCESS_TOKEN_HERE' - ``` - - ```csharp C# lines - var client = new RestClient("http:///%7ByourDomain%7D/api_path"); - var request = new RestRequest(Method.GET); - request.AddHeader("authorization", "Bearer YOUR_ACCESS_TOKEN_HERE"); - IRestResponse response = client.Execute(request); - ``` - - ```go Go lines - package main - import ( - "fmt" - "net/http" - "io/ioutil" - ) - func main() { - url := "http:///%7ByourDomain%7D/api_path" - req, _ := http.NewRequest("get", url, nil) - req.Header.Add("authorization", "Bearer YOUR_ACCESS_TOKEN_HERE") - res, _ := http.DefaultClient.Do(req) - defer res.Body.Close() - body, _ := ioutil.ReadAll(res.Body) - fmt.Println(res) - fmt.Println(string(body)) - } - ``` - - ```java Java lines - HttpResponse response = Unirest.get("http:///%7ByourDomain%7D/api_path") - .header("authorization", "Bearer YOUR_ACCESS_TOKEN_HERE") - .asString(); - ``` - - ```javascript Node.JS lines - var axios = require("axios").default; - var options = { - method: 'get', - url: 'http:///%7ByourDomain%7D/api_path', - headers: {authorization: 'Bearer YOUR_ACCESS_TOKEN_HERE'} - }; - axios.request(options).then(function (response) { - console.log(response.data); - }).catch(function (error) { - console.error(error); - }); - ``` - - ```obj-c Obj-C lines - #import - NSDictionary *headers = @{ @"authorization": @"Bearer YOUR_ACCESS_TOKEN_HERE" }; - NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http:///%7ByourDomain%7D/api_path"] - cachePolicy:NSURLRequestUseProtocolCachePolicy - - timeoutInterval:10.0]; - - [request setHTTPMethod:@"get"]; - [request setAllHTTPHeaderFields:headers]; - NSURLSession *session = [NSURLSession sharedSession]; - NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request - completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { - - if (error) { - - NSLog(@"%@", error); - - } else { - - NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response; - - NSLog(@"%@", httpResponse); - - } - - }]; - - [dataTask resume]; - ``` - - ```php PHP lines - #import - NSDictionary *headers = @{ @"authorization": @"Bearer YOUR_ACCESS_TOKEN_HERE" }; - NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http:///%7ByourDomain%7D/api_path"] - cachePolicy:NSURLRequestUseProtocolCachePolicy - - timeoutInterval:10.0]; - - [request setHTTPMethod:@"get"]; - [request setAllHTTPHeaderFields:headers]; - NSURLSession *session = [NSURLSession sharedSession]; - NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request - completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { - - if (error) { - - NSLog(@"%@", error); - - } else { - - NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response; - - NSLog(@"%@", httpResponse); - - } - - }]; - - [dataTask resume]; - ``` - - ```python Python lines - import http.client - conn = http.client.HTTPConnection("") - headers = { 'authorization': "Bearer YOUR_ACCESS_TOKEN_HERE" } - conn.request("get", "/%7ByourDomain%7D/api_path", headers=headers) - res = conn.getresponse() - data = res.read() - print(data.decode("utf-8")) - ``` - - ```ruby Ruby lines - require 'uri' - require 'net/http' - url = URI("http:///%7ByourDomain%7D/api_path") - http = Net::HTTP.new(url.host, url.port) - request = Net::HTTP::Get.new(url) - request["authorization"] = 'Bearer YOUR_ACCESS_TOKEN_HERE' - response = http.request(request) - puts response.read_body - ``` - - ```swift Swift lines - import Foundation - let headers = ["authorization": "Bearer YOUR_ACCESS_TOKEN_HERE"] - let request = NSMutableURLRequest(url: NSURL(string: "http:///%7ByourDomain%7D/api_path")! as URL, - cachePolicy: .useProtocolCachePolicy, - - timeoutInterval: 10.0) - - request.httpMethod = "get" - request.allHTTPHeaderFields = headers - let session = URLSession.shared - let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in - if (error != nil) { - print(error) - - } else { - let httpResponse = response as? HTTPURLResponse - - print(httpResponse) - - } - }) - dataTask.resume() - ``` - - - - ##### Point de contrôle - Maintenant que vous avez configuré votre application, exécutez-la pour vérifier que : - `GET /api/public` est disponible pour les demandes non authentifiées. - `GET /api/private` est disponible pour les demandes authentifiées. - `GET /api/private-scoped` est disponible pour les demandes authentifiées contenant un jeton d’accès avec la permission `read:messages`. - -
- - ## Étapes suivantes - - Beau travail! Si vous en êtes arrivé là, vous devriez avoir la connexion, la déconnexion et les informations de profil utilisateur actives dans votre application. - - Cela conclut notre tutoriel de démarrage rapide, mais il y a tellement plus à explorer. Pour en savoir plus sur ce que vous pouvez faire avec Auth0, consultez : - - * [Auth0 Dashboard](https://manage.auth0.com/#) : apprenez à configurer et gérer votre locataire et vos applications Auth0 - * [Trousse SDK omniauth-auth0](https://github.com/auth0/omniauth-auth0) : explorez en détail la trousse SDK utilisée dans ce tutoriel - * [Auth0 Marketplace](https://marketplace.auth0.com/) : découvrez des intégrations que vous pouvez activer pour étendre les fonctionnalités d’Auth0 -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+--- +title: "Ajouter une autorisation à votre API Ruby on Rails" +permalink: "interactive" +'description': "Ce tutoriel effectue la validation des jetons d’accès en utilisant le gem jwt dans une classe Auth0Client personnalisée." +'og:title': "Ajouter une autorisation à votre API Ruby on Rails" +'og:description': "Ce tutoriel effectue la validation des jetons d’accès en utilisant le gem jwt dans une classe Auth0Client personnalisée." +'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/rails.png" +'twitter:title': "Ajouter une autorisation à votre API Ruby on Rails" +'twitter:description': "Ce tutoriel effectue la validation des jetons d’accès en utilisant le gem jwt dans une classe Auth0Client personnalisée." +sidebarTitle: Ruby on Rails API +--- + +import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; +import { LoggedInForm } from "/snippets/Login.jsx"; +import ApplicationController from "/snippets/quickstart/backend/rails/application_controller.rb.mdx"; +import Auth0Client from "/snippets/quickstart/backend/rails/auth0_client.rb.mdx"; +import Secured from "/snippets/quickstart/backend/rails/secured.rb.mdx"; +import PublicController from "/snippets/quickstart/backend/rails/public_controller.rb.mdx"; +import PrivateController from "/snippets/quickstart/backend/rails/private_controller.rb.mdx"; + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + +export const sections = [ + { id: "définir-les-autorisations", title: "Définir les autorisations" }, + { id: "installer-les-dépendances", title: "Installer les dépendances" }, + { id: "créer-une-classe-auth0client", title: "Créer une classe Auth0Client" }, + { id: "définir-un-concern-secured", title: "Définir un concern Secured" }, + { id: "inclure-la-préoccupation-secure-dans-votre-applicationcontroller", title: "Inclure la préoccupation Secure dans votre ApplicationController" }, + { id: "créer-le-point-de-terminaison-public", title: "Créer le point de terminaison public" }, + { id: "créer-les-points-de-terminaison-privés", title: "Créer les points de terminaison privés" } +] + + + + Ce tutoriel effectue la validation des jetons d’accès en utilisant le gem [**jwt**](https://github.com/jwt/ruby-jwt) dans une classe `Auth0Client` personnalisée. Un concern appelé `Secured` est utilisé pour autoriser les points de terminaison qui nécessitent une authentification par le biais d’un jeton d’accès entrant. + + Si vous n’avez pas encore créé d’API dans votre Auth0 Dashboard, vous pouvez utiliser le sélecteur interactif pour créer une nouvelle API Auth0 ou sélectionner une API existante pour votre projet. + + Pour configurer votre première API via Auth0 Dashboard, consultez [notre guide de démarrage](https://auth0.com/docs/get-started/auth0-overview/set-up-apis). + + Chaque API Auth0 utilise l’identificateur API, dont votre application a besoin pour valider le jeton d’accès. + + + **Vous ne connaissez pas Auth0?** Découvrez [Auth0](https://auth0.com/docs/overview) et [l’implémentation de l’authentification et de l’autorisation d’API](https://auth0.com/docs/api-auth) en utilisant le cadre d’applications OAuth 2.0. + + +
+ Les autorisations vous permettent de définir comment les ressources peuvent être accessibles au nom de l’utilisateur avec un jeton d’accès donné. Par exemple, vous pouvez choisir d’accorder un accès en lecture à la ressource `messages` si les utilisateurs ont le niveau d’accès gestionnaire et un accès en écriture à cette ressource s’ils ont le niveau d’accès administrateur. + + Vous pouvez définir les autorisations autorisées dans la vue **Permissions (Autorisations)** de la section [API](https://manage.auth0.com/#/apis) d’Auth0 Dashboard. + + ![Auth0 Dashboard> Applications > APIs (API) > [Specific API (API précise)] > Onglet Permissions (Autorisations)](/docs/images/fr-ca/cdy7uua7fh8z/1s3Yp5zqJiKiSWqbPSezNO/677a3405b2853f5fdf9e42f6e83ceba7/Quickstarts_API_-_French.png) + + + Cet exemple utilise la permission `read:messages`. + +
+ +
+ Installer le gem **jwt**. + + ``` + gem 'jwt' + bundle install + ``` +
+ +
+ Créez une classe appelée `Auth0Client`. Cette classe décode et vérifie le jeton d’accès entrant provenant de l’en-tête `Authorization` de la requête. + + La classe `Auth0Client` récupère la clé publique de votre locataire Auth0 et l’utilise pour vérifier la signature du jeton d’accès. La structure `Token` définit une méthode `validate_permissions` pour rechercher une `scope` particulière dans un jeton d’accès en fournissant un tableau des permissions requises et en vérifiant si elles sont présentes dans la charge utile du jeton. +
+ +
+ Créez un concern appelé `Secured` qui recherche le jeton d’accès dans l’en-tête `Authorization` d’une requête entrante. + + Si le jeton est présent, `Auth0Client.validate_token` utilisera le gem `jwt` pour vérifier la signature du jeton et valider les demandes du jeton. + + Outre la vérification de la validité du jeton d’accès, concern possède un mécanisme permettant de confirmer que le jeton dispose d’une **permission** suffisante pour accéder aux ressources demandées. Dans cet exemple, nous définissons une méthode `validate_permissions` qui reçoit un bloc et vérifie les autorisations en appelant la méthode `Token.validate_permissions` de la classe `Auth0Client`. + + Pour la route `/private-scoped`, les permissions définies seront croisées avec les permissions provenant de la charge utile, afin de déterminer si elle contient un ou plusieurs éléments de l’autre tableau. +
+ +
+ En ajoutant la préoccupation `Secure` à votre contrôleur d’application, vous n’aurez plus qu’à utiliser un filtre `before_action` dans le contrôleur qui requiert une autorisation. +
+ +
+ Créez un contrôleur pour gérer le point de terminaison public `/api/public`. + + Le point de terminaison `/public` ne requiert aucune autorisation et aucune `before_action` n’est donc nécessaire. +
+ +
+ Créez un contrôleur pour traiter les points de terminaison privés : `/api/private` et `/api/private-scoped`. + + `/api/private` est disponible pour les requêtes authentifiées contenant un jeton d’accès sans permission supplémentaire. + + `/api/private-scoped` est disponible pour les requêtes authentifiées contenant un jeton d’accès dont la permission `read:messages` est accordée. + + Les points de terminaison protégés doivent appeler la méthode `authorize` du concern `Secured`; vous devez pour cela utiliser `before_action :authorize`, ce qui assure que la méthode `Secured.authorize` est appelée avant chaque action dans le `PrivateController`. + + ### Faire un appel à votre API + + Pour appeler votre API, vous avez besoin d’un jeton d’accès. Vous pouvez obtenir un jeton d’accès à des fins de test dans la vue **Test** dans vos [API settings (Paramètres API)](https://manage.auth0.com/#/apis). + + ![Auth0 Dashboard> Applications > API > [API specifique] > Onglet Test](/docs/images/fr-ca/cdy7uua7fh8z/6jeVBuypOGX5qMRXeJn5ow/8aa621c6d95e3f21115493a19ab05f7a/Quickstart_Example_App_-_API.png) + + Fournissez le jeton d’accès comme un en-tête `Authorization` dans vos demandes. + + + ```bash cURL lines + curl --request get \ + --url 'http:///%7ByourDomain%7D/api_path' \ + --header 'authorization: Bearer YOUR_ACCESS_TOKEN_HERE' + ``` + + ```csharp C# lines + var client = new RestClient("http:///%7ByourDomain%7D/api_path"); + var request = new RestRequest(Method.GET); + request.AddHeader("authorization", "Bearer YOUR_ACCESS_TOKEN_HERE"); + IRestResponse response = client.Execute(request); + ``` + + ```go Go lines + package main + import ( + "fmt" + "net/http" + "io/ioutil" + ) + func main() { + url := "http:///%7ByourDomain%7D/api_path" + req, _ := http.NewRequest("get", url, nil) + req.Header.Add("authorization", "Bearer YOUR_ACCESS_TOKEN_HERE") + res, _ := http.DefaultClient.Do(req) + defer res.Body.Close() + body, _ := ioutil.ReadAll(res.Body) + fmt.Println(res) + fmt.Println(string(body)) + } + ``` + + ```java Java lines + HttpResponse response = Unirest.get("http:///%7ByourDomain%7D/api_path") + .header("authorization", "Bearer YOUR_ACCESS_TOKEN_HERE") + .asString(); + ``` + + ```javascript Node.JS lines + var axios = require("axios").default; + var options = { + method: 'get', + url: 'http:///%7ByourDomain%7D/api_path', + headers: {authorization: 'Bearer YOUR_ACCESS_TOKEN_HERE'} + }; + axios.request(options).then(function (response) { + console.log(response.data); + }).catch(function (error) { + console.error(error); + }); + ``` + + ```obj-c Obj-C lines + #import + NSDictionary *headers = @{ @"authorization": @"Bearer YOUR_ACCESS_TOKEN_HERE" }; + NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http:///%7ByourDomain%7D/api_path"] + cachePolicy:NSURLRequestUseProtocolCachePolicy + + timeoutInterval:10.0]; + + [request setHTTPMethod:@"get"]; + [request setAllHTTPHeaderFields:headers]; + NSURLSession *session = [NSURLSession sharedSession]; + NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request + completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { + + if (error) { + + NSLog(@"%@", error); + + } else { + + NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response; + + NSLog(@"%@", httpResponse); + + } + + }]; + + [dataTask resume]; + ``` + + ```php PHP lines + #import + NSDictionary *headers = @{ @"authorization": @"Bearer YOUR_ACCESS_TOKEN_HERE" }; + NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http:///%7ByourDomain%7D/api_path"] + cachePolicy:NSURLRequestUseProtocolCachePolicy + + timeoutInterval:10.0]; + + [request setHTTPMethod:@"get"]; + [request setAllHTTPHeaderFields:headers]; + NSURLSession *session = [NSURLSession sharedSession]; + NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request + completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { + + if (error) { + + NSLog(@"%@", error); + + } else { + + NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response; + + NSLog(@"%@", httpResponse); + + } + + }]; + + [dataTask resume]; + ``` + + ```python Python lines + import http.client + conn = http.client.HTTPConnection("") + headers = { 'authorization': "Bearer YOUR_ACCESS_TOKEN_HERE" } + conn.request("get", "/%7ByourDomain%7D/api_path", headers=headers) + res = conn.getresponse() + data = res.read() + print(data.decode("utf-8")) + ``` + + ```ruby Ruby lines + require 'uri' + require 'net/http' + url = URI("http:///%7ByourDomain%7D/api_path") + http = Net::HTTP.new(url.host, url.port) + request = Net::HTTP::Get.new(url) + request["authorization"] = 'Bearer YOUR_ACCESS_TOKEN_HERE' + response = http.request(request) + puts response.read_body + ``` + + ```swift Swift lines + import Foundation + let headers = ["authorization": "Bearer YOUR_ACCESS_TOKEN_HERE"] + let request = NSMutableURLRequest(url: NSURL(string: "http:///%7ByourDomain%7D/api_path")! as URL, + cachePolicy: .useProtocolCachePolicy, + + timeoutInterval: 10.0) + + request.httpMethod = "get" + request.allHTTPHeaderFields = headers + let session = URLSession.shared + let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in + if (error != nil) { + print(error) + + } else { + let httpResponse = response as? HTTPURLResponse + + print(httpResponse) + + } + }) + dataTask.resume() + ``` + + + + ##### Point de contrôle + Maintenant que vous avez configuré votre application, exécutez-la pour vérifier que : + `GET /api/public` est disponible pour les demandes non authentifiées. + `GET /api/private` est disponible pour les demandes authentifiées. + `GET /api/private-scoped` est disponible pour les demandes authentifiées contenant un jeton d’accès avec la permission `read:messages`. + +
+ + ## Étapes suivantes + + Beau travail! Si vous en êtes arrivé là, vous devriez avoir la connexion, la déconnexion et les informations de profil utilisateur actives dans votre application. + + Cela conclut notre tutoriel de démarrage rapide, mais il y a tellement plus à explorer. Pour en savoir plus sur ce que vous pouvez faire avec Auth0, consultez : + + * [Auth0 Dashboard](https://manage.auth0.com/#) : apprenez à configurer et gérer votre locataire et vos applications Auth0 + * [Trousse SDK omniauth-auth0](https://github.com/auth0/omniauth-auth0) : explorez en détail la trousse SDK utilisée dans ce tutoriel + * [Auth0 Marketplace](https://marketplace.auth0.com/) : découvrez des intégrations que vous pouvez activer pour étendre les fonctionnalités d’Auth0 +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
diff --git a/main/docs/fr-ca/quickstart/backend/webapi-owin/interactive.mdx b/main/docs/fr-ca/quickstart/backend/webapi-owin/interactive.mdx index 1e7569eb1..54702c1ae 100644 --- a/main/docs/fr-ca/quickstart/backend/webapi-owin/interactive.mdx +++ b/main/docs/fr-ca/quickstart/backend/webapi-owin/interactive.mdx @@ -1,153 +1,155 @@ ---- -title: "Ajouter une autorisation à votre application API ASP.NET OWIN Web" -permalink: "interactive" -'description': "Ce tutoriel explique comment ajouter une autorisation à une API ASP.NET OWIN en utilisant le logiciel médiateur JWT standard." -'og:title': "Ajouter une autorisation à votre application API ASP.NET OWIN Web" -'og:description': "Ce tutoriel explique comment ajouter une autorisation à une API ASP.NET OWIN en utilisant le logiciel médiateur JWT standard." -'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/asp.png" -'twitter:title': "Ajouter une autorisation à votre application API ASP.NET OWIN Web" -'twitter:description': "Ce tutoriel explique comment ajouter une autorisation à une API ASP.NET OWIN en utilisant le logiciel médiateur JWT standard." -sidebarTitle: ASP.NET Web API (OWIN) ---- - -import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; -import { LoggedInForm } from "/snippets/Login.jsx"; -import Openidconnectsigningkeyresolver from "/snippets/quickstart/backend/webapi-owin/OpenIdConnectSigningKeyResolver.cs.mdx"; -import Scopeauthorizeattribute from "/snippets/quickstart/backend/webapi-owin/ScopeAuthorizeAttribute.cs.mdx"; -import Apicontroller from "/snippets/quickstart/backend/webapi-owin/ApiController.cs.mdx"; - -export const sections = [ - { id: "définir-les-autorisations", title: "Définir les autorisations" }, - { id: "installer-les-dépendances", title: "Installer les dépendances" }, - { id: "configurer-l-intergiciel", title: "Configurer l’intergiciel" }, - { id: "vérifier-la-signature-du-jeton", title: "Vérifier la signature du jeton" }, - { id: "valider-les-permissions", title: "Valider les permissions" }, - { id: "protéger-les-points-de-terminaison-des-api", title: "Protéger les points de terminaison des API" } -] - - - - Auth0 vous permet d’ajouter une autorisation à n’importe quel type d’application. Ce guide explique comment intégrer Auth0 à n’importe quelle application API ASP.NET Owin Web, nouvelle ou ancienne, à l’aide du package `Microsoft.Owin.Security.Jwt`. - - Si vous n’avez pas encore créé d’API dans votre Auth0 Dashboard, vous pouvez utiliser le sélecteur interactif pour créer une nouvelle API Auth0 ou sélectionner une API existante pour votre projet. - - Pour configurer votre première API via Auth0 Dashboard, consultez notre guide de démarrage. - - Chaque API Auth0 utilise l’identificateur API, dont votre application a besoin pour valider le jeton d’accès. - - - **Vous ne connaissez pas Auth0 ?** Découvrez Auth0 et l’implémentation de l’authentification et de l’autorisation d’API en utilisant le cadre d’applications OAuth 2.0. - - -
- Les autorisations vous permettent de définir comment les ressources peuvent être accessibles au nom de l’utilisateur avec un jeton d’accès donné. Par exemple, vous pouvez choisir d’accorder un accès en lecture à la ressource `messages` si les utilisateurs ont le niveau d’accès gestionnaire et un accès en écriture à cette ressource s’ils ont le niveau d’accès administrateur. - - Vous pouvez définir les autorisations autorisées dans la vue **Permissions (Autorisations)** de la section [API](https://manage.auth0.com/#/apis) d’Auth0 Dashboard. L’exemple suivant utilise la permission `read:messages`. - - ![Auth0 Dashboard> Applications > APIs (API) > [Specific API (API précise)] > Onglet Permissions (Autorisations)](/docs/images/fr-ca/cdy7uua7fh8z/1s3Yp5zqJiKiSWqbPSezNO/677a3405b2853f5fdf9e42f6e83ceba7/Quickstarts_API_-_French.png) -
- -
- Installez le NuGetPackage `Microsoft.Owin.Security.Jwt`. Ce package contient l’intergiciel OWIN JWT nécessaire pour utiliser les jetons d’accès Auth0 dans l’API Web ASP.NET Owin. - - ``` - Install-Package Microsoft.Owin.Security.Jwt - ``` -
- -
- Allez dans la méthode de `Configuration` de votre classe `Startup` et ajoutez un appel à `UseJwtBearerAuthentication` passant dans les `JwtBearerAuthenticationOptions` configurées. - - `JwtBearerAuthenticationOptions` doit indiquer votre identificateur API Auth0 dans la propriété `ValidAudience` et le chemin complet vers votre domaine Auth0 en tant que `ValidIssuer`. Vous devrez configurer l’instance `IssuerSigningKeyResolver` pour utiliser l’instance `OpenIdConnectSigningKeyResolver` afin de résoudre la clé de connexion. - - - **N’oubliez pas la barre oblique finale**. - Assurez-vous que l’URL précisée pour `ValidIssuer` contient une barre oblique (`/`) finale. Cela doit correspondre exactement à la demande de l’émetteur JWT. Les appels d’API ne s’authentifieront pas correctement si vous avez mal configuré cette valeur. - -
- -
- Le logiciel médiateur OWIN JWT n’utilise pas Open ID Connect Discovery par défaut, vous devez donc fournir un `IssuerSigningKeyResolver` personnalisé. - - Créez la classe `OpenIdConnectSigningKeyResolver` et assurez-vous de retourner la bonne `SecurityKey` en implémentant `GetSigningKey`. Cette classe est ensuite utilisée comme `TokenValidationParameters.IssuerSigningKeyResolver` lors de la configuration du logiciel médiateur dans `Startup.cs`. -
- -
- Le logiciel médiateur JWT vérifie que le jeton d’accès inclus dans la requête est valide; cependant, il n’inclut pas encore de mécanisme pour vérifier que le jeton a une **scope (permission)** suffisante pour accéder aux ressources demandées. - - Créez une classe appelée `ScopeAuthorizeAttribute` qui hérite de `System.Web.Http.AuthorizeAttribute`. Cet attribut vérifiera que la demande de `scope` émise par votre locataire Auth0 est présente, et si oui, il assurera que la demande de `scope` contient la permission demandée. -
- -
- Les routes ci-dessous sont disponibles pour les demandes suivantes : - - - `GET /api/public` : Disponible pour les demandes non authentifiées. - - `GET /api/private` : Disponible pour les demandes authentifiées contenant un jeton d’accès sans permission supplémentaire. - - `GET /api/private-scoped` : Disponible pour les demandes authentifiées contenant un jeton d’accès dont la permission `read:messages` est accordée. - - L’intergiciel JWT s’intègre aux mécanismes d’authentification et d’autorisation standard d’ASP.NET, vous n’avez donc qu’à décorer votre action de contrôleur avec l’attribut `[Authorize]` pour obtenir un point de terminaison. - - Mettez à jour l’action avec l’attribut `ScopeAuthorize` et passez le nom de la `scope` requise dans le paramètre `scope`. Cela garantit que la permission adéquate est disponible pour appeler un point de terminaison d’API donné. - - - ##### Point de contrôle - Maintenant que vous avez configuré votre application, lancez votre application et vérifiez que : - `GET /api/public` est disponible pour les demandes non authentifiées. - `GET /api/private` est disponible pour les demandes authentifiées. - `GET /api/private-scoped` est disponible pour les demandes authentifiées contenant un jeton d’accès avec la permission `read:messages`. - -
- - ## Étapes suivantes - - Beau travail! Si vous en êtes arrivé là, vous devriez avoir la connexion, la déconnexion et les informations de profil utilisateur actives dans votre application. - - Cela conclut notre tutoriel de démarrage rapide, mais il y a tellement plus à explorer. Pour en savoir plus sur ce que vous pouvez faire avec Auth0, consultez : - - * [Auth0 Dashboard](https://manage.auth0.com/#) : apprenez à configurer et gérer votre locataire et vos applications Auth0 - * [Auth0 Marketplace](https://marketplace.auth0.com/) : découvrez des intégrations que vous pouvez activer pour étendre les fonctionnalités d’Auth0 -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+--- +title: "Ajouter une autorisation à votre application API ASP.NET OWIN Web" +permalink: "interactive" +'description': "Ce tutoriel explique comment ajouter une autorisation à une API ASP.NET OWIN en utilisant le logiciel médiateur JWT standard." +'og:title': "Ajouter une autorisation à votre application API ASP.NET OWIN Web" +'og:description': "Ce tutoriel explique comment ajouter une autorisation à une API ASP.NET OWIN en utilisant le logiciel médiateur JWT standard." +'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/asp.png" +'twitter:title': "Ajouter une autorisation à votre application API ASP.NET OWIN Web" +'twitter:description': "Ce tutoriel explique comment ajouter une autorisation à une API ASP.NET OWIN en utilisant le logiciel médiateur JWT standard." +sidebarTitle: ASP.NET Web API (OWIN) +--- + +import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; +import { LoggedInForm } from "/snippets/Login.jsx"; +import Openidconnectsigningkeyresolver from "/snippets/quickstart/backend/webapi-owin/OpenIdConnectSigningKeyResolver.cs.mdx"; +import Scopeauthorizeattribute from "/snippets/quickstart/backend/webapi-owin/ScopeAuthorizeAttribute.cs.mdx"; +import Apicontroller from "/snippets/quickstart/backend/webapi-owin/ApiController.cs.mdx"; + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + +export const sections = [ + { id: "définir-les-autorisations", title: "Définir les autorisations" }, + { id: "installer-les-dépendances", title: "Installer les dépendances" }, + { id: "configurer-l-intergiciel", title: "Configurer l’intergiciel" }, + { id: "vérifier-la-signature-du-jeton", title: "Vérifier la signature du jeton" }, + { id: "valider-les-permissions", title: "Valider les permissions" }, + { id: "protéger-les-points-de-terminaison-des-api", title: "Protéger les points de terminaison des API" } +] + + + + Auth0 vous permet d’ajouter une autorisation à n’importe quel type d’application. Ce guide explique comment intégrer Auth0 à n’importe quelle application API ASP.NET Owin Web, nouvelle ou ancienne, à l’aide du package `Microsoft.Owin.Security.Jwt`. + + Si vous n’avez pas encore créé d’API dans votre Auth0 Dashboard, vous pouvez utiliser le sélecteur interactif pour créer une nouvelle API Auth0 ou sélectionner une API existante pour votre projet. + + Pour configurer votre première API via Auth0 Dashboard, consultez notre guide de démarrage. + + Chaque API Auth0 utilise l’identificateur API, dont votre application a besoin pour valider le jeton d’accès. + + + **Vous ne connaissez pas Auth0 ?** Découvrez Auth0 et l’implémentation de l’authentification et de l’autorisation d’API en utilisant le cadre d’applications OAuth 2.0. + + +
+ Les autorisations vous permettent de définir comment les ressources peuvent être accessibles au nom de l’utilisateur avec un jeton d’accès donné. Par exemple, vous pouvez choisir d’accorder un accès en lecture à la ressource `messages` si les utilisateurs ont le niveau d’accès gestionnaire et un accès en écriture à cette ressource s’ils ont le niveau d’accès administrateur. + + Vous pouvez définir les autorisations autorisées dans la vue **Permissions (Autorisations)** de la section [API](https://manage.auth0.com/#/apis) d’Auth0 Dashboard. L’exemple suivant utilise la permission `read:messages`. + + ![Auth0 Dashboard> Applications > APIs (API) > [Specific API (API précise)] > Onglet Permissions (Autorisations)](/docs/images/fr-ca/cdy7uua7fh8z/1s3Yp5zqJiKiSWqbPSezNO/677a3405b2853f5fdf9e42f6e83ceba7/Quickstarts_API_-_French.png) +
+ +
+ Installez le NuGetPackage `Microsoft.Owin.Security.Jwt`. Ce package contient l’intergiciel OWIN JWT nécessaire pour utiliser les jetons d’accès Auth0 dans l’API Web ASP.NET Owin. + + ``` + Install-Package Microsoft.Owin.Security.Jwt + ``` +
+ +
+ Allez dans la méthode de `Configuration` de votre classe `Startup` et ajoutez un appel à `UseJwtBearerAuthentication` passant dans les `JwtBearerAuthenticationOptions` configurées. + + `JwtBearerAuthenticationOptions` doit indiquer votre identificateur API Auth0 dans la propriété `ValidAudience` et le chemin complet vers votre domaine Auth0 en tant que `ValidIssuer`. Vous devrez configurer l’instance `IssuerSigningKeyResolver` pour utiliser l’instance `OpenIdConnectSigningKeyResolver` afin de résoudre la clé de connexion. + + + **N’oubliez pas la barre oblique finale**. + Assurez-vous que l’URL précisée pour `ValidIssuer` contient une barre oblique (`/`) finale. Cela doit correspondre exactement à la demande de l’émetteur JWT. Les appels d’API ne s’authentifieront pas correctement si vous avez mal configuré cette valeur. + +
+ +
+ Le logiciel médiateur OWIN JWT n’utilise pas Open ID Connect Discovery par défaut, vous devez donc fournir un `IssuerSigningKeyResolver` personnalisé. + + Créez la classe `OpenIdConnectSigningKeyResolver` et assurez-vous de retourner la bonne `SecurityKey` en implémentant `GetSigningKey`. Cette classe est ensuite utilisée comme `TokenValidationParameters.IssuerSigningKeyResolver` lors de la configuration du logiciel médiateur dans `Startup.cs`. +
+ +
+ Le logiciel médiateur JWT vérifie que le jeton d’accès inclus dans la requête est valide; cependant, il n’inclut pas encore de mécanisme pour vérifier que le jeton a une **scope (permission)** suffisante pour accéder aux ressources demandées. + + Créez une classe appelée `ScopeAuthorizeAttribute` qui hérite de `System.Web.Http.AuthorizeAttribute`. Cet attribut vérifiera que la demande de `scope` émise par votre locataire Auth0 est présente, et si oui, il assurera que la demande de `scope` contient la permission demandée. +
+ +
+ Les routes ci-dessous sont disponibles pour les demandes suivantes : + + - `GET /api/public` : Disponible pour les demandes non authentifiées. + - `GET /api/private` : Disponible pour les demandes authentifiées contenant un jeton d’accès sans permission supplémentaire. + - `GET /api/private-scoped` : Disponible pour les demandes authentifiées contenant un jeton d’accès dont la permission `read:messages` est accordée. + + L’intergiciel JWT s’intègre aux mécanismes d’authentification et d’autorisation standard d’ASP.NET, vous n’avez donc qu’à décorer votre action de contrôleur avec l’attribut `[Authorize]` pour obtenir un point de terminaison. + + Mettez à jour l’action avec l’attribut `ScopeAuthorize` et passez le nom de la `scope` requise dans le paramètre `scope`. Cela garantit que la permission adéquate est disponible pour appeler un point de terminaison d’API donné. + + + ##### Point de contrôle + Maintenant que vous avez configuré votre application, lancez votre application et vérifiez que : + `GET /api/public` est disponible pour les demandes non authentifiées. + `GET /api/private` est disponible pour les demandes authentifiées. + `GET /api/private-scoped` est disponible pour les demandes authentifiées contenant un jeton d’accès avec la permission `read:messages`. + +
+ + ## Étapes suivantes + + Beau travail! Si vous en êtes arrivé là, vous devriez avoir la connexion, la déconnexion et les informations de profil utilisateur actives dans votre application. + + Cela conclut notre tutoriel de démarrage rapide, mais il y a tellement plus à explorer. Pour en savoir plus sur ce que vous pouvez faire avec Auth0, consultez : + + * [Auth0 Dashboard](https://manage.auth0.com/#) : apprenez à configurer et gérer votre locataire et vos applications Auth0 + * [Auth0 Marketplace](https://marketplace.auth0.com/) : découvrez des intégrations que vous pouvez activer pour étendre les fonctionnalités d’Auth0 +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
diff --git a/main/docs/fr-ca/quickstart/native/android-facebook-login/interactive.mdx b/main/docs/fr-ca/quickstart/native/android-facebook-login/interactive.mdx index bbfd6799a..421ff6c3f 100644 --- a/main/docs/fr-ca/quickstart/native/android-facebook-login/interactive.mdx +++ b/main/docs/fr-ca/quickstart/native/android-facebook-login/interactive.mdx @@ -1,277 +1,279 @@ ---- -title: "Android – Connexion Facebook" -permalink: "interactive" -'description': "Ce tutoriel explique comment ajouter la connexion utilisateur à une application Android à l’aide de la méthode native Connexion Facebook." -'og:title': "Android – Connexion Facebook" -'og:description': "Ce tutoriel explique comment ajouter la connexion utilisateur à une application Android à l’aide de la méthode native Connexion Facebook." -'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/android.png" -'twitter:title': "Android – Connexion Facebook" -'twitter:description': "Ce tutoriel explique comment ajouter la connexion utilisateur à une application Android à l’aide de la méthode native Connexion Facebook." ---- - -import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; -import { LoggedInForm } from "/snippets/Login.jsx"; -import Performloginsimplecallback from "/snippets/quickstart/native/android-facebook-login/performLogin + SimpleCallback.mdx"; -import Oncreate from "/snippets/quickstart/native/android-facebook-login/onCreate.mdx"; -import Fetchsessiontoken from "/snippets/quickstart/native/android-facebook-login/fetchSessionToken.mdx"; -import Fetchuserprofile from "/snippets/quickstart/native/android-facebook-login/fetchUserProfile.mdx"; -import Exchangetokens from "/snippets/quickstart/native/android-facebook-login/exchangeTokens.mdx"; -import Performlogin from "/snippets/quickstart/native/android-facebook-login/performLogin.mdx"; - -export const sections = [ - { id: "configurations-requise", title: "Configurations requise" }, - { id: "avant-de-commencer", title: "Avant de commencer" }, - { id: "demande-d-autorisations-facebook", title: "Demande d’autorisations Facebook" }, - { id: "créer-la-méthode-performlogin", title: "Créer la méthode performLogin" }, - { id: "appeler-la-méthode-performlogin", title: "Appeler la méthode performLogin" }, - { id: "intégrer-facebook", title: "Intégrer Facebook" }, - { id: "récupérer-le-jeton-d-accès-à-la-session-facebook", title: "Récupérer le jeton d’accès à la session Facebook" }, - { id: "récupérer-le-profil-utilisateur-facebook", title: "Récupérer le profil utilisateur Facebook" }, - { id: "intégrer-auth0", title: "Intégrer Auth0" }, - { id: "échanger-les-données-reçues-contre-des-jetons-auth0", title: "Échanger les données reçues contre des jetons Auth0" }, - { id: "mettre-à-jour-la-méthode-performlogin", title: "Mettre à jour la méthode performLogin" } -] - - - - Ce tutoriel explique comment ajouter la connexion utilisateur à une application Android à l’aide de la méthode native Connexion Facebook. Nous vous recommandons de vous connecter pour suivre ce démarrage rapide avec les exemples configurés pour votre compte. - -
- - Android Studio 3.6.1 - - Trousse SDK Android 25 - - Émulateur - Nexus 5X - Android 6.0 - - Ce tutoriel décrit comment mettre en œuvre la connexion avec la [trousse SDK Facebook](https://developers.facebook.com/docs/). -
- -
- - Installez et configurez la [trousse SDK Connexion Facebook](https://developers.facebook.com/docs/facebook-login/). Vous découvrirez également le processus de création d’une application Facebook sur [https://developers.facebook.com](https://developers.facebook.com/). **À la fin de cette étape, vous devriez avoir une application mobile fonctionnant avec la fonction de connexion Facebook intégrée.** - - Configurez votre application Auth0 dans le Dashboard pour utiliser la fonction Connexion Facebook en mode natif. Voir [Ajouter une connexion Facebook aux applications natives](https://auth0.com/docs/connections/nativesocial/facebook). **À la fin de cette étape, votre application sera en mesure d’implémenter la fonction Connexion Facebook en mode natif.** -
- -
- Votre application est déjà capable de se connecter à Facebook. Cependant, pour garantir un profil utilisateur riche, vous devez mettre à jour les autorisations avec lesquelles le bouton de connexion Facebook a été configuré. - - Définissez les autorisations demandées sur `public_profile` et `email`. De cette manière, l’adresse courriel de l’utilisateur sera également incluse dans la réponse, à condition que la demande d’accès soit acceptée par l’utilisateur. - - `loginButton.setPermissions(Arrays.asList("public_profile", "email"));` -
- -
- Maintenant, pour lancer le processus d’authentification avec Auth0, créez une nouvelle méthode où vous préparerez la charge utile à envoyer. - - Vous utiliserez une interface simple pour gérer nos rappels internes. - - Dans l’exemple, la méthode s’appelle `performLogin` et l’interface `SimpleCallback`. Ajoutez les deux. -
- -
- Maintenant, appelez la méthode de la méthode `onSuccess` de rappel (Callback) de connexion Facebook. -
- -
- Lorsque vous vous connectez à Facebook avec Auth0, le système dorsal effectue des vérifications en arrière-plan pour s’assurer que l’utilisateur est bien celui qu’il prétend être. Pour ce faire, il faut lui fournir un jeton d’accès à la session. - - En outre, si un utilisateur doit être créé sur Auth0 pour représenter cet utilisateur Facebook, le système dorsal aura besoin de certaines de ses informations, comme le nom, le nom de famille et l’adresse électronique. L’adresse électronique, si elle est fournie, sera signalée comme non vérifiée dans le profil utilisateur Auth0. - - Pour obtenir le jeton d’accès de session et le profil utilisateur, deux requêtes supplémentaires doivent être effectuées auprès de l’API Facebook. -
- -
- Effectuez une nouvelle requête GET vers le point de terminaison `/oauth/access_token` de l’API Facebook. Utilisez les paramètres de requête suivants : - - - `grant_type` : `fb_attenuate_token`. - - `fb_exchange_token` : le jeton d’accès reçu lors de la connexion. - - `client_id` : l’identifiant de votre application. Cette valeur provient du tableau de bord du développeur Facebook et devrait déjà être utilisée dans votre application si vous avez réussi à intégrer la connexion Facebook. - - Placez la logique de cette étape dans sa propre méthode. Vous effectuerez cet appel plus tard, à partir de la méthode ajoutée précédemment. - - L’exemple utilise la classe `GraphRequest` de la trousse SDK Facebook pour effectuer cette demande. -
- -
- Effectuez à présent une autre demande GET, comme dans l’étape précédente. Le chemin du point de terminaison correspondra à la valeur de l’identificateur de l’utilisateur figurant dans le résultat de la connexion Facebook (p. ex., `/904636746222815`). Utilisez les paramètres suivants : - - - `access_token` : le jeton d’accès reçu lors de la connexion. - - `fields` : les champs du profil utilisateur que vous souhaitez récupérer dans la réponse. Ces champs sont directement liés aux autorisations du bouton de connexion Facebook qui ont été configurées au début. Lorsqu’une autorisation est facultative, l’utilisateur doit d’abord consentir à y donner accès. Pour inscrire un utilisateur à Auth0, le nom complet et l’adresse électronique suffisent. -
- -
- Maintenant que les artefacts requis ont été obtenus, vous êtes prêt à les échanger contre les identifiants utilisateur Auth0, comme l’identifiant et les jetons d’accès. Mais d’abord, vous devez configurer la trousse SDK Auth0 pour qu’il effectue cette dernière demande. - - ### Obtenir les clés de votre application - - 1. Allez dans la section **Applications** de [Auth0 Dashboard](https://manage.auth0.com/) et sélectionnez l’application existante dans laquelle vous avez activé la fonction **Sign in with Facebook (Se connecter avec Facebook)**. Si vous avez besoin d’aide pour cette étape, veuillez consulter la section des exigences en haut de cet article. - 2. Copiez les valeurs **Domaine** et **Identifiant client** de la page des paramètres de l’application. Ces valeurs sont requises par la trousse SDK. - 3. Créez deux nouvelles ressources dans le fichier strings.xml de votre application Android pour les stocker. Les noms des clés doivent correspondre à ceux utilisés ci-dessous : - - ``` - - -     {yourDomain} - -     {yourClientId} - - - ``` - - ### Installer la trousse SDK Auth0 - - Dans votre application Android, ajoutez cette ligne au fichier app/build.gradle : - - ``` - dependencies { - implementation 'com.auth0.android:auth0:1.+' - } - ``` - - Il est maintenant temps d’exécuter la tâche Gradle Sync pour actualiser le projet et ses dépendances. - - ### Mise à jour du manifeste pour l’authentification Web - - Si votre application ne prévoit pas d’utiliser le module d’authentification Web fourni par la trousse SDK, vous devrez supprimer l’activité inutilisée du fichier AndroidManifest.xml pour éviter les problèmes liés au placeholder du manifeste. Pour ce faire, il suffit d’ajouter une déclaration d’activité et de l’annoter avec tools:node="remove". - - ```html - - - - - ``` - - Toutefois, si vous envisagez de prendre en charge l’authentification Web, rendez-vous [ici](https://auth0.com/docs/libraries/auth0-android#authentication-via-universal-login) pour savoir comment déclarer les placeholder du manifeste. -
- -
- Vous devez instancier la trousse SDK avant de l’utiliser. Définissez un champ au niveau de la classe et initialisez-le dans la méthode `onCreate`. Remarque : Les identifiants définis à l’étape précédente sont transmis au développeur `Auth0` et une nouvelle instance de `AuthenticationAPIClient` est créée avec lui. - - ``` - private AuthenticationAPIClient auth0Client; - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - - setContentView(R.layout.activity_login); - - Auth0 account = new Auth0(getString(R.string.com_auth0_client_id), getString(R.string.com_auth0_domain)); - - auth0Client = new AuthenticationAPIClient(account); - - //... - - } - ``` - - Créez la méthode qui contiendra la logique d’échange des deux artefacts obtenus contre les identifiants de l’utilisateur Auth0. Dans l’exemple, cette méthode s’appelle `exchangeTokens`. - - Le client de l’API déclare la méthode `loginWithNativeSocialToken` qui reçoit un jeton et un type de sujet. Le premier correspond au jeton de session et le second indique le type de connexion avec lequel le système dorsal tentera de s’authentifier. - - Pour la fonction native Connexion Facebook, vous devez utiliser la valeur suivante : `"http://auth0.com/oauth/token-type/facebook-info-session-access-token"` - - Les autres valeurs à configurer sont le profil utilisateur (en utilisant la clé `user_profile`) et la permission que vous demandez aux jetons Auth0 de contenir. - - - Nous recommandons de conserver toutes les valeurs immuables en tant que constantes au début de la classe. L’exemple utilise des constantes pour le type de jeton sujet, les permissions Facebook et les permissions Auth0. Pour en savoir plus sur les permissions Auth0, lisez cet article. - -
- -
- Maintenant que chaque étape est définie dans sa propre méthode, il est temps de tout regrouper dans la méthode `performLogin`. - - Si tout a bien fonctionné, vous devriez maintenant être en mesure de vous authentifier de manière native avec la trousse SDK de connexion à Facebook. Cela signifie que si l’application Facebook est installée sur l’appareil, l’authentification sera gérée par l’application et non par une application de navigateur. -
- - ## Étapes suivantes - - Beau travail! Si vous en êtes arrivé là, vous devriez avoir la connexion, la déconnexion et les informations de profil utilisateur actives dans votre application. - - Cela conclut notre tutoriel de démarrage rapide, mais il y a tellement plus à explorer. Pour en savoir plus sur ce que vous pouvez faire avec Auth0, consultez : - - * [Auth0 Dashboard](https://manage.auth0.com/#) : apprenez à configurer et gérer votre locataire et vos applications Auth0 - * [Auth0 Marketplace](https://marketplace.auth0.com/) : découvrez des intégrations que vous pouvez activer pour étendre les fonctionnalités d’Auth0 -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+--- +title: "Android – Connexion Facebook" +permalink: "interactive" +'description': "Ce tutoriel explique comment ajouter la connexion utilisateur à une application Android à l’aide de la méthode native Connexion Facebook." +'og:title': "Android – Connexion Facebook" +'og:description': "Ce tutoriel explique comment ajouter la connexion utilisateur à une application Android à l’aide de la méthode native Connexion Facebook." +'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/android.png" +'twitter:title': "Android – Connexion Facebook" +'twitter:description': "Ce tutoriel explique comment ajouter la connexion utilisateur à une application Android à l’aide de la méthode native Connexion Facebook." +--- + +import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; +import { LoggedInForm } from "/snippets/Login.jsx"; +import Performloginsimplecallback from "/snippets/quickstart/native/android-facebook-login/performLogin + SimpleCallback.mdx"; +import Oncreate from "/snippets/quickstart/native/android-facebook-login/onCreate.mdx"; +import Fetchsessiontoken from "/snippets/quickstart/native/android-facebook-login/fetchSessionToken.mdx"; +import Fetchuserprofile from "/snippets/quickstart/native/android-facebook-login/fetchUserProfile.mdx"; +import Exchangetokens from "/snippets/quickstart/native/android-facebook-login/exchangeTokens.mdx"; +import Performlogin from "/snippets/quickstart/native/android-facebook-login/performLogin.mdx"; + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + +export const sections = [ + { id: "configurations-requise", title: "Configurations requise" }, + { id: "avant-de-commencer", title: "Avant de commencer" }, + { id: "demande-d-autorisations-facebook", title: "Demande d’autorisations Facebook" }, + { id: "créer-la-méthode-performlogin", title: "Créer la méthode performLogin" }, + { id: "appeler-la-méthode-performlogin", title: "Appeler la méthode performLogin" }, + { id: "intégrer-facebook", title: "Intégrer Facebook" }, + { id: "récupérer-le-jeton-d-accès-à-la-session-facebook", title: "Récupérer le jeton d’accès à la session Facebook" }, + { id: "récupérer-le-profil-utilisateur-facebook", title: "Récupérer le profil utilisateur Facebook" }, + { id: "intégrer-auth0", title: "Intégrer Auth0" }, + { id: "échanger-les-données-reçues-contre-des-jetons-auth0", title: "Échanger les données reçues contre des jetons Auth0" }, + { id: "mettre-à-jour-la-méthode-performlogin", title: "Mettre à jour la méthode performLogin" } +] + + + + Ce tutoriel explique comment ajouter la connexion utilisateur à une application Android à l’aide de la méthode native Connexion Facebook. Nous vous recommandons de vous connecter pour suivre ce démarrage rapide avec les exemples configurés pour votre compte. + +
+ - Android Studio 3.6.1 + - Trousse SDK Android 25 + - Émulateur - Nexus 5X - Android 6.0 + + Ce tutoriel décrit comment mettre en œuvre la connexion avec la [trousse SDK Facebook](https://developers.facebook.com/docs/). +
+ +
+ - Installez et configurez la [trousse SDK Connexion Facebook](https://developers.facebook.com/docs/facebook-login/). Vous découvrirez également le processus de création d’une application Facebook sur [https://developers.facebook.com](https://developers.facebook.com/). **À la fin de cette étape, vous devriez avoir une application mobile fonctionnant avec la fonction de connexion Facebook intégrée.** + + Configurez votre application Auth0 dans le Dashboard pour utiliser la fonction Connexion Facebook en mode natif. Voir [Ajouter une connexion Facebook aux applications natives](https://auth0.com/docs/connections/nativesocial/facebook). **À la fin de cette étape, votre application sera en mesure d’implémenter la fonction Connexion Facebook en mode natif.** +
+ +
+ Votre application est déjà capable de se connecter à Facebook. Cependant, pour garantir un profil utilisateur riche, vous devez mettre à jour les autorisations avec lesquelles le bouton de connexion Facebook a été configuré. + + Définissez les autorisations demandées sur `public_profile` et `email`. De cette manière, l’adresse courriel de l’utilisateur sera également incluse dans la réponse, à condition que la demande d’accès soit acceptée par l’utilisateur. + + `loginButton.setPermissions(Arrays.asList("public_profile", "email"));` +
+ +
+ Maintenant, pour lancer le processus d’authentification avec Auth0, créez une nouvelle méthode où vous préparerez la charge utile à envoyer. + + Vous utiliserez une interface simple pour gérer nos rappels internes. + + Dans l’exemple, la méthode s’appelle `performLogin` et l’interface `SimpleCallback`. Ajoutez les deux. +
+ +
+ Maintenant, appelez la méthode de la méthode `onSuccess` de rappel (Callback) de connexion Facebook. +
+ +
+ Lorsque vous vous connectez à Facebook avec Auth0, le système dorsal effectue des vérifications en arrière-plan pour s’assurer que l’utilisateur est bien celui qu’il prétend être. Pour ce faire, il faut lui fournir un jeton d’accès à la session. + + En outre, si un utilisateur doit être créé sur Auth0 pour représenter cet utilisateur Facebook, le système dorsal aura besoin de certaines de ses informations, comme le nom, le nom de famille et l’adresse électronique. L’adresse électronique, si elle est fournie, sera signalée comme non vérifiée dans le profil utilisateur Auth0. + + Pour obtenir le jeton d’accès de session et le profil utilisateur, deux requêtes supplémentaires doivent être effectuées auprès de l’API Facebook. +
+ +
+ Effectuez une nouvelle requête GET vers le point de terminaison `/oauth/access_token` de l’API Facebook. Utilisez les paramètres de requête suivants : + + - `grant_type` : `fb_attenuate_token`. + - `fb_exchange_token` : le jeton d’accès reçu lors de la connexion. + - `client_id` : l’identifiant de votre application. Cette valeur provient du tableau de bord du développeur Facebook et devrait déjà être utilisée dans votre application si vous avez réussi à intégrer la connexion Facebook. + + Placez la logique de cette étape dans sa propre méthode. Vous effectuerez cet appel plus tard, à partir de la méthode ajoutée précédemment. + + L’exemple utilise la classe `GraphRequest` de la trousse SDK Facebook pour effectuer cette demande. +
+ +
+ Effectuez à présent une autre demande GET, comme dans l’étape précédente. Le chemin du point de terminaison correspondra à la valeur de l’identificateur de l’utilisateur figurant dans le résultat de la connexion Facebook (p. ex., `/904636746222815`). Utilisez les paramètres suivants : + + - `access_token` : le jeton d’accès reçu lors de la connexion. + - `fields` : les champs du profil utilisateur que vous souhaitez récupérer dans la réponse. Ces champs sont directement liés aux autorisations du bouton de connexion Facebook qui ont été configurées au début. Lorsqu’une autorisation est facultative, l’utilisateur doit d’abord consentir à y donner accès. Pour inscrire un utilisateur à Auth0, le nom complet et l’adresse électronique suffisent. +
+ +
+ Maintenant que les artefacts requis ont été obtenus, vous êtes prêt à les échanger contre les identifiants utilisateur Auth0, comme l’identifiant et les jetons d’accès. Mais d’abord, vous devez configurer la trousse SDK Auth0 pour qu’il effectue cette dernière demande. + + ### Obtenir les clés de votre application + + 1. Allez dans la section **Applications** de [Auth0 Dashboard](https://manage.auth0.com/) et sélectionnez l’application existante dans laquelle vous avez activé la fonction **Sign in with Facebook (Se connecter avec Facebook)**. Si vous avez besoin d’aide pour cette étape, veuillez consulter la section des exigences en haut de cet article. + 2. Copiez les valeurs **Domaine** et **Identifiant client** de la page des paramètres de l’application. Ces valeurs sont requises par la trousse SDK. + 3. Créez deux nouvelles ressources dans le fichier strings.xml de votre application Android pour les stocker. Les noms des clés doivent correspondre à ceux utilisés ci-dessous : + + ``` + + +     {yourDomain} + +     {yourClientId} + + + ``` + + ### Installer la trousse SDK Auth0 + + Dans votre application Android, ajoutez cette ligne au fichier app/build.gradle : + + ``` + dependencies { + implementation 'com.auth0.android:auth0:1.+' + } + ``` + + Il est maintenant temps d’exécuter la tâche Gradle Sync pour actualiser le projet et ses dépendances. + + ### Mise à jour du manifeste pour l’authentification Web + + Si votre application ne prévoit pas d’utiliser le module d’authentification Web fourni par la trousse SDK, vous devrez supprimer l’activité inutilisée du fichier AndroidManifest.xml pour éviter les problèmes liés au placeholder du manifeste. Pour ce faire, il suffit d’ajouter une déclaration d’activité et de l’annoter avec tools:node="remove". + + ```html + + + + + ``` + + Toutefois, si vous envisagez de prendre en charge l’authentification Web, rendez-vous [ici](https://auth0.com/docs/libraries/auth0-android#authentication-via-universal-login) pour savoir comment déclarer les placeholder du manifeste. +
+ +
+ Vous devez instancier la trousse SDK avant de l’utiliser. Définissez un champ au niveau de la classe et initialisez-le dans la méthode `onCreate`. Remarque : Les identifiants définis à l’étape précédente sont transmis au développeur `Auth0` et une nouvelle instance de `AuthenticationAPIClient` est créée avec lui. + + ``` + private AuthenticationAPIClient auth0Client; + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + setContentView(R.layout.activity_login); + + Auth0 account = new Auth0(getString(R.string.com_auth0_client_id), getString(R.string.com_auth0_domain)); + + auth0Client = new AuthenticationAPIClient(account); + + //... + + } + ``` + + Créez la méthode qui contiendra la logique d’échange des deux artefacts obtenus contre les identifiants de l’utilisateur Auth0. Dans l’exemple, cette méthode s’appelle `exchangeTokens`. + + Le client de l’API déclare la méthode `loginWithNativeSocialToken` qui reçoit un jeton et un type de sujet. Le premier correspond au jeton de session et le second indique le type de connexion avec lequel le système dorsal tentera de s’authentifier. + + Pour la fonction native Connexion Facebook, vous devez utiliser la valeur suivante : `"http://auth0.com/oauth/token-type/facebook-info-session-access-token"` + + Les autres valeurs à configurer sont le profil utilisateur (en utilisant la clé `user_profile`) et la permission que vous demandez aux jetons Auth0 de contenir. + + + Nous recommandons de conserver toutes les valeurs immuables en tant que constantes au début de la classe. L’exemple utilise des constantes pour le type de jeton sujet, les permissions Facebook et les permissions Auth0. Pour en savoir plus sur les permissions Auth0, lisez cet article. + +
+ +
+ Maintenant que chaque étape est définie dans sa propre méthode, il est temps de tout regrouper dans la méthode `performLogin`. + + Si tout a bien fonctionné, vous devriez maintenant être en mesure de vous authentifier de manière native avec la trousse SDK de connexion à Facebook. Cela signifie que si l’application Facebook est installée sur l’appareil, l’authentification sera gérée par l’application et non par une application de navigateur. +
+ + ## Étapes suivantes + + Beau travail! Si vous en êtes arrivé là, vous devriez avoir la connexion, la déconnexion et les informations de profil utilisateur actives dans votre application. + + Cela conclut notre tutoriel de démarrage rapide, mais il y a tellement plus à explorer. Pour en savoir plus sur ce que vous pouvez faire avec Auth0, consultez : + + * [Auth0 Dashboard](https://manage.auth0.com/#) : apprenez à configurer et gérer votre locataire et vos applications Auth0 + * [Auth0 Marketplace](https://marketplace.auth0.com/) : découvrez des intégrations que vous pouvez activer pour étendre les fonctionnalités d’Auth0 +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
diff --git a/main/docs/fr-ca/quickstart/native/android/interactive.mdx b/main/docs/fr-ca/quickstart/native/android/interactive.mdx index c491ddd61..305853729 100644 --- a/main/docs/fr-ca/quickstart/native/android/interactive.mdx +++ b/main/docs/fr-ca/quickstart/native/android/interactive.mdx @@ -1,217 +1,219 @@ ---- -title: "Ajouter une connexion à votre application Android" -permalink: "interactive" -'description': "Ce guide explique comment intégrer Auth0 à une application Android en utilisant la trousse SDK Auth0 Android." -'og:title': "Ajouter une connexion à votre application Android" -'og:description': "Ce guide explique comment intégrer Auth0 à une application Android en utilisant la trousse SDK Auth0 Android." -'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/android.png" -'twitter:title': "Ajouter une connexion à votre application Android" -'twitter:description': "Ce guide explique comment intégrer Auth0 à une application Android en utilisant la trousse SDK Auth0 Android." -sidebarTitle: Android ---- - -import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; -import { LoggedInForm } from "/snippets/Login.jsx"; -import Build from "/snippets/quickstart/native/android/build.gradle.mdx"; -import Build2 from "/snippets/quickstart/native/android/build.gradle2.mdx"; -import Strings from "/snippets/quickstart/native/android/strings.xml.mdx"; -import Mainactivity from "/snippets/quickstart/native/android/MainActivity.kt.mdx"; -import Mainactivity2 from "/snippets/quickstart/native/android/MainActivity.kt2.mdx"; -import Mainactivity3 from "/snippets/quickstart/native/android/MainActivity.kt3.mdx"; - -export const sections = [ - { id: "configuration-d-auth0", title: "Configuration d’Auth0" }, - { id: "installer-la-trousse-sdk-android-auth0", title: "Installer la trousse SDK Android Auth0" }, - { id: "ajouter-des-paramètres-fictifs-dans-le-manifeste", title: "Ajouter des paramètres fictifs dans le manifeste" }, - { id: "configuration-de-votre-application", title: "Configuration de votre application" }, - { id: "ajouter-une-fonctionnalité-de-connexion-à-votre-application", title: "Ajouter une fonctionnalité de connexion à votre application" }, - { id: "ajouter-une-fonctionnalité-de-déconnexion-à-votre-application", title: "Ajouter une fonctionnalité de déconnexion à votre application" }, - { id: "afficher-les-informations-du-profil-utilisateur", title: "Afficher les informations du profil utilisateur" } -] - - - -
- Pour utiliser les services Auth0, vous devez avoir une application installée dans Auth0 Dashboard. L’application Auth0 est l’endroit où vous allez configurer l’authentification pour votre projet. - - ### Configurer une application - - Utilisez le sélecteur interactif pour créer une nouvelle application Auth0 ou sélectionner une application existante qui représente le projet avec lequel vous souhaitez effectuer l’intégration. Dans Auth0, chaque application se voit attribuer un identifiant client unique alphanumérique que votre code d’application utilisera pour appeler les API Auth0 via la trousse SDK. - - Tous les paramètres que vous configurez à l’aide de ce guide de démarrage rapide seront automatiquement mis à jour pour votre application dans le [Tableau de bord](https://manage.auth0.com/#/), qui est l’endroit où vous pourrez gérer vos applications à l’avenir. - - Si vous préférez explorer une configuration complète, consultez plutôt un exemple d’application. - - ### Configuration des URL de rappel - - Une URL de rappel est l’URL de l’application vers laquelle Auth0 dirigera vos utilisateurs une fois qu’ils se seront authentifiés. Si vous ne définissez pas cette valeur, Auth0 ne renverra pas les utilisateurs vers votre application après leur connexion. - - - Si vous suivez notre projet à titre d’exemple, définissez ceci sur `demo://{yourDomain}/android/YOUR\_APP\_PACKAGE\_NAME/callback`. - - - ### Configuration des URL de déconnexion - - Une URL de déconnexion est l’URL de l’application vers laquelle Auth0 redirigera vos utilisateurs une fois qu’ils se seront déconnectés. Si vous ne définissez pas cette valeur, les utilisateurs ne pourront pas se déconnecter de votre application et recevront un message d’erreur. - - - Si vous suivez notre projet à titre d’exemple, définissez ceci sur `demo://{yourDomain}/android/YOUR\_APP\_PACKAGE\_NAME/callback` - -
- -
- Ajoutez la trousse SDK [Android Auth0](https://github.com/auth0/Auth0.Android) à votre projet. La bibliothèque adressera des demandes aux Authentication et Management API d’Auth0. - - Dans la section dépendances du `build.gradle` de votre application, ajoutez ce qui suit : - - ``` - implementation 'com.auth0.android:auth0:2. ' - ``` - - Veillez à cibler le code Java 8+ pour les plugiciels Android et Kotlin respectivement. -
- -
- La trousse SDK nécessite des paramètres fictifs dans le manifeste. Auth0 utilise des paramètres fictifs en interne pour définir un `intent-filter`, qui capture l’URL de rappel pour l’authentification. Vous devez définir le domaine du locataire Auth0 et le schéma de l’URL de rappel. - - Vous n’avez pas besoin de déclarer un `intent-filter` spécifique pour votre activité car vous avez défini les paramètres fictifs dans le manifeste avec vos valeurs Auth0 **Domaine** et **Schéma** et la bibliothèque traitera la redirection pour vous. - - - Nous avons utilisé la valeur `demo` pour `auth0Scheme` ici, afin qu’un schéma d’URL personnalisé puisse être utilisé pour l’URL vers laquelle Auth0 redirige après la connexion. L’alternative est `https` si vous voulez utiliser des [liens vers les applications Android](https://auth0.com/docs/applications/enable-android-app-links). Vous pouvez en savoir plus sur la définition de cette valeur dans le [SDK README d’Auth0.Android](https://github.com/auth0/Auth0.Android#a-note-about-app-deep-linking). - -
- -
- Pour que la trousse SDK fonctionne correctement, définissez les propriétés suivantes dans `strings.xml` : - - - `com_auth0_domain` : Le domaine de votre locataire Auth0. En général, vous le trouvez dans Auth0 Dashboard sous vos paramètres d’application dans le champ Domain (Domaine). Si vous utilisez un [domaine personnalisé](https://auth0.com/docs/custom-domains), définissez-le plutôt sur la valeur de votre domaine personnalisé. - - `com_auth0_client_id` : l’identificateur de l’application Auth0 que vous avez configurée précédemment dans ce guide rapide. Vous pouvez le trouver dans Auth0 Dashboard, dans les paramètres de votre application, dans le champ Client ID (ID client). - - Assurez-vous que le fichier `AndroidManifest.xml` spécifie l’autorisation `android.permissions.INTERNET` : - - ```html - - ``` - - Exécutez **Sync Project with Gradle Files** dans Android Studio ou exécutez `./gradlew clean assembleDebug` à partir de la ligne de commande. - - - Pour en savoir plus sur l’utilisation de Gradle, consultez la [documentation officielle de Gradle](https://gradle.org/getting-started-android-build/). - -
- -
- La [connexion universelle](https://auth0.com/docs/hosted-pages/login) est le moyen le plus simple de mettre en place l’authentification dans votre application. Nous recommandons de l’utiliser pour une meilleure expérience, une meilleure sécurité et un plus grand nombre de fonctionnalités. - - Dans la méthode `onCreate`, créez une nouvelle instance de la classe `Auth0` qui contiendra les informations d’identification de l’utilisateur. - - Créez une méthode `loginWithBrowser` et utilisez la classe `WebAuthProvider` pour vous authentifier avec n’importe quelle connexion que vous avez activée sur votre application dans [Auth0 Dashboard](https://manage.auth0.com/#/). Ici, vous pouvez passer la valeur du schéma qui a été utilisée dans le paramètre fictif du manifeste `auth0Scheme` dans le cadre de la configuration initiale. - - Après avoir appelé la fonction `WebAuthProvider#start`, le navigateur se lance et affiche la page de connexion. Une fois l’utilisateur authentifié, l’URL de rappel est appelée. L’URL de rappel contient le résultat final du processus d’authentification. - - - ##### Point de contrôle - Ajoutez un bouton à votre application qui appelle `loginWithBrowser`. Lorsque vous cliquez dessus, vérifiez que votre application Next.js vous redirige vers la page [Connexion universelle Auth0](https://auth0.com/universal-login) et que vous pouvez maintenant vous connecter ou vous inscrire en utilisant un nom d’utilisateur et un mot de passe ou un fournisseur social. - Une fois l’opération terminée, vérifiez qu’Auth0 vous redirige vers votre application. - -
- -
- Utilisez `WebAuthProvider` pour supprimer le témoin défini par le navigateur au moment de l’authentification, de sorte que les utilisateurs soient obligés de saisir à nouveau leurs identifiants la prochaine fois qu’ils essaient de s’authentifier. - - Ajoutez une méthode `logout` à votre application pour supprimer la session de l’utilisateur et le déconnecter de l’application. Ici, vous pouvez passer la valeur du schéma qui a été utilisée dans le placeholder du manifeste `auth0Scheme` dans le cadre de la configuration initiale. - - Utilisez la classe `WebAuthProvider` pour mettre en œuvre la déconnexion. Cet appel ouvre le navigateur et dirige l’utilisateur vers le point de terminaison de déconnexion. Si l’utilisateur annule la déconnexion, envisagez de le rediriger vers l’URL précédente. - - - ##### Point de contrôle - Ajoutez un bouton à votre application qui appelle `logout` et déconnecte l’utilisateur de votre application. Lorsque vous cliquez sur ce bouton, vérifiez que votre application Android vous redirige vers la page de déconnexion et vous renvoie, et que vous n’êtes plus connecté à votre application. - -
- -
- Utilisez la classe `AuthenticationAPIClient` pour [récupérer le profil utilisateur auprès de Auth0](https://auth0.com/docs/users/user-profiles#user-profile-management-api-access). Pour ce faire, les éléments suivants sont nécessaires : - - - Le jeton d’accès renvoyé par la phase de connexion - - Le `WebAuthProvider.login` doit contenir la permission `profile` - - Vous devez spécifier la permission `email` si vous avez besoin de récupérer l’adresse courriel de l’utilisateur. - - - Ce guide rapide définit par défaut les permissions `openid profile email` lors de l’étape de connexion ci-dessus. - - - L’exemple suivant démontre une fonction qui peut être utilisée pour récupérer le profil utilisateur et l’afficher à l’écran : - - - ##### Point de contrôle - Appelez la fonction `showUserProfile` après la connexion. Vérifiez que le rappel `onSuccess` renvoie les informations du profil utilisateur. - -
- - ## Étapes suivantes - - Beau travail! Si vous en êtes arrivé là, vous devriez avoir la connexion, la déconnexion et les informations de profil utilisateur actives dans votre application. - - Cela conclut notre tutoriel de démarrage rapide, mais il y a tellement plus à explorer. Pour en savoir plus sur ce que vous pouvez faire avec Auth0, consultez : - - * [Auth0 Dashboard](https://manage.auth0.com/#) : apprenez à configurer et gérer votre locataire et vos applications Auth0 - * [Trousse SDK Auth0.Android](https://github.com/auth0/Auth0.Android) : explorez en détail la trousse SDK utilisée dans ce tutoriel - * [Auth0 Marketplace](https://marketplace.auth0.com/) : découvrez des intégrations que vous pouvez activer pour étendre les fonctionnalités d’Auth0 -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+--- +title: "Ajouter une connexion à votre application Android" +permalink: "interactive" +'description': "Ce guide explique comment intégrer Auth0 à une application Android en utilisant la trousse SDK Auth0 Android." +'og:title': "Ajouter une connexion à votre application Android" +'og:description': "Ce guide explique comment intégrer Auth0 à une application Android en utilisant la trousse SDK Auth0 Android." +'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/android.png" +'twitter:title': "Ajouter une connexion à votre application Android" +'twitter:description': "Ce guide explique comment intégrer Auth0 à une application Android en utilisant la trousse SDK Auth0 Android." +sidebarTitle: Android +--- + +import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; +import { LoggedInForm } from "/snippets/Login.jsx"; +import Build from "/snippets/quickstart/native/android/build.gradle.mdx"; +import Build2 from "/snippets/quickstart/native/android/build.gradle2.mdx"; +import Strings from "/snippets/quickstart/native/android/strings.xml.mdx"; +import Mainactivity from "/snippets/quickstart/native/android/MainActivity.kt.mdx"; +import Mainactivity2 from "/snippets/quickstart/native/android/MainActivity.kt2.mdx"; +import Mainactivity3 from "/snippets/quickstart/native/android/MainActivity.kt3.mdx"; + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + +export const sections = [ + { id: "configuration-d-auth0", title: "Configuration d’Auth0" }, + { id: "installer-la-trousse-sdk-android-auth0", title: "Installer la trousse SDK Android Auth0" }, + { id: "ajouter-des-paramètres-fictifs-dans-le-manifeste", title: "Ajouter des paramètres fictifs dans le manifeste" }, + { id: "configuration-de-votre-application", title: "Configuration de votre application" }, + { id: "ajouter-une-fonctionnalité-de-connexion-à-votre-application", title: "Ajouter une fonctionnalité de connexion à votre application" }, + { id: "ajouter-une-fonctionnalité-de-déconnexion-à-votre-application", title: "Ajouter une fonctionnalité de déconnexion à votre application" }, + { id: "afficher-les-informations-du-profil-utilisateur", title: "Afficher les informations du profil utilisateur" } +] + + + +
+ Pour utiliser les services Auth0, vous devez avoir une application installée dans Auth0 Dashboard. L’application Auth0 est l’endroit où vous allez configurer l’authentification pour votre projet. + + ### Configurer une application + + Utilisez le sélecteur interactif pour créer une nouvelle application Auth0 ou sélectionner une application existante qui représente le projet avec lequel vous souhaitez effectuer l’intégration. Dans Auth0, chaque application se voit attribuer un identifiant client unique alphanumérique que votre code d’application utilisera pour appeler les API Auth0 via la trousse SDK. + + Tous les paramètres que vous configurez à l’aide de ce guide de démarrage rapide seront automatiquement mis à jour pour votre application dans le [Tableau de bord](https://manage.auth0.com/#/), qui est l’endroit où vous pourrez gérer vos applications à l’avenir. + + Si vous préférez explorer une configuration complète, consultez plutôt un exemple d’application. + + ### Configuration des URL de rappel + + Une URL de rappel est l’URL de l’application vers laquelle Auth0 dirigera vos utilisateurs une fois qu’ils se seront authentifiés. Si vous ne définissez pas cette valeur, Auth0 ne renverra pas les utilisateurs vers votre application après leur connexion. + + + Si vous suivez notre projet à titre d’exemple, définissez ceci sur `demo://{yourDomain}/android/YOUR\_APP\_PACKAGE\_NAME/callback`. + + + ### Configuration des URL de déconnexion + + Une URL de déconnexion est l’URL de l’application vers laquelle Auth0 redirigera vos utilisateurs une fois qu’ils se seront déconnectés. Si vous ne définissez pas cette valeur, les utilisateurs ne pourront pas se déconnecter de votre application et recevront un message d’erreur. + + + Si vous suivez notre projet à titre d’exemple, définissez ceci sur `demo://{yourDomain}/android/YOUR\_APP\_PACKAGE\_NAME/callback` + +
+ +
+ Ajoutez la trousse SDK [Android Auth0](https://github.com/auth0/Auth0.Android) à votre projet. La bibliothèque adressera des demandes aux Authentication et Management API d’Auth0. + + Dans la section dépendances du `build.gradle` de votre application, ajoutez ce qui suit : + + ``` + implementation 'com.auth0.android:auth0:2. ' + ``` + + Veillez à cibler le code Java 8+ pour les plugiciels Android et Kotlin respectivement. +
+ +
+ La trousse SDK nécessite des paramètres fictifs dans le manifeste. Auth0 utilise des paramètres fictifs en interne pour définir un `intent-filter`, qui capture l’URL de rappel pour l’authentification. Vous devez définir le domaine du locataire Auth0 et le schéma de l’URL de rappel. + + Vous n’avez pas besoin de déclarer un `intent-filter` spécifique pour votre activité car vous avez défini les paramètres fictifs dans le manifeste avec vos valeurs Auth0 **Domaine** et **Schéma** et la bibliothèque traitera la redirection pour vous. + + + Nous avons utilisé la valeur `demo` pour `auth0Scheme` ici, afin qu’un schéma d’URL personnalisé puisse être utilisé pour l’URL vers laquelle Auth0 redirige après la connexion. L’alternative est `https` si vous voulez utiliser des [liens vers les applications Android](https://auth0.com/docs/applications/enable-android-app-links). Vous pouvez en savoir plus sur la définition de cette valeur dans le [SDK README d’Auth0.Android](https://github.com/auth0/Auth0.Android#a-note-about-app-deep-linking). + +
+ +
+ Pour que la trousse SDK fonctionne correctement, définissez les propriétés suivantes dans `strings.xml` : + + - `com_auth0_domain` : Le domaine de votre locataire Auth0. En général, vous le trouvez dans Auth0 Dashboard sous vos paramètres d’application dans le champ Domain (Domaine). Si vous utilisez un [domaine personnalisé](https://auth0.com/docs/custom-domains), définissez-le plutôt sur la valeur de votre domaine personnalisé. + - `com_auth0_client_id` : l’identificateur de l’application Auth0 que vous avez configurée précédemment dans ce guide rapide. Vous pouvez le trouver dans Auth0 Dashboard, dans les paramètres de votre application, dans le champ Client ID (ID client). + + Assurez-vous que le fichier `AndroidManifest.xml` spécifie l’autorisation `android.permissions.INTERNET` : + + ```html + + ``` + + Exécutez **Sync Project with Gradle Files** dans Android Studio ou exécutez `./gradlew clean assembleDebug` à partir de la ligne de commande. + + + Pour en savoir plus sur l’utilisation de Gradle, consultez la [documentation officielle de Gradle](https://gradle.org/getting-started-android-build/). + +
+ +
+ La [connexion universelle](https://auth0.com/docs/hosted-pages/login) est le moyen le plus simple de mettre en place l’authentification dans votre application. Nous recommandons de l’utiliser pour une meilleure expérience, une meilleure sécurité et un plus grand nombre de fonctionnalités. + + Dans la méthode `onCreate`, créez une nouvelle instance de la classe `Auth0` qui contiendra les informations d’identification de l’utilisateur. + + Créez une méthode `loginWithBrowser` et utilisez la classe `WebAuthProvider` pour vous authentifier avec n’importe quelle connexion que vous avez activée sur votre application dans [Auth0 Dashboard](https://manage.auth0.com/#/). Ici, vous pouvez passer la valeur du schéma qui a été utilisée dans le paramètre fictif du manifeste `auth0Scheme` dans le cadre de la configuration initiale. + + Après avoir appelé la fonction `WebAuthProvider#start`, le navigateur se lance et affiche la page de connexion. Une fois l’utilisateur authentifié, l’URL de rappel est appelée. L’URL de rappel contient le résultat final du processus d’authentification. + + + ##### Point de contrôle + Ajoutez un bouton à votre application qui appelle `loginWithBrowser`. Lorsque vous cliquez dessus, vérifiez que votre application Next.js vous redirige vers la page [Connexion universelle Auth0](https://auth0.com/universal-login) et que vous pouvez maintenant vous connecter ou vous inscrire en utilisant un nom d’utilisateur et un mot de passe ou un fournisseur social. + Une fois l’opération terminée, vérifiez qu’Auth0 vous redirige vers votre application. + +
+ +
+ Utilisez `WebAuthProvider` pour supprimer le témoin défini par le navigateur au moment de l’authentification, de sorte que les utilisateurs soient obligés de saisir à nouveau leurs identifiants la prochaine fois qu’ils essaient de s’authentifier. + + Ajoutez une méthode `logout` à votre application pour supprimer la session de l’utilisateur et le déconnecter de l’application. Ici, vous pouvez passer la valeur du schéma qui a été utilisée dans le placeholder du manifeste `auth0Scheme` dans le cadre de la configuration initiale. + + Utilisez la classe `WebAuthProvider` pour mettre en œuvre la déconnexion. Cet appel ouvre le navigateur et dirige l’utilisateur vers le point de terminaison de déconnexion. Si l’utilisateur annule la déconnexion, envisagez de le rediriger vers l’URL précédente. + + + ##### Point de contrôle + Ajoutez un bouton à votre application qui appelle `logout` et déconnecte l’utilisateur de votre application. Lorsque vous cliquez sur ce bouton, vérifiez que votre application Android vous redirige vers la page de déconnexion et vous renvoie, et que vous n’êtes plus connecté à votre application. + +
+ +
+ Utilisez la classe `AuthenticationAPIClient` pour [récupérer le profil utilisateur auprès de Auth0](https://auth0.com/docs/users/user-profiles#user-profile-management-api-access). Pour ce faire, les éléments suivants sont nécessaires : + + - Le jeton d’accès renvoyé par la phase de connexion + - Le `WebAuthProvider.login` doit contenir la permission `profile` + + Vous devez spécifier la permission `email` si vous avez besoin de récupérer l’adresse courriel de l’utilisateur. + + + Ce guide rapide définit par défaut les permissions `openid profile email` lors de l’étape de connexion ci-dessus. + + + L’exemple suivant démontre une fonction qui peut être utilisée pour récupérer le profil utilisateur et l’afficher à l’écran : + + + ##### Point de contrôle + Appelez la fonction `showUserProfile` après la connexion. Vérifiez que le rappel `onSuccess` renvoie les informations du profil utilisateur. + +
+ + ## Étapes suivantes + + Beau travail! Si vous en êtes arrivé là, vous devriez avoir la connexion, la déconnexion et les informations de profil utilisateur actives dans votre application. + + Cela conclut notre tutoriel de démarrage rapide, mais il y a tellement plus à explorer. Pour en savoir plus sur ce que vous pouvez faire avec Auth0, consultez : + + * [Auth0 Dashboard](https://manage.auth0.com/#) : apprenez à configurer et gérer votre locataire et vos applications Auth0 + * [Trousse SDK Auth0.Android](https://github.com/auth0/Auth0.Android) : explorez en détail la trousse SDK utilisée dans ce tutoriel + * [Auth0 Marketplace](https://marketplace.auth0.com/) : découvrez des intégrations que vous pouvez activer pour étendre les fonctionnalités d’Auth0 +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
diff --git a/main/docs/fr-ca/quickstart/native/device/interactive.mdx b/main/docs/fr-ca/quickstart/native/device/interactive.mdx index 2b5a6b7f7..efca010ea 100644 --- a/main/docs/fr-ca/quickstart/native/device/interactive.mdx +++ b/main/docs/fr-ca/quickstart/native/device/interactive.mdx @@ -12,6 +12,8 @@ permalink: "interactive" import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; import { LoggedInForm } from "/snippets/Login.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + export const sections = [ { id: "conditions-requises", title: "Conditions requises" }, { id: "recevoir-le-code-de-l-appareil", title: "Recevoir le code de l’appareil" }, @@ -50,7 +52,7 @@ export const sections = [ Pour obtenir le code de l’appareil, votre application doit appeler le [Authorize endpoint (Point de terminaison d’autorisation)](/docs/api/authentication#-post-oauth-device-code-) d’Authentication API du flux d’autorisation de l’appareil : - + ```bash cURL lines curl --request post \ --url 'https://dev-gja8kxz4ndtex3rq.us.auth0.com/oauth/device/code' \ @@ -199,7 +201,7 @@ export const sections = [ }) dataTask.resume() ``` - + diff --git a/main/docs/fr-ca/quickstart/native/flutter/interactive.mdx b/main/docs/fr-ca/quickstart/native/flutter/interactive.mdx index ed936d749..95255a64e 100644 --- a/main/docs/fr-ca/quickstart/native/flutter/interactive.mdx +++ b/main/docs/fr-ca/quickstart/native/flutter/interactive.mdx @@ -1,239 +1,241 @@ ---- -title: "Ajouter une fonctionnalité de connexion à votre application Flutter" -permalink: "interactive" -'description': "Ce guide explique comment intégrer Auth0 à une application Flutter à l’aide de la trousse SDK Flutter Auth0." -'og:title': "Ajouter une fonctionnalité de connexion à votre application Flutter" -'og:description': "Ce guide explique comment intégrer Auth0 à une application Flutter à l’aide de la trousse SDK Flutter Auth0." -'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/flutter.jpeg" -'twitter:title': "Ajouter une fonctionnalité de connexion à votre application Flutter" -'twitter:description': "Ce guide explique comment intégrer Auth0 à une application Flutter à l’aide de la trousse SDK Flutter Auth0." -sidebarTitle: Flutter ---- - -import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; -import { LoggedInForm } from "/snippets/Login.jsx"; -import Build from "/snippets/quickstart/native/flutter/build.gradle.mdx"; -import MainView from "/snippets/quickstart/native/flutter/main_view.dart.mdx"; -import MainView2 from "/snippets/quickstart/native/flutter/main_view.dart2.mdx"; -import ProfileView from "/snippets/quickstart/native/flutter/profile_view.dart.mdx"; - -export const sections = [ - { id: "configuration-d-auth0", title: "Configuration d’Auth0" }, - { id: "installer-la-trousse-sdk-flutter-auth0", title: "Installer la trousse SDK Flutter Auth0" }, - { id: "configurer-android", title: "Configurer Android" }, - { id: "configurer-ios-macos", title: "Configurer iOS/macOS" }, - { id: "ajouter-une-fonctionnalité-de-connexion-à-votre-application", title: "Ajouter une fonctionnalité de connexion à votre application" }, - { id: "ajouter-une-fonctionnalité-de-déconnexion-à-votre-application", title: "Ajouter une fonctionnalité de déconnexion à votre application" }, - { id: "afficher-les-informations-du-profil-utilisateur", title: "Afficher les informations du profil utilisateur" } -] - - - - Auth0 vous permet d’ajouter rapidement l’authentification et d’accéder aux informations relatives au profil de l’utilisateur dans votre application. Ce guide explique comment intégrer Auth0 à une application Flutter à l’aide de la [trousse SDK Flutter Auth0](https://github.com/auth0/auth0-flutter). - - - La trousse SDK Flutter ne prend actuellement en charge que les applications Flutter pour Android, iOS et macOS. - - - Ce guide de démarrage rapide suppose que vous avez déjà une application [Flutter](https://flutter.dev/) installée et active. Si ce n’est pas le cas, consultez les [guides « Getting started » (Premiers pas) de Flutter](https://docs.flutter.dev/get-started/install) pour commencer avec une application simple. - - Vous devez également être familiarisé avec [Outil de ligne de commande Flutter](https://docs.flutter.dev/reference/flutter-cli). - -
- Pour utiliser les services Auth0, vous devez avoir une application installée dans Auth0 Dashboard. L’application Auth0 est l’endroit où vous allez configurer le fonctionnement de l’authentification pour votre projet. - - ### Configurer une application Auth0. - - Utilisez le sélecteur interactif pour créer une nouvelle application Auth0 ou sélectionner une application Auth0 **Native** existante. Dans Auth0, il est attribué à chaque application un identifiant client unique alphanumérique que votre code d’application utilisera pour appeler les API Auth0 via la trousse SDK. - - Tous les paramètres que vous configurez à l’aide de ce guide rapide seront automatiquement mis à jour pour votre application dans le [Dashboard](https://manage.auth0.com/dashboard/us/auth0-dsepaid/), qui est l’endroit où vous pourrez gérer vos applications à l’avenir. - - Si vous préférez explorer une configuration complète, consultez plutôt un exemple d’application. - - ### Configurer les URL de rappel et les URL de déconnexion - - Les Callback URL et les URL de déconnexion sont des URL qu’invoque Auth0 pour rediriger vers votre application. Auth0 invoque l’URL de rappel après avoir authentifié l’utilisateur, et l’URL de déconnexion après avoir supprimé le témoin de session. Si les Callback URL et les URL de déconnexion ne sont pas définies, les utilisateurs ne pourront pas se connecter ou se déconnecter de l’application et recevront un message d’erreur. - - Définissez les Callback URL et les URL de déconnexion sur les valeurs suivantes, en fonction de votre plateforme. - - - Sur Android, la valeur du paramètre fictif `SCHEME` peut être `https` ou un autre schéma personnalisé. Les schémas `https` nécessitent l’activation des [liens d’application Android](https://auth0.com/docs/get-started/applications/enable-android-app-links-support). - Sur iOS 17.4+ et macOS 14.4+, il est possible d’utiliser des liens universels (`https`) comme URL Callback et de déconnexion. Lorsqu’activé, la trousse SDK reviendra à l’utilisation d’un schéma d’URL personnalisé sur les anciennes versions iOS/MacOS – [l’identificateur de bundle](https://developer.apple.com/documentation/appstoreconnectapi/bundle\_ids)de votre application. **Cette fonctionnalité nécessite un Xcode 15.3+ et un compte Apple Developer payant**. - - - #### Android - - `SCHEME://{yourDomain}/android/YOUR_PACKAGE_NAME/callback` - - #### iOS - - `https://{yourDomain}/ios/YOUR_BUNDLE_IDENTIFIER/callback,` - - `YOUR_BUNDLE_IDENTIFIER://{yourDomain}/ios/YOUR_BUNDLE_IDENTIFIER/callback` - - #### macOS - - `https://{yourDomain}/macos/YOUR_BUNDLE_IDENTIFIER/callback,` - - `YOUR_BUNDLE_IDENTIFIER://{yourDomain}/macos/YOUR_BUNDLE_IDENTIFIER/callback` - - Par exemple, si l’identifiant de votre bundle iOS était `com.example.MyApp` et votre domaine Auth0 était `example.us.auth0.com`, alors cette valeur serait : - - `https://example.us.auth0.com/ios/com.example.MyApp/callback,` - - `com.example.MyApp://example.us.auth0.com/ios/com.example.MyApp/callback` -
- -
- Ajoutez la trousse SDK Flutter Auth0 au projet : - - `flutter pub add auth0_flutter` -
- -
- Si vous ne développez pas pour la plateforme Android, ignorez cette étape. - - La trousse SDK nécessite des placeholder dans le manifeste. Auth0 utilise des placeholder en interne pour définir un `intent-filter`, qui capture l’URL de rappel d’authentification. Vous devez définir le domaine du locataire Auth0 et le schéma de l’URL de rappel. - - L’[exemple](https://github.com/auth0-samples/auth0-flutter-samples/tree/main/sample/android) utilise les placeholder suivants : - - - `auth0Domain` : Le domaine de votre locataire Auth0. En général, vous le trouverez dans Auth0 Dashboard sous vos **Application Settings (Paramètres d’application)** dans le champ **Domain (Domaine)**. Si vous utilisez un domaine personnalisé, indiquez dans ce champ votre domaine personnalisé. - - `auth0Scheme` : Le schéma à utiliser. Peut être un schéma personnalisé, ou https si vous souhaitez utiliser les [liens d’application Android](https://auth0.com/docs/applications/enable-android-app-links). Vous pouvez en savoir plus sur la définition de cette valeur dans le [SDK README d’Auth0.Android](https://github.com/auth0/Auth0.Android#a-note-about-app-deep-linking). - - - Vous n’avez pas besoin de déclarer un `intent-filter` spécifique pour votre activité car vous avez défini les paramètres fictifs dans le manifeste avec vos valeurs Auth0 **Domain** et **Scheme**. La bibliothèque gère la redirection pour vous. - - - Exécutez **Sync Project with Gradle Files** dans Android Studio pour appliquer vos modifications. -
- -
- Si vous ne développez pas pour les plateformes iOS ou macOS, ignorez cette étape. - - - Cette étape nécessite un compte Apple Developer payant. Il est nécessaire d’utiliser des liens universels comme URL Callback et de déconnexion. Ignorez cette étape pour utiliser plutôt un schéma d’URL personnalisé. - - - ### Configurer Team ID et l’identifiant du bundle - - Allez à la [page des paramètres](https://manage.auth0.com/#/applications/%7ByourClientId%7D/settings) de votre application Auth0, faites défiler jusqu’en bas, et ouvrez **Advanced Settings (Paramètres avancés) > Device Settings (Paramètres de l’appareil)**. Dans la section **iOS**, définissez **Team ID** sur votre [Apple Team ID](https://developer.apple.com/help/account/manage-your-team/locate-your-team-id/) et **App ID** sur l’identificateur du bundle de votre application. - - ![null](/docs/images/fr-ca/cdy7uua7fh8z/7wetuICumueyqt6dbB32ro/00f8484daece173bdefedab166fdd837/IOS_Settings_-_French.png) - - Cette action ajoutera votre application au fichier `apple-app-site-association` de votre locataire Auth0. - - ### Ajouter la capacité de domaine associé - - Ouvrez votre application dans Xcode en exécutant `open ios/Runner.xcworkspace` (ou `open macos/Runner.xcworkspace` pour macOS). Allez à l’[onglet](https://developer.apple.com/documentation/xcode/adding-capabilities-to-your-app#Add-a-capability)**Signing and Capabilities (Signature et capacités)** des paramètres de la cible de l’**exécuteur**, puis appuyez sur le bouton **+ Capability (Capabilité)**. Puis sélectionnez **Associated Domains (Domaines associés)**. - - ![null](/docs/images/fr-ca/cdy7uua7fh8z/3GO76kXynaieKs5CSj3UTp/1cc577b56d00bc3bad877e31b848c1ec/ios-xcode-capabilities.png) - - Ensuite, ajoutez l’[entrée](https://developer.apple.com/documentation/xcode/configuring-an-associated-domain#Define-a-service-and-its-associated-domain) suivante sous **Associated Domains (Domaines associés)** : - - `webcredentials:{yourDomain}` - - Si vous avez un domaine personnalisé, utilisez-le à la place du domaine Auth0 de la page des paramètres. - - - Pour que le domaine associé fonctionne, votre application doit être signée avec votre certificat d’équipe **même lors du développement pour le simulateur iOS**. Assurez-vous d’utiliser Apple Team dont la Team ID (ID d’équipe) est configurée dans la page des paramètres de votre application Auth0. - -
- -
- La connexion universelle est le moyen le plus simple de mettre en place l’authentification dans votre application. Nous recommandons de l’utiliser pour une meilleure expérience, une meilleure sécurité et un plus grand nombre de fonctionnalités. - - Intégrez la connexion universelle Auth0 dans votre application Flutter en utilisant la classe `Auth0`. Redirigez vos utilisateurs vers la page de connexion universelle Auth0 en utilisant `webAuthentication().login()`. Il s’agit d’une fonctionnalité `Future` pour que vous récupériez les jetons de l’utilisateur. - - **Android** : si vous utilisez un schéma personnalisé, passez ce schéma à la méthode de connexion afin que le SDK puisse assurer un aller-retour vers la page de connexion : - - `await auth0.webAuthentication(scheme: ’YOUR CUSTOM SCHEME’).login();` - - Lorsqu’un utilisateur se connecte, il est redirigé vers votre application. Puis, vous pouvez accéder à l’identifiant et aux jetons d’accès de cet utilisateur. - - - ##### Point de contrôle - Ajoutez un bouton à votre application qui appelle `webAuthentication().login()` et déconnecte l’utilisateur de votre application. Vérifiez que vous êtes redirigé vers Auth0 pour l’authentification, puis renvoyé vers votre application. - Vérifiez que vous pouvez accéder aux jetons sur le résultat de l’appel `login`. - -
- -
- Pour déconnecter les utilisateurs, redirigez-les vers le point de terminaison Auth0 pour effacer leur session de connexion en appelant la trousse SDK Flutter Auth0 `webAuthentication().logout()`. En savoir plus sur la déconnexion d’Auth0. - - **Android** : si vous utilisez un schéma personnalisé, passez ce schéma à la méthode de déconnexion afin que la trousse SDK puisse renvoyer correctement vers votre application : - - `await auth0.webAuthentication(scheme: ’YOUR CUSTOM SCHEME’).logout();` - - - ##### Point de contrôle - Ajoutez un bouton à votre application qui appelle `webAuthentication().logout()` et déconnecte l’utilisateur de votre application. Lorsque vous le sélectionnez, vérifiez que votre application Flutter vous redirige vers le point de terminaison de déconnexion et vice-versa. Vous ne devriez pas être connecté à votre application. - -
- -
- Le profil utilisateur récupère automatiquement les propriétés du profil utilisateur pour vous lorsque vous appelez `webAuthentication().login()`. L’objet retourné à partir de l’étape de connexion contient une propriété `user` avec toutes les propriétés du profil utilisateur, qui est renseigné en décodant le jeton d’ID. - - - ##### Point de contrôle - Connectez-vous et inspectez la propriété `user` par rapport au résultat. Vérifiez les informations de profil utilisateur actuel, telles que son `email` ou `name`. - -
- - ## Étapes suivantes - - Beau travail! Si vous en êtes arrivé là, vous devriez avoir la connexion, la déconnexion et les informations de profil utilisateur actives dans votre application. - - Cela conclut notre tutoriel de démarrage rapide, mais il y a tellement plus à explorer. Pour en savoir plus sur ce que vous pouvez faire avec Auth0, consultez : - - * [Auth0 Dashboard](https://manage.auth0.com/#) : apprenez à configurer et gérer votre locataire et vos applications Auth0 - * [Trousse SDK auth0-flutter](https://www.github.com/auth0/auth0-flutter/) : explorez en détail la trousse SDK utilisée dans ce tutoriel - * [Auth0 Marketplace](https://marketplace.auth0.com/) : découvrez des intégrations que vous pouvez activer pour étendre les fonctionnalités d’Auth0 - * [Configure other identity providers](/docs/identityproviders) - * [Enable multifactor authentication](/docs/multifactor-authentication) - * [Learn about attack protection](/docs/attack-protection) - * [Learn about Actions](/docs/customize/actions) -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+--- +title: "Ajouter une fonctionnalité de connexion à votre application Flutter" +permalink: "interactive" +'description': "Ce guide explique comment intégrer Auth0 à une application Flutter à l’aide de la trousse SDK Flutter Auth0." +'og:title': "Ajouter une fonctionnalité de connexion à votre application Flutter" +'og:description': "Ce guide explique comment intégrer Auth0 à une application Flutter à l’aide de la trousse SDK Flutter Auth0." +'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/flutter.jpeg" +'twitter:title': "Ajouter une fonctionnalité de connexion à votre application Flutter" +'twitter:description': "Ce guide explique comment intégrer Auth0 à une application Flutter à l’aide de la trousse SDK Flutter Auth0." +sidebarTitle: Flutter +--- + +import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; +import { LoggedInForm } from "/snippets/Login.jsx"; +import Build from "/snippets/quickstart/native/flutter/build.gradle.mdx"; +import MainView from "/snippets/quickstart/native/flutter/main_view.dart.mdx"; +import MainView2 from "/snippets/quickstart/native/flutter/main_view.dart2.mdx"; +import ProfileView from "/snippets/quickstart/native/flutter/profile_view.dart.mdx"; + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + +export const sections = [ + { id: "configuration-d-auth0", title: "Configuration d’Auth0" }, + { id: "installer-la-trousse-sdk-flutter-auth0", title: "Installer la trousse SDK Flutter Auth0" }, + { id: "configurer-android", title: "Configurer Android" }, + { id: "configurer-ios-macos", title: "Configurer iOS/macOS" }, + { id: "ajouter-une-fonctionnalité-de-connexion-à-votre-application", title: "Ajouter une fonctionnalité de connexion à votre application" }, + { id: "ajouter-une-fonctionnalité-de-déconnexion-à-votre-application", title: "Ajouter une fonctionnalité de déconnexion à votre application" }, + { id: "afficher-les-informations-du-profil-utilisateur", title: "Afficher les informations du profil utilisateur" } +] + + + + Auth0 vous permet d’ajouter rapidement l’authentification et d’accéder aux informations relatives au profil de l’utilisateur dans votre application. Ce guide explique comment intégrer Auth0 à une application Flutter à l’aide de la [trousse SDK Flutter Auth0](https://github.com/auth0/auth0-flutter). + + + La trousse SDK Flutter ne prend actuellement en charge que les applications Flutter pour Android, iOS et macOS. + + + Ce guide de démarrage rapide suppose que vous avez déjà une application [Flutter](https://flutter.dev/) installée et active. Si ce n’est pas le cas, consultez les [guides « Getting started » (Premiers pas) de Flutter](https://docs.flutter.dev/get-started/install) pour commencer avec une application simple. + + Vous devez également être familiarisé avec [Outil de ligne de commande Flutter](https://docs.flutter.dev/reference/flutter-cli). + +
+ Pour utiliser les services Auth0, vous devez avoir une application installée dans Auth0 Dashboard. L’application Auth0 est l’endroit où vous allez configurer le fonctionnement de l’authentification pour votre projet. + + ### Configurer une application Auth0. + + Utilisez le sélecteur interactif pour créer une nouvelle application Auth0 ou sélectionner une application Auth0 **Native** existante. Dans Auth0, il est attribué à chaque application un identifiant client unique alphanumérique que votre code d’application utilisera pour appeler les API Auth0 via la trousse SDK. + + Tous les paramètres que vous configurez à l’aide de ce guide rapide seront automatiquement mis à jour pour votre application dans le [Dashboard](https://manage.auth0.com/dashboard/us/auth0-dsepaid/), qui est l’endroit où vous pourrez gérer vos applications à l’avenir. + + Si vous préférez explorer une configuration complète, consultez plutôt un exemple d’application. + + ### Configurer les URL de rappel et les URL de déconnexion + + Les Callback URL et les URL de déconnexion sont des URL qu’invoque Auth0 pour rediriger vers votre application. Auth0 invoque l’URL de rappel après avoir authentifié l’utilisateur, et l’URL de déconnexion après avoir supprimé le témoin de session. Si les Callback URL et les URL de déconnexion ne sont pas définies, les utilisateurs ne pourront pas se connecter ou se déconnecter de l’application et recevront un message d’erreur. + + Définissez les Callback URL et les URL de déconnexion sur les valeurs suivantes, en fonction de votre plateforme. + + + Sur Android, la valeur du paramètre fictif `SCHEME` peut être `https` ou un autre schéma personnalisé. Les schémas `https` nécessitent l’activation des [liens d’application Android](https://auth0.com/docs/get-started/applications/enable-android-app-links-support). + Sur iOS 17.4+ et macOS 14.4+, il est possible d’utiliser des liens universels (`https`) comme URL Callback et de déconnexion. Lorsqu’activé, la trousse SDK reviendra à l’utilisation d’un schéma d’URL personnalisé sur les anciennes versions iOS/MacOS – [l’identificateur de bundle](https://developer.apple.com/documentation/appstoreconnectapi/bundle\_ids)de votre application. **Cette fonctionnalité nécessite un Xcode 15.3+ et un compte Apple Developer payant**. + + + #### Android + + `SCHEME://{yourDomain}/android/YOUR_PACKAGE_NAME/callback` + + #### iOS + + `https://{yourDomain}/ios/YOUR_BUNDLE_IDENTIFIER/callback,` + + `YOUR_BUNDLE_IDENTIFIER://{yourDomain}/ios/YOUR_BUNDLE_IDENTIFIER/callback` + + #### macOS + + `https://{yourDomain}/macos/YOUR_BUNDLE_IDENTIFIER/callback,` + + `YOUR_BUNDLE_IDENTIFIER://{yourDomain}/macos/YOUR_BUNDLE_IDENTIFIER/callback` + + Par exemple, si l’identifiant de votre bundle iOS était `com.example.MyApp` et votre domaine Auth0 était `example.us.auth0.com`, alors cette valeur serait : + + `https://example.us.auth0.com/ios/com.example.MyApp/callback,` + + `com.example.MyApp://example.us.auth0.com/ios/com.example.MyApp/callback` +
+ +
+ Ajoutez la trousse SDK Flutter Auth0 au projet : + + `flutter pub add auth0_flutter` +
+ +
+ Si vous ne développez pas pour la plateforme Android, ignorez cette étape. + + La trousse SDK nécessite des placeholder dans le manifeste. Auth0 utilise des placeholder en interne pour définir un `intent-filter`, qui capture l’URL de rappel d’authentification. Vous devez définir le domaine du locataire Auth0 et le schéma de l’URL de rappel. + + L’[exemple](https://github.com/auth0-samples/auth0-flutter-samples/tree/main/sample/android) utilise les placeholder suivants : + + - `auth0Domain` : Le domaine de votre locataire Auth0. En général, vous le trouverez dans Auth0 Dashboard sous vos **Application Settings (Paramètres d’application)** dans le champ **Domain (Domaine)**. Si vous utilisez un domaine personnalisé, indiquez dans ce champ votre domaine personnalisé. + - `auth0Scheme` : Le schéma à utiliser. Peut être un schéma personnalisé, ou https si vous souhaitez utiliser les [liens d’application Android](https://auth0.com/docs/applications/enable-android-app-links). Vous pouvez en savoir plus sur la définition de cette valeur dans le [SDK README d’Auth0.Android](https://github.com/auth0/Auth0.Android#a-note-about-app-deep-linking). + + + Vous n’avez pas besoin de déclarer un `intent-filter` spécifique pour votre activité car vous avez défini les paramètres fictifs dans le manifeste avec vos valeurs Auth0 **Domain** et **Scheme**. La bibliothèque gère la redirection pour vous. + + + Exécutez **Sync Project with Gradle Files** dans Android Studio pour appliquer vos modifications. +
+ +
+ Si vous ne développez pas pour les plateformes iOS ou macOS, ignorez cette étape. + + + Cette étape nécessite un compte Apple Developer payant. Il est nécessaire d’utiliser des liens universels comme URL Callback et de déconnexion. Ignorez cette étape pour utiliser plutôt un schéma d’URL personnalisé. + + + ### Configurer Team ID et l’identifiant du bundle + + Allez à la [page des paramètres](https://manage.auth0.com/#/applications/%7ByourClientId%7D/settings) de votre application Auth0, faites défiler jusqu’en bas, et ouvrez **Advanced Settings (Paramètres avancés) > Device Settings (Paramètres de l’appareil)**. Dans la section **iOS**, définissez **Team ID** sur votre [Apple Team ID](https://developer.apple.com/help/account/manage-your-team/locate-your-team-id/) et **App ID** sur l’identificateur du bundle de votre application. + + ![null](/docs/images/fr-ca/cdy7uua7fh8z/7wetuICumueyqt6dbB32ro/00f8484daece173bdefedab166fdd837/IOS_Settings_-_French.png) + + Cette action ajoutera votre application au fichier `apple-app-site-association` de votre locataire Auth0. + + ### Ajouter la capacité de domaine associé + + Ouvrez votre application dans Xcode en exécutant `open ios/Runner.xcworkspace` (ou `open macos/Runner.xcworkspace` pour macOS). Allez à l’[onglet](https://developer.apple.com/documentation/xcode/adding-capabilities-to-your-app#Add-a-capability)**Signing and Capabilities (Signature et capacités)** des paramètres de la cible de l’**exécuteur**, puis appuyez sur le bouton **+ Capability (Capabilité)**. Puis sélectionnez **Associated Domains (Domaines associés)**. + + ![null](/docs/images/fr-ca/cdy7uua7fh8z/3GO76kXynaieKs5CSj3UTp/1cc577b56d00bc3bad877e31b848c1ec/ios-xcode-capabilities.png) + + Ensuite, ajoutez l’[entrée](https://developer.apple.com/documentation/xcode/configuring-an-associated-domain#Define-a-service-and-its-associated-domain) suivante sous **Associated Domains (Domaines associés)** : + + `webcredentials:{yourDomain}` + + Si vous avez un domaine personnalisé, utilisez-le à la place du domaine Auth0 de la page des paramètres. + + + Pour que le domaine associé fonctionne, votre application doit être signée avec votre certificat d’équipe **même lors du développement pour le simulateur iOS**. Assurez-vous d’utiliser Apple Team dont la Team ID (ID d’équipe) est configurée dans la page des paramètres de votre application Auth0. + +
+ +
+ La connexion universelle est le moyen le plus simple de mettre en place l’authentification dans votre application. Nous recommandons de l’utiliser pour une meilleure expérience, une meilleure sécurité et un plus grand nombre de fonctionnalités. + + Intégrez la connexion universelle Auth0 dans votre application Flutter en utilisant la classe `Auth0`. Redirigez vos utilisateurs vers la page de connexion universelle Auth0 en utilisant `webAuthentication().login()`. Il s’agit d’une fonctionnalité `Future` pour que vous récupériez les jetons de l’utilisateur. + + **Android** : si vous utilisez un schéma personnalisé, passez ce schéma à la méthode de connexion afin que le SDK puisse assurer un aller-retour vers la page de connexion : + + `await auth0.webAuthentication(scheme: ’YOUR CUSTOM SCHEME’).login();` + + Lorsqu’un utilisateur se connecte, il est redirigé vers votre application. Puis, vous pouvez accéder à l’identifiant et aux jetons d’accès de cet utilisateur. + + + ##### Point de contrôle + Ajoutez un bouton à votre application qui appelle `webAuthentication().login()` et déconnecte l’utilisateur de votre application. Vérifiez que vous êtes redirigé vers Auth0 pour l’authentification, puis renvoyé vers votre application. + Vérifiez que vous pouvez accéder aux jetons sur le résultat de l’appel `login`. + +
+ +
+ Pour déconnecter les utilisateurs, redirigez-les vers le point de terminaison Auth0 pour effacer leur session de connexion en appelant la trousse SDK Flutter Auth0 `webAuthentication().logout()`. En savoir plus sur la déconnexion d’Auth0. + + **Android** : si vous utilisez un schéma personnalisé, passez ce schéma à la méthode de déconnexion afin que la trousse SDK puisse renvoyer correctement vers votre application : + + `await auth0.webAuthentication(scheme: ’YOUR CUSTOM SCHEME’).logout();` + + + ##### Point de contrôle + Ajoutez un bouton à votre application qui appelle `webAuthentication().logout()` et déconnecte l’utilisateur de votre application. Lorsque vous le sélectionnez, vérifiez que votre application Flutter vous redirige vers le point de terminaison de déconnexion et vice-versa. Vous ne devriez pas être connecté à votre application. + +
+ +
+ Le profil utilisateur récupère automatiquement les propriétés du profil utilisateur pour vous lorsque vous appelez `webAuthentication().login()`. L’objet retourné à partir de l’étape de connexion contient une propriété `user` avec toutes les propriétés du profil utilisateur, qui est renseigné en décodant le jeton d’ID. + + + ##### Point de contrôle + Connectez-vous et inspectez la propriété `user` par rapport au résultat. Vérifiez les informations de profil utilisateur actuel, telles que son `email` ou `name`. + +
+ + ## Étapes suivantes + + Beau travail! Si vous en êtes arrivé là, vous devriez avoir la connexion, la déconnexion et les informations de profil utilisateur actives dans votre application. + + Cela conclut notre tutoriel de démarrage rapide, mais il y a tellement plus à explorer. Pour en savoir plus sur ce que vous pouvez faire avec Auth0, consultez : + + * [Auth0 Dashboard](https://manage.auth0.com/#) : apprenez à configurer et gérer votre locataire et vos applications Auth0 + * [Trousse SDK auth0-flutter](https://www.github.com/auth0/auth0-flutter/) : explorez en détail la trousse SDK utilisée dans ce tutoriel + * [Auth0 Marketplace](https://marketplace.auth0.com/) : découvrez des intégrations que vous pouvez activer pour étendre les fonctionnalités d’Auth0 + * [Configure other identity providers](/docs/identityproviders) + * [Enable multifactor authentication](/docs/multifactor-authentication) + * [Learn about attack protection](/docs/attack-protection) + * [Learn about Actions](/docs/customize/actions) +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
diff --git a/main/docs/fr-ca/quickstart/native/ionic-angular/interactive.mdx b/main/docs/fr-ca/quickstart/native/ionic-angular/interactive.mdx index 525315a05..cadca8856 100644 --- a/main/docs/fr-ca/quickstart/native/ionic-angular/interactive.mdx +++ b/main/docs/fr-ca/quickstart/native/ionic-angular/interactive.mdx @@ -1,264 +1,266 @@ ---- -title: "Ajouter la connexion à votre application Ionic Angular avec Capacitor" -permalink: "interactive" -'description': "Ce guide explique comment intégrer Auth0 avec une application Ionic (Angular) et Capacitor en utilisant la trousse SDK Angular Auth0." -'og:title': "Ajouter la connexion à votre application Ionic Angular avec Capacitor" -'og:description': "Ce guide explique comment intégrer Auth0 avec une application Ionic (Angular) et Capacitor en utilisant la trousse SDK Angular Auth0." -'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/ionic.jpeg" -'twitter:title': "Ajouter la connexion à votre application Ionic Angular avec Capacitor" -'twitter:description': "Ce guide explique comment intégrer Auth0 avec une application Ionic (Angular) et Capacitor en utilisant la trousse SDK Angular Auth0." -sidebarTitle: Ionic & Capacitor (Angular) ---- - -import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; -import { LoggedInForm } from "/snippets/Login.jsx"; -import AppModule from "/snippets/quickstart/native/ionic-angular/app.module.ts.mdx"; -import AppComponent from "/snippets/quickstart/native/ionic-angular/app.component.ts.mdx"; -import Loginbutton from "/snippets/quickstart/native/ionic-angular/login-button.ts.mdx"; -import Logoutbutton from "/snippets/quickstart/native/ionic-angular/logout-button.ts.mdx"; -import Userprofile from "/snippets/quickstart/native/ionic-angular/user-profile.ts.mdx"; - -export const sections = [ - { id: "démarrage", title: "Démarrage" }, - { id: "configuration-d-auth0", title: "Configuration d’Auth0" }, - { id: "installer-la-trousse-sdk-react-auth0", title: "Installer la trousse SDK React Auth0" }, - { id: "enregistrer-et-configurer-le-module-d-authentification", title: "Enregistrer et configurer le module d’authentification" }, - { id: "ajouter-une-fonctionnalité-de-connexion-à-votre-application", title: "Ajouter une fonctionnalité de connexion à votre application" }, - { id: "gérer-la-callback-de-connexion", title: "Gérer la callback de connexion" }, - { id: "ajouter-une-fonctionnalité-de-déconnexion-à-votre-application", title: "Ajouter une fonctionnalité de déconnexion à votre application" }, - { id: "afficher-le-profil-utilisateur", title: "Afficher le profil utilisateur" } -] - - - - Auth0 vous permet d’ajouter rapidement l’authentification et d’accéder aux informations relatives au profil de l’utilisateur dans votre application. Ce guide explique comment intégrer Auth0 avec une application Ionic (Angular) & Capacitor en utilisant la [trousse SDK Angular Auth0](https://github.com/auth0/auth0-angular). - -
- Ce guide de démarrage rapide suppose que vous avez déjà une application [Ionic](https://ionicframework.com/) en cours d’exécution avec [Capacitor](https://capacitorjs.com/). Si ce n’est pas le cas, consultez [Using Capacitor with Ionic Framework guide (Utiliser Capacitor avec le cadre d’applications Ionic)](https://capacitorjs.com/docs/getting-started/with-ionic) pour commencer avec une application simple ou clonez nos [our sample apps (exemples d’applications)](https://github.com/auth0-samples/auth0-ionic-samples). - - Vous devez également être familiarisé avec [Capacitor development workflow (le flux de production de développement Capacitor)](https://capacitorjs.com/docs/basics/workflow). -
- -
- Pour utiliser les services Auth0, vous devez avoir une application installée dans Auth0 Dashboard. L’application Auth0 est l’endroit où vous allez configurer le fonctionnement de l’authentification pour votre projet. - - - Tout au long de cet article, `YOUR\_PACKAGE\_ID` est l’identifiant du package de votre application. Ceci peut être trouvé et configuré dans le champ `appId` de votre fichier `capacitor.config.ts` . Voir [Capacitor’s Config schema (Schéma de configuration du Capacitor)](https://capacitorjs.com/docs/config#schema) pour plus d’informations. - - - ### Configurer une application - - Utilisez le sélecteur interactif pour créer une nouvelle application Auth0 ou sélectionner une application existante qui représente le projet avec lequel vous souhaitez effectuer l’intégration. Dans Auth0, il est attribué à chaque application un identifiant client unique alphanumérique que votre code d’application utilisera pour appeler les API Auth0 via la trousse SDK. - - Tous les paramètres que vous configurez à l’aide de ce guide rapide seront automatiquement mis à jour pour votre application dans le [Dashboard](https://manage.auth0.com/#/), qui est l’endroit où vous pourrez gérer vos applications à l’avenir. - - Si vous préférez explorer une configuration complète, consultez plutôt un exemple d’application. - - ### Configurer les URL de rappel - - Une URL de rappel est une URL intégrée dans votre application vers laquelle vous souhaitez qu’Auth0 redirige les utilisateurs après leur authentification. Si elle n’est pas définie, les utilisateurs ne seront pas redirigés vers votre application après s’être connectés. - - - Si vous suivez notre projet à titre d’exemple, définissez ceci sur : - `YOUR\_PACKAGE\_ID://{yourDomain}/capacitor/YOUR\_PACKAGE\_ID/callback` - - - ### Configuration des URL de déconnexion - - Une URL de déconnexion est une URL intégrée dans votre application vers laquelle vous souhaitez qu’Auth0 redirige les utilisateurs après leur déconnexion. Si elle n’est pas définie, les utilisateurs ne pourront pas se déconnecter de votre application et recevront un message d’erreur. - - - Si vous suivez notre projet à titre d’exemple, définissez ceci sur : - `YOUR\_PACKAGE\_ID://{yourDomain}/capacitor/YOUR\_PACKAGE\_ID/callback` - - - ### Configurer les origines autorisées - - Pour pouvoir faire des requêtes à partir de votre application d’origine vers Auth0, définissez les **origines autorisées** dans vos [Application Settings (Paramètres d’application)](https://manage.auth0.com/#/applications/%7ByourClientId%7D/settings). - - - Si vous suivez notre projet à titre d’exemple, définissez ceci sur `capacitor://localhost, http://localhost` pour iOS et Android respectivement. - - - Enfin, assurez-vous que le **type d’application** pour votre application est défini sur **Native** dans les [Application Settings (Paramètres d’application)](https://manage.auth0.com/#/applications/%7ByourClientId%7D/settings). -
- -
- Exécutez la commande suivante dans le répertoire de votre projet pour installer la trousse SDK Angular Auth0 : - - `npm install @auth0/auth0-angular` - - La trousse SDK expose plusieurs types qui vous aident à intégrer Auth0 avec votre application Angular, y compris un module et un service d’authentification. - - ### Installer les plugiciels Capacitor - - Ce guide rapide et cet exemple utilisent certains des plugiciels officiels Capacitor. Installez-les dans votre application à l’aide de la commande suivante : - - `npm install @capacitor/browser @capacitor/app` - - - [`@capacitor/browser`](https://capacitorjs.com/docs/apis/browser) : Vous permet d’interagir avec le navigateur de système de l’appareil, et est utilisé pour ouvrir l’URL vers le point de terminaison d’autorisation d’Auth0. - - [`@capacitor/app`](https://capacitorjs.com/docs/apis/app) : Vous permet de vous abonner à des événements d’application de haut niveau, utiles pour la gestion des Callbacks depuis Auth0. - - - Le plugiciel de navigateur de Capacitor sur iOS utilise [`SFSafariViewController`](https://developer.apple.com/documentation/safariservices/sfsafariviewcontroller), qui sur iOS 11+ ne partage pas les témoins avec Safari sur l’appareil. Cela signifie que SSO ne fonctionnera pas sur ces appareils. Si vous avez besoin de SSO, veuillez utiliser un plugiciel compatible qui utilise [ASWebAuthenticationSession](https://developer.apple.com/documentation/authenticationservices/aswebauthenticationsession). - -
- -
- La trousse SDK exporte `AuthModule`, un module qui contient tous les services nécessaires au fonctionnement de la trousse SDK. Ce module doit être enregistré avec votre application et être configuré avec votre domaine Auth0 et votre identifiant client. - - La fonction `AuthModule.forRoot` prend la configuration suivante : - - - `domain` : La valeur `domain` présente dans les **paramètres** de l’application que vous avez créée dans Auth0 Dashboard, ou votre domaine personnalisé si vous utilisez la fonctionnalité Domaines personnalisés d’Auth0. - - `clientId` : La valeur de l’identifiant du client présente dans les **paramètres** de l’application que vous avez créée dans Auth0 Dashboard. - - `useRefreshTokens` : Pour utiliser auth0-angular avec Ionic sur Android et iOS, il est nécessaire d’activer les jetons d’actualisation. - - `useRefreshTokensFallback` : Pour utiliser auth0-angular avec Ionic sur Android et iOS, il est nécessaire de désactiver le iframe de substitution. - - `authorizationParams.redirect_uri` : L’URL pour rediriger vos utilisateurs après qu’ils se sont authentifiés avec Auth0. - - - Pour conserver l’authentification après la fermeture et la réouverture de l’application, vous pouvez définir `cacheLocation` sur `localstorage` lors de la configuration du SDK, mais soyez conscient des [risques liés au stockage de jetons dans localstorage](/docs/libraries/auth0-single-page-app-sdk#change-storage-options). De plus, localstorage devrait être traité comme **transitoire** dans l’application Capacitor car les données pourraient être récupérées de façon inattendue dans certaines circonstances. Veuillez lire les [directives sur le stockage dans la documentation Capacitor](https://capacitorjs.com/docs/guides/storage#why-cant-i-just-use-localstorage-or-indexeddb). - En outre, le SDK a la capacité [d’utiliser une implémentation de cache personnalisée](https://github.com/auth0/auth0-spa-js/blob/master/EXAMPLES.md#creating-a-custom-cache) pour stocker des jetons, si vous avez une exigence d’utiliser un mécanisme de stockage plus sûr et persistant. - **Notez** que nous recommandons **de ne pas** utiliser le [plugiciel Capacitor pour stocker](https://capacitorjs.com/docs/apis/storage) les jetons, car cela est soutenu par [UserDefaults](https://developer.apple.com/documentation/foundation/userdefaults) et [SharedPreferences](https://developer.android.com/reference/android/content/SharedPreferences) sur iOS et Android respectivement. Les données stockées à l’aide de ces API ne sont pas cryptées, non sécurisées et peuvent également être synchronisées dans le nuage. - - - - ##### Point de contrôle - Maintenant que vous avez configuré votre application avec la trousse SDK Angular Auth0, exécutez votre application pour vérifier que la trousse SDK est initialisée sans erreur et que votre application s’exécute comme auparavant. - -
- -
- Dans une application Capacitor, le [plugiciel de navigateur Capacitor](https://capacitorjs.com/docs/apis/browser) effectue une redirection vers la [page de connexion universelle Auth0](https://auth0.com/universal-login). Définissez le paramètre `openUrl` sur la fonction `loginWithRedirect` pour utiliser `Browser.open` de sorte que l’URL soit ouverte à l’aide du composant navigateur du système de l’appareil ([SFSafariViewController](https://developer.apple.com/documentation/safariservices/sfsafariviewcontroller) sur iOS et les [Onglets Personnalisés Chrome](https://developer.chrome.com/docs/android/custom-tabs) sur Android). - - - Par défaut, la méthode `loginWithRedirect` de la trousse SDK utilise `window.location.href` pour accéder à la page de connexion dans l’application de navigateur par défaut sur l’appareil de l’utilisateur plutôt que dans le composant de navigateur système approprié pour la plate-forme. L’utilisateur quitterait votre application pour s’authentifier et pourrait rendre l’expérience utilisateur sous-optimale. - - - - ##### Point de contrôle - La fonction `loginWithRedirect` indique à la trousse SDK d’initier le flux de connexion, en utilisant la fonction `Browser.open` pour ouvrir l’URL de connexion avec le composant navigateur du système de la plateforme en définissant le paramètre `openUrl`. Cela permet à votre utilisateur de se connecter à votre application. Les utilisateurs sont redirigés vers la page de connexion à Auth0 et ne reçoivent aucune erreur. - -
- -
- Une fois que les utilisateurs sont connectés avec la page de connexion universelle, ils sont redirigés vers votre application via une URL avec un schéma d’URL personnalisé. L’événement `appUrlOpen` doit être géré depuis votre application. Vous pouvez appeler la méthode `handleRedirectCallback` depuis la trousse SDK Auth0 pour initier l’état de l’authentification. - - Vous pouvez utiliser cette méthode uniquement sur une redirection depuis Auth0. Pour vérifier le succès, vérifiez la présence du `code` et des paramètres `state` dans l’URL. - - La méthode `Browser.close()` devrait fermer le navigateur lorsque cet événement est déclenché. - - Notez que la callback de l’événement `appUrlOpen` est enveloppé dans `ngZone.run`. Les modifications aux observables survenant lorsque `handleRedirectCallback` est exécuté sont détectées par l’application Angular. Pour en savoir plus sur cette fonctionnalité, veuillez consulter [Utiliser Angular avec Capacitator](https://capacitorjs.com/docs/guides/angular). Sinon, l’écran ne se met pas à jour pour afficher l’état authentifié après la connexion. - - - Cet article suppose que vous utiliserez des schémas d’URL personnalisés pour gérer le rappel dans votre application. Pour ce faire, enregistrez votre `YOUR\_PACKAGE\_ID` comme schéma d’URL pour la plateforme de votre choix. Pour en savoir plus, lire [Defining a Custom URL Scheme (Définition d’un schéma d’URL personnalisé)](https://developer.apple.com/documentation/xcode/defining-a-custom-url-scheme-for-your-app) pour iOS ou [Create Deep Links to App Content (Création de liens profonds vers le contenu des applications)](https://developer.android.com/training/app-links/deep-linking) pour Android. - - - - ##### Point de contrôle - Ajoutez `appUrlOpen` au composant `App` de votre application et connectez-vous. La fenêtre du navigateur devrait se fermer une fois que l’utilisateur s’authentifie et se connecte à votre application. - -
- -
- Maintenant que les utilisateurs peuvent se connecter, vous devez configurer une façon de se déconnecter. Les utilisateurs doivent être redirigés vers le point de terminaison de déconnexion Auth0 dans le navigateur pour effacer leur session de navigation. Encore une fois, le plugiciel du navigateur de Capacitor doit effectuer cette redirection afin que l’utilisateur ne quitte pas votre application et ne vive pas une expérience frustrante. - - Pour y parvenir avec Ionic et Capacitor en conjonction avec le SDK Auth0 : - - - Créez l’URL de votre application vers laquelle Auth0 doit rediriger après la déconnexion. Il s’agit d’une URL qui utilise votre schéma personnalisé enregistré et le domaine Auth0. Ajoutez-la à votre configuration **URL de déconnexions autorisées** dans Auth0 Dashboard - - Déconnectez-vous de la trousse SDK en appelant `logout` et transmettez votre URL de redirection comme paramètre `logoutParams.returnTo`. - - Définissez le paramètre `openUrl` sur un callback qui utilise le plugiciel de navigateur Capacitor pour ouvrir l’URL à l’aide de `Browser.open`. - - - De la même manière que pour l’étape de connexion, si vous ne définissez pas `openUrl` lors de l’appel de `logout`, le SDK redirige l’utilisateur vers l’URL de déconnexion à l’aide de l’application de navigateur par défaut sur l’appareil, ce qui offre une expérience utilisateur sous-optimale. - - - - ##### Point de contrôle - Fournir un moyen pour vos utilisateurs de se déconnecter de votre application. Vérifiez la redirection vers Auth0, puis vers l’adresse que vous avez spécifiée dans le paramètre `returnTo`. Assurez-vous que les utilisateurs ne sont plus connectés à votre application. - -
- -
- La trousse SDK Auth0 récupère les informations de profil associées aux utilisateurs connectés dans n’importe quel composant dont vous avez besoin, comme leur nom ou leur image de profil, pour personnaliser l’interface utilisateur. Les informations de profil sont disponibles via la propriété `user$` exposée par `AuthService`. - - - ##### Point de contrôle - Fournir un moyen pour que vos utilisateurs puissent voir leurs détails de profil utilisateur dans l’application et vérifiez que vous êtes en mesure de récupérer et d’afficher les informations de votre profil à l’écran une fois que vous avez ouvert une session. - -
- - ## Étapes suivantes - - Beau travail! Si vous en êtes arrivé là, vous devriez avoir la connexion, la déconnexion et les informations de profil utilisateur actives dans votre application. - - Cela conclut notre tutoriel de démarrage rapide, mais il y a tellement plus à explorer. Pour en savoir plus sur ce que vous pouvez faire avec Auth0, consultez : - - * [Auth0 Dashboard](https://manage.auth0.com/#) : apprenez à configurer et gérer votre locataire et vos applications Auth0 - * [Auth0 Marketplace](https://marketplace.auth0.com/) : découvrez des intégrations que vous pouvez activer pour étendre les fonctionnalités d’Auth0 -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+--- +title: "Ajouter la connexion à votre application Ionic Angular avec Capacitor" +permalink: "interactive" +'description': "Ce guide explique comment intégrer Auth0 avec une application Ionic (Angular) et Capacitor en utilisant la trousse SDK Angular Auth0." +'og:title': "Ajouter la connexion à votre application Ionic Angular avec Capacitor" +'og:description': "Ce guide explique comment intégrer Auth0 avec une application Ionic (Angular) et Capacitor en utilisant la trousse SDK Angular Auth0." +'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/ionic.jpeg" +'twitter:title': "Ajouter la connexion à votre application Ionic Angular avec Capacitor" +'twitter:description': "Ce guide explique comment intégrer Auth0 avec une application Ionic (Angular) et Capacitor en utilisant la trousse SDK Angular Auth0." +sidebarTitle: Ionic & Capacitor (Angular) +--- + +import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; +import { LoggedInForm } from "/snippets/Login.jsx"; +import AppModule from "/snippets/quickstart/native/ionic-angular/app.module.ts.mdx"; +import AppComponent from "/snippets/quickstart/native/ionic-angular/app.component.ts.mdx"; +import Loginbutton from "/snippets/quickstart/native/ionic-angular/login-button.ts.mdx"; +import Logoutbutton from "/snippets/quickstart/native/ionic-angular/logout-button.ts.mdx"; +import Userprofile from "/snippets/quickstart/native/ionic-angular/user-profile.ts.mdx"; + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + +export const sections = [ + { id: "démarrage", title: "Démarrage" }, + { id: "configuration-d-auth0", title: "Configuration d’Auth0" }, + { id: "installer-la-trousse-sdk-react-auth0", title: "Installer la trousse SDK React Auth0" }, + { id: "enregistrer-et-configurer-le-module-d-authentification", title: "Enregistrer et configurer le module d’authentification" }, + { id: "ajouter-une-fonctionnalité-de-connexion-à-votre-application", title: "Ajouter une fonctionnalité de connexion à votre application" }, + { id: "gérer-la-callback-de-connexion", title: "Gérer la callback de connexion" }, + { id: "ajouter-une-fonctionnalité-de-déconnexion-à-votre-application", title: "Ajouter une fonctionnalité de déconnexion à votre application" }, + { id: "afficher-le-profil-utilisateur", title: "Afficher le profil utilisateur" } +] + + + + Auth0 vous permet d’ajouter rapidement l’authentification et d’accéder aux informations relatives au profil de l’utilisateur dans votre application. Ce guide explique comment intégrer Auth0 avec une application Ionic (Angular) & Capacitor en utilisant la [trousse SDK Angular Auth0](https://github.com/auth0/auth0-angular). + +
+ Ce guide de démarrage rapide suppose que vous avez déjà une application [Ionic](https://ionicframework.com/) en cours d’exécution avec [Capacitor](https://capacitorjs.com/). Si ce n’est pas le cas, consultez [Using Capacitor with Ionic Framework guide (Utiliser Capacitor avec le cadre d’applications Ionic)](https://capacitorjs.com/docs/getting-started/with-ionic) pour commencer avec une application simple ou clonez nos [our sample apps (exemples d’applications)](https://github.com/auth0-samples/auth0-ionic-samples). + + Vous devez également être familiarisé avec [Capacitor development workflow (le flux de production de développement Capacitor)](https://capacitorjs.com/docs/basics/workflow). +
+ +
+ Pour utiliser les services Auth0, vous devez avoir une application installée dans Auth0 Dashboard. L’application Auth0 est l’endroit où vous allez configurer le fonctionnement de l’authentification pour votre projet. + + + Tout au long de cet article, `YOUR\_PACKAGE\_ID` est l’identifiant du package de votre application. Ceci peut être trouvé et configuré dans le champ `appId` de votre fichier `capacitor.config.ts` . Voir [Capacitor’s Config schema (Schéma de configuration du Capacitor)](https://capacitorjs.com/docs/config#schema) pour plus d’informations. + + + ### Configurer une application + + Utilisez le sélecteur interactif pour créer une nouvelle application Auth0 ou sélectionner une application existante qui représente le projet avec lequel vous souhaitez effectuer l’intégration. Dans Auth0, il est attribué à chaque application un identifiant client unique alphanumérique que votre code d’application utilisera pour appeler les API Auth0 via la trousse SDK. + + Tous les paramètres que vous configurez à l’aide de ce guide rapide seront automatiquement mis à jour pour votre application dans le [Dashboard](https://manage.auth0.com/#/), qui est l’endroit où vous pourrez gérer vos applications à l’avenir. + + Si vous préférez explorer une configuration complète, consultez plutôt un exemple d’application. + + ### Configurer les URL de rappel + + Une URL de rappel est une URL intégrée dans votre application vers laquelle vous souhaitez qu’Auth0 redirige les utilisateurs après leur authentification. Si elle n’est pas définie, les utilisateurs ne seront pas redirigés vers votre application après s’être connectés. + + + Si vous suivez notre projet à titre d’exemple, définissez ceci sur : + `YOUR\_PACKAGE\_ID://{yourDomain}/capacitor/YOUR\_PACKAGE\_ID/callback` + + + ### Configuration des URL de déconnexion + + Une URL de déconnexion est une URL intégrée dans votre application vers laquelle vous souhaitez qu’Auth0 redirige les utilisateurs après leur déconnexion. Si elle n’est pas définie, les utilisateurs ne pourront pas se déconnecter de votre application et recevront un message d’erreur. + + + Si vous suivez notre projet à titre d’exemple, définissez ceci sur : + `YOUR\_PACKAGE\_ID://{yourDomain}/capacitor/YOUR\_PACKAGE\_ID/callback` + + + ### Configurer les origines autorisées + + Pour pouvoir faire des requêtes à partir de votre application d’origine vers Auth0, définissez les **origines autorisées** dans vos [Application Settings (Paramètres d’application)](https://manage.auth0.com/#/applications/%7ByourClientId%7D/settings). + + + Si vous suivez notre projet à titre d’exemple, définissez ceci sur `capacitor://localhost, http://localhost` pour iOS et Android respectivement. + + + Enfin, assurez-vous que le **type d’application** pour votre application est défini sur **Native** dans les [Application Settings (Paramètres d’application)](https://manage.auth0.com/#/applications/%7ByourClientId%7D/settings). +
+ +
+ Exécutez la commande suivante dans le répertoire de votre projet pour installer la trousse SDK Angular Auth0 : + + `npm install @auth0/auth0-angular` + + La trousse SDK expose plusieurs types qui vous aident à intégrer Auth0 avec votre application Angular, y compris un module et un service d’authentification. + + ### Installer les plugiciels Capacitor + + Ce guide rapide et cet exemple utilisent certains des plugiciels officiels Capacitor. Installez-les dans votre application à l’aide de la commande suivante : + + `npm install @capacitor/browser @capacitor/app` + + - [`@capacitor/browser`](https://capacitorjs.com/docs/apis/browser) : Vous permet d’interagir avec le navigateur de système de l’appareil, et est utilisé pour ouvrir l’URL vers le point de terminaison d’autorisation d’Auth0. + - [`@capacitor/app`](https://capacitorjs.com/docs/apis/app) : Vous permet de vous abonner à des événements d’application de haut niveau, utiles pour la gestion des Callbacks depuis Auth0. + + + Le plugiciel de navigateur de Capacitor sur iOS utilise [`SFSafariViewController`](https://developer.apple.com/documentation/safariservices/sfsafariviewcontroller), qui sur iOS 11+ ne partage pas les témoins avec Safari sur l’appareil. Cela signifie que SSO ne fonctionnera pas sur ces appareils. Si vous avez besoin de SSO, veuillez utiliser un plugiciel compatible qui utilise [ASWebAuthenticationSession](https://developer.apple.com/documentation/authenticationservices/aswebauthenticationsession). + +
+ +
+ La trousse SDK exporte `AuthModule`, un module qui contient tous les services nécessaires au fonctionnement de la trousse SDK. Ce module doit être enregistré avec votre application et être configuré avec votre domaine Auth0 et votre identifiant client. + + La fonction `AuthModule.forRoot` prend la configuration suivante : + + - `domain` : La valeur `domain` présente dans les **paramètres** de l’application que vous avez créée dans Auth0 Dashboard, ou votre domaine personnalisé si vous utilisez la fonctionnalité Domaines personnalisés d’Auth0. + - `clientId` : La valeur de l’identifiant du client présente dans les **paramètres** de l’application que vous avez créée dans Auth0 Dashboard. + - `useRefreshTokens` : Pour utiliser auth0-angular avec Ionic sur Android et iOS, il est nécessaire d’activer les jetons d’actualisation. + - `useRefreshTokensFallback` : Pour utiliser auth0-angular avec Ionic sur Android et iOS, il est nécessaire de désactiver le iframe de substitution. + - `authorizationParams.redirect_uri` : L’URL pour rediriger vos utilisateurs après qu’ils se sont authentifiés avec Auth0. + + + Pour conserver l’authentification après la fermeture et la réouverture de l’application, vous pouvez définir `cacheLocation` sur `localstorage` lors de la configuration du SDK, mais soyez conscient des [risques liés au stockage de jetons dans localstorage](/docs/libraries/auth0-single-page-app-sdk#change-storage-options). De plus, localstorage devrait être traité comme **transitoire** dans l’application Capacitor car les données pourraient être récupérées de façon inattendue dans certaines circonstances. Veuillez lire les [directives sur le stockage dans la documentation Capacitor](https://capacitorjs.com/docs/guides/storage#why-cant-i-just-use-localstorage-or-indexeddb). + En outre, le SDK a la capacité [d’utiliser une implémentation de cache personnalisée](https://github.com/auth0/auth0-spa-js/blob/master/EXAMPLES.md#creating-a-custom-cache) pour stocker des jetons, si vous avez une exigence d’utiliser un mécanisme de stockage plus sûr et persistant. + **Notez** que nous recommandons **de ne pas** utiliser le [plugiciel Capacitor pour stocker](https://capacitorjs.com/docs/apis/storage) les jetons, car cela est soutenu par [UserDefaults](https://developer.apple.com/documentation/foundation/userdefaults) et [SharedPreferences](https://developer.android.com/reference/android/content/SharedPreferences) sur iOS et Android respectivement. Les données stockées à l’aide de ces API ne sont pas cryptées, non sécurisées et peuvent également être synchronisées dans le nuage. + + + + ##### Point de contrôle + Maintenant que vous avez configuré votre application avec la trousse SDK Angular Auth0, exécutez votre application pour vérifier que la trousse SDK est initialisée sans erreur et que votre application s’exécute comme auparavant. + +
+ +
+ Dans une application Capacitor, le [plugiciel de navigateur Capacitor](https://capacitorjs.com/docs/apis/browser) effectue une redirection vers la [page de connexion universelle Auth0](https://auth0.com/universal-login). Définissez le paramètre `openUrl` sur la fonction `loginWithRedirect` pour utiliser `Browser.open` de sorte que l’URL soit ouverte à l’aide du composant navigateur du système de l’appareil ([SFSafariViewController](https://developer.apple.com/documentation/safariservices/sfsafariviewcontroller) sur iOS et les [Onglets Personnalisés Chrome](https://developer.chrome.com/docs/android/custom-tabs) sur Android). + + + Par défaut, la méthode `loginWithRedirect` de la trousse SDK utilise `window.location.href` pour accéder à la page de connexion dans l’application de navigateur par défaut sur l’appareil de l’utilisateur plutôt que dans le composant de navigateur système approprié pour la plate-forme. L’utilisateur quitterait votre application pour s’authentifier et pourrait rendre l’expérience utilisateur sous-optimale. + + + + ##### Point de contrôle + La fonction `loginWithRedirect` indique à la trousse SDK d’initier le flux de connexion, en utilisant la fonction `Browser.open` pour ouvrir l’URL de connexion avec le composant navigateur du système de la plateforme en définissant le paramètre `openUrl`. Cela permet à votre utilisateur de se connecter à votre application. Les utilisateurs sont redirigés vers la page de connexion à Auth0 et ne reçoivent aucune erreur. + +
+ +
+ Une fois que les utilisateurs sont connectés avec la page de connexion universelle, ils sont redirigés vers votre application via une URL avec un schéma d’URL personnalisé. L’événement `appUrlOpen` doit être géré depuis votre application. Vous pouvez appeler la méthode `handleRedirectCallback` depuis la trousse SDK Auth0 pour initier l’état de l’authentification. + + Vous pouvez utiliser cette méthode uniquement sur une redirection depuis Auth0. Pour vérifier le succès, vérifiez la présence du `code` et des paramètres `state` dans l’URL. + + La méthode `Browser.close()` devrait fermer le navigateur lorsque cet événement est déclenché. + + Notez que la callback de l’événement `appUrlOpen` est enveloppé dans `ngZone.run`. Les modifications aux observables survenant lorsque `handleRedirectCallback` est exécuté sont détectées par l’application Angular. Pour en savoir plus sur cette fonctionnalité, veuillez consulter [Utiliser Angular avec Capacitator](https://capacitorjs.com/docs/guides/angular). Sinon, l’écran ne se met pas à jour pour afficher l’état authentifié après la connexion. + + + Cet article suppose que vous utiliserez des schémas d’URL personnalisés pour gérer le rappel dans votre application. Pour ce faire, enregistrez votre `YOUR\_PACKAGE\_ID` comme schéma d’URL pour la plateforme de votre choix. Pour en savoir plus, lire [Defining a Custom URL Scheme (Définition d’un schéma d’URL personnalisé)](https://developer.apple.com/documentation/xcode/defining-a-custom-url-scheme-for-your-app) pour iOS ou [Create Deep Links to App Content (Création de liens profonds vers le contenu des applications)](https://developer.android.com/training/app-links/deep-linking) pour Android. + + + + ##### Point de contrôle + Ajoutez `appUrlOpen` au composant `App` de votre application et connectez-vous. La fenêtre du navigateur devrait se fermer une fois que l’utilisateur s’authentifie et se connecte à votre application. + +
+ +
+ Maintenant que les utilisateurs peuvent se connecter, vous devez configurer une façon de se déconnecter. Les utilisateurs doivent être redirigés vers le point de terminaison de déconnexion Auth0 dans le navigateur pour effacer leur session de navigation. Encore une fois, le plugiciel du navigateur de Capacitor doit effectuer cette redirection afin que l’utilisateur ne quitte pas votre application et ne vive pas une expérience frustrante. + + Pour y parvenir avec Ionic et Capacitor en conjonction avec le SDK Auth0 : + + - Créez l’URL de votre application vers laquelle Auth0 doit rediriger après la déconnexion. Il s’agit d’une URL qui utilise votre schéma personnalisé enregistré et le domaine Auth0. Ajoutez-la à votre configuration **URL de déconnexions autorisées** dans Auth0 Dashboard + - Déconnectez-vous de la trousse SDK en appelant `logout` et transmettez votre URL de redirection comme paramètre `logoutParams.returnTo`. + - Définissez le paramètre `openUrl` sur un callback qui utilise le plugiciel de navigateur Capacitor pour ouvrir l’URL à l’aide de `Browser.open`. + + + De la même manière que pour l’étape de connexion, si vous ne définissez pas `openUrl` lors de l’appel de `logout`, le SDK redirige l’utilisateur vers l’URL de déconnexion à l’aide de l’application de navigateur par défaut sur l’appareil, ce qui offre une expérience utilisateur sous-optimale. + + + + ##### Point de contrôle + Fournir un moyen pour vos utilisateurs de se déconnecter de votre application. Vérifiez la redirection vers Auth0, puis vers l’adresse que vous avez spécifiée dans le paramètre `returnTo`. Assurez-vous que les utilisateurs ne sont plus connectés à votre application. + +
+ +
+ La trousse SDK Auth0 récupère les informations de profil associées aux utilisateurs connectés dans n’importe quel composant dont vous avez besoin, comme leur nom ou leur image de profil, pour personnaliser l’interface utilisateur. Les informations de profil sont disponibles via la propriété `user$` exposée par `AuthService`. + + + ##### Point de contrôle + Fournir un moyen pour que vos utilisateurs puissent voir leurs détails de profil utilisateur dans l’application et vérifiez que vous êtes en mesure de récupérer et d’afficher les informations de votre profil à l’écran une fois que vous avez ouvert une session. + +
+ + ## Étapes suivantes + + Beau travail! Si vous en êtes arrivé là, vous devriez avoir la connexion, la déconnexion et les informations de profil utilisateur actives dans votre application. + + Cela conclut notre tutoriel de démarrage rapide, mais il y a tellement plus à explorer. Pour en savoir plus sur ce que vous pouvez faire avec Auth0, consultez : + + * [Auth0 Dashboard](https://manage.auth0.com/#) : apprenez à configurer et gérer votre locataire et vos applications Auth0 + * [Auth0 Marketplace](https://marketplace.auth0.com/) : découvrez des intégrations que vous pouvez activer pour étendre les fonctionnalités d’Auth0 +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
diff --git a/main/docs/fr-ca/quickstart/native/ionic-react/interactive.mdx b/main/docs/fr-ca/quickstart/native/ionic-react/interactive.mdx index 31ebc54d2..856a41c6a 100644 --- a/main/docs/fr-ca/quickstart/native/ionic-react/interactive.mdx +++ b/main/docs/fr-ca/quickstart/native/ionic-react/interactive.mdx @@ -1,264 +1,266 @@ ---- -title: "Ajouter la connexion à votre application Ionic React avec l’application Capacitor" -permalink: "interactive" -'description': "Ce guide explique comment intégrer Auth0 avec une application Ionic (React) & Capacitor en utilisant la trousse SDK React Auth0." -'og:title': "Ajouter la connexion à votre application Ionic React avec l’application Capacitor" -'og:description': "Ce guide explique comment intégrer Auth0 avec une application Ionic (React) & Capacitor en utilisant la trousse SDK React Auth0." -'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/ionic.jpeg" -'twitter:title': "Ajouter la connexion à votre application Ionic React avec l’application Capacitor" -'twitter:description': "Ce guide explique comment intégrer Auth0 avec une application Ionic (React) & Capacitor en utilisant la trousse SDK React Auth0." -sidebarTitle: Ionic & Capacitor (React) ---- - -import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; -import { LoggedInForm } from "/snippets/Login.jsx"; -import Index from "/snippets/quickstart/native/ionic-react/index.tsx.mdx"; -import Loginbutton from "/snippets/quickstart/native/ionic-react/login-button.tsx.mdx"; -import Logoutbutton from "/snippets/quickstart/native/ionic-react/logout-button.tsx.mdx"; -import App from "/snippets/quickstart/native/ionic-react/app.tsx.mdx"; -import Userprofile from "/snippets/quickstart/native/ionic-react/user-profile.tsx.mdx"; - -export const sections = [ - { id: "démarrage", title: "Démarrage" }, - { id: "configuration-d-auth0", title: "Configuration d’Auth0" }, - { id: "installer-la-trousse-sdk-react-auth0", title: "Installer la trousse SDK React Auth0" }, - { id: "configurer-le-composant-auth0provider", title: "Configurer le composant Auth0Provider" }, - { id: "ajouter-une-fonctionnalité-de-connexion-à-votre-application", title: "Ajouter une fonctionnalité de connexion à votre application" }, - { id: "gérer-le-rappel-de-connexion", title: "Gérer le rappel de connexion" }, - { id: "ajouter-une-fonctionnalité-de-déconnexion-à-votre-application", title: "Ajouter une fonctionnalité de déconnexion à votre application" }, - { id: "afficher-le-profil-utilisateur", title: "Afficher le profil utilisateur" } -] - - - - Auth0 vous permet d’ajouter rapidement l’authentification et de pouvoir accéder aux informations relatives au profil utilisateur dans votre application. Ce guide explique comment intégrer Auth0 avec une application Ionic (React) & Capacitor en utilisant la [trousse SDK Auth0 React](https://github.com/auth0/auth0-react). - -
- Ce guide de démarrage rapide suppose que vous avez déjà une application [Ionic](https://ionicframework.com/) en cours d’exécution avec [Capacitor](https://capacitorjs.com/). Si ce n’est pas le cas, consultez [Using Capacitor with Ionic Framework guide (Utiliser Capacitor avec le cadre d’applications Ionic)](https://capacitorjs.com/docs/getting-started/with-ionic) pour commencer avec une application simple ou clonez nos [our sample apps (exemples d’applications)](https://github.com/auth0-samples/auth0-ionic-samples). - - Vous devez également être familiarisé avec [Capacitor development workflow (le flux de production de développement Capacitor)](https://capacitorjs.com/docs/basics/workflow). -
- -
- Pour utiliser les services Auth0, vous devez avoir une application installée dans Auth0 Dashboard. L’application Auth0 est l’endroit où vous allez configurer le fonctionnement de l’authentification pour votre projet. - - - Tout au long de cet article, `YOUR\_PACKAGE\_ID` est l’identifiant du package de votre application. Ceci peut être trouvé et configuré dans le champ `appId` de votre fichier `capacitor.config.ts` . Voir [Capacitor’s Config schema (Schéma de configuration du Capacitor)](https://capacitorjs.com/docs/config#schema) pour plus d’informations. - - - ### Configurer une application - - Utilisez le sélecteur interactif pour créer une nouvelle application Auth0 ou sélectionner une application existante qui représente le projet avec lequel vous souhaitez effectuer l’intégration. Dans Auth0, il est attribué à chaque application un identifiant client unique alphanumérique que votre code d’application utilisera pour appeler les API Auth0 via la trousse SDK. - - Tous les paramètres que vous configurez à l’aide de ce guide rapide seront automatiquement mis à jour pour votre application dans le [Dashboard](https://manage.auth0.com/#/), qui est l’endroit où vous pourrez gérer vos applications à l’avenir. - - Si vous préférez explorer une configuration complète, consultez plutôt un exemple d’application. - - ### Configuration des URL de rappel - - Une URL de rappel est une URL intégrée dans votre application vers laquelle vous souhaitez qu’Auth0 redirige les utilisateurs après leur authentification. Si elle n’est pas définie, les utilisateurs ne seront pas redirigés vers votre application après s’être connectés. - - - Si vous suivez notre projet à titre d’exemple, définissez ceci sur : - `YOUR\_PACKAGE\_ID://{yourTenant}.auth0.com/capacitor/YOUR\_PACKAGE\_ID/callback`. - - - ### Configuration des URL de déconnexion - - Une URL de déconnexion est une URL intégrée dans votre application vers laquelle vous souhaitez qu’Auth0 redirige les utilisateurs après leur déconnexion. Si elle n’est pas définie, les utilisateurs ne pourront pas se déconnecter de votre application et recevront un message d’erreur. - - - Si vous suivez notre projet à titre d’exemple, définissez ceci sur : - `YOUR\_PACKAGE\_ID://{yourTenant}.auth0.com/capacitor/YOUR\_PACKAGE\_ID/callback`. - - - ### Configurer les origines autorisées - - Pour pouvoir faire des requêtes à partir de votre application d’origine vers Auth0, définissez les **origines autorisées** dans vos [Application Settings (Paramètres d’application)](https://manage.auth0.com/dashboard/#/applications/%7ByourClientId%7D/settings). - - - Si vous suivez notre projet faisant office d’exemple, définissez ceci sur `capacitor://localhost, http://localhost` pour iOS et Android respectivement. - - - Enfin, assurez-vous que le **type d’application** pour votre application est défini sur **Native** dans les [Application Settings (Paramètres d’application)](https://manage.auth0.com/dashboard/#/applications/%7ByourClientId%7D/settings). -
- -
- Exécutez la commande suivante dans le répertoire de votre projet pour installer la trousse SDK React Auth0 : - - `npm install @auth0/auth0-react` - - La trousse SDK expose des méthodes et variables qui vous aident à intégrer Auth0 avec votre application React en utilisant les [Crochets React](https://reactjs.org/docs/hooks-overview.html) ou les [Composants d’ordre supérieur](https://reactjs.org/docs/higher-order-components.html). - - ### Installer les plugiciels Capacitor - - Ce guide rapide et cet exemple utilisent certains des plugiciels officiels Capacitor. Installez-les dans votre application à l’aide de la commande suivante : - - `npm install @capacitor/browser @capacitor/app` - - - [`@capacitor/browser`](https://capacitorjs.com/docs/apis/browser) : Vous permet d’interagir avec le navigateur de système de l’appareil, et est utilisé pour ouvrir l’URL vers le point de terminaison d’autorisation d’Auth0. - - [`@capacitor/app`](https://capacitorjs.com/docs/apis/app) : Vous permet de vous abonner à des événements d’application de haut niveau, utiles pour la gestion des Callbacks depuis Auth0. - - - Le plugiciel de navigateur de Capacitor sur iOS utilise [`SFSafariViewController`](https://developer.apple.com/documentation/safariservices/sfsafariviewcontroller), qui sur iOS 11+ ne partage pas les témoins avec Safari sur l’appareil. Cela signifie que SSO ne fonctionnera pas sur ces appareils. Si vous avez besoin de SSO, veuillez utiliser un plugiciel compatible qui utilise [ASWebAuthenticationSession](https://developer.apple.com/documentation/authenticationservices/aswebauthenticationsession). - -
- -
- Au cours de son fonctionnement, la trousse SDK React Auth0 utilise [React Context](https://reactjs.org/docs/context.html) pour gérer l’état d’authentification de vos utilisateurs. Une façon d’intégrer Auth0 avec votre application React est d’envelopper votre composant racine avec un `Auth0Provider` que vous pouvez importer à partir de la trousse SDK. - - Le composant `Auth0Provider` prend les props suivants : - - - `domain` : La valeur du `domain` présente dans les **paramètres** de l’application que vous avez créée dans votre Auth0 Dashboard, ou votre domaine personnalisé si vous utilisez la fonctionnalité Domaines personnalisés d’Auth0. - - `clientId` : La valeur de l’identifiant du client présente dans les **paramètres** de l’application que vous avez créée dans votre Auth0 Dashboard. - - `useRefreshTokens` : Pour utiliser auth0-react avec Ionic sur Android et iOS, il est nécessaire d’activer les jetons d’actualisation. - - `useRefreshTokensFallback` : Pour utiliser auth0-react avec Ionic sur Android et iOS, il est nécessaire de désactiver le iframe de substitution. - - `authorizationParams.redirect_uri` : L’URL vers laquelle vous souhaitez rediriger vos utilisateurs après qu’ils se soient authentifiés avec Auth0. - - - Pour conserver l’authentification après la fermeture et la réouverture de l’application, vous pouvez définir `cacheLocation` sur `localstorage` lors de la configuration du SDK, mais soyez conscient des [risques liés au stockage de jetons dans localstorage](/docs/libraries/auth0-single-page-app-sdk#change-storage-options). De plus, localstorage devrait être traité comme **transitoire** dans l’application Capacitor car les données pourraient être récupérées de façon inattendue dans certaines circonstances. Veuillez lire les [directives sur le stockage dans la documentation Capacitor](https://capacitorjs.com/docs/guides/storage#why-cant-i-just-use-localstorage-or-indexeddb). - En outre, le SDK a la capacité [d’utiliser une implémentation de cache personnalisée](https://github.com/auth0/auth0-spa-js/blob/master/EXAMPLES.md#creating-a-custom-cache) pour stocker des jetons, si vous avez une exigence d’utiliser un mécanisme de stockage plus sûr et persistant. - **Notez** que nous recommandons **de ne pas** utiliser le [plugiciel Capacitor pour stocker](https://capacitorjs.com/docs/apis/storage) les jetons, car cela est soutenu par [UserDefaults](https://developer.apple.com/documentation/foundation/userdefaults) et [SharedPreferences](https://developer.android.com/reference/android/content/SharedPreferences) sur iOS et Android respectivement. Les données stockées à l’aide de ces API ne sont pas cryptées, non sécurisées et peuvent également être synchronisées dans le nuage. - - - - ##### Point de contrôle - Ajoutez le composant `Auth0Provider` d’une manière qui enveloppe votre composant `App`, puis exécutez votre application pour vérifier que le SDK est initialisé correctement et que votre application ne lance pas d’erreurs liées à Auth0. - -
- -
- Dans une application Capacitor, le plugiciel [Capacitor’s Browser](https://capacitorjs.com/docs/apis/browser) effectue une redirection vers la [Universal Login Page (page de connexion universelle) d’Auth0](https://auth0.com/universal-login) Auth0. Définissez le paramètre `openUrl` sur la fonction `loginWithRedirect` pour utiliser `Browser.open` afin que l’URL soit ouverte à l’aide du composant de navigateur système de l’appareil ([SFSafariViewController](https://developer.apple.com/documentation/safariservices/sfsafariviewcontroller) sur iOS et [Chrome Custom Tabs [Onglets personnalisés Chrome]](https://developer.chrome.com/docs/android/custom-tabs) sur Android). - - - Par défaut, la méthode `loginWithRedirect` de la trousse SDK utilise `window.location.href` pour accéder à la page de connexion dans l’application de navigateur par défaut sur l’appareil de l’utilisateur plutôt que dans le composant de navigateur système approprié pour la plate-forme. L’utilisateur quitterait votre application pour s’authentifier et pourrait rendre l’expérience utilisateur sous-optimale. - - - - ##### Point de contrôle - La fonction `loginWithRedirect` indique à la trousse SDK d’initier le flux de connexion, en utilisant la fonction `Browser.open` pour ouvrir l’URL de connexion avec le composant navigateur du système de la plateforme en définissant le paramètre `openUrl`. Cela permet à votre utilisateur de se connecter à votre application. Les utilisateurs sont redirigés vers la page de connexion à Auth0 et ne reçoivent aucune erreur. - -
- -
- Une fois que les utilisateurs sont connectés avec la page de connexion universelle, ils sont redirigés vers votre application au moyen d’une URL avec un schéma d’URL personnalisé. L’événement `appUrlOpen` doit être traité au sein de votre application. Vous pouvez appeler la méthode `handleRedirectCallback` à partir de la trousse SDK Auth0 pour initialiser l’état d’authentification. - - Vous pouvez utiliser cette méthode uniquement sur une redirection depuis Auth0. Vérifiez que les paramètres `code` et `state` sont présents dans l’URL. - - La méthode `Browser.close()` devrait fermer le navigateur lorsque cet événement est déclenché. - - - Cet article suppose que vous utiliserez des schémas d’URL personnalisés pour gérer le rappel dans votre application. Pour ce faire, enregistrez votre `YOUR\_PACKAGE\_ID` comme schéma d’URL pour la plateforme de votre choix. Pour en savoir plus, lire [Defining a Custom URL Scheme (Définition d’un schéma d’URL personnalisé)](https://developer.apple.com/documentation/xcode/defining-a-custom-url-scheme-for-your-app) pour iOS ou [Create Deep Links to App Content (Création de liens profonds vers le contenu des applications)](https://developer.android.com/training/app-links/deep-linking) pour Android. - - - - ##### Point de contrôle - Ajoutez `appUrlOpen` au composant `App` de votre application et connectez-vous. La fenêtre du navigateur devrait se fermer une fois que l’utilisateur s’authentifie et se connecte à votre application. - -
- -
- Maintenant que les utilisateurs peuvent se connecter, vous devez configurer [une façon de se déconnecter](https://auth0.com/docs/logout/guides/logout-auth0). Les utilisateurs doivent être redirigés vers le point de terminaison de déconnexion Auth0 dans le navigateur pour effacer leur session de navigation. Encore une fois, le plugiciel du navigateur de Capacitor doit effectuer cette redirection afin que l’utilisateur ne quitte pas votre application et ne vive pas une expérience frustrante. - - Pour y parvenir avec Ionic et Capacitor en conjonction avec le SDK Auth0 : - - - Créez l’URL de votre application vers laquelle Auth0 doit rediriger après la déconnexion. Il s’agit d’une URL qui utilise votre schéma personnalisé enregistré et le domaine Auth0. Ajoutez-la à votre configuration **URL de déconnexions autorisées** dans Auth0 Dashboard - - Déconnectez-vous de la trousse SDK en appelant `logout` et transmettez votre URL de redirection comme paramètre `logoutParams.returnTo`. - - Définissez le paramètre `openUrl` sur un callback qui utilise le plugiciel de navigateur Capacitor pour ouvrir l’URL à l’aide de `Browser.open`. - - - De la même manière que pour l’étape de connexion, si vous ne définissez pas `openUrl` lors de l’appel de `logout`, le SDK redirige l’utilisateur vers l’URL de déconnexion à l’aide de l’application de navigateur par défaut sur l’appareil, ce qui offre une expérience utilisateur sous-optimale. - - - - ##### Point de contrôle - Fournir un moyen pour vos utilisateurs de se déconnecter de votre application. Vérifiez que vous redirigez vers Auth0, puis vers l’adresse spécifiée dans le paramètre `returnTo`. Vérifiez que vous n’êtes plus connecté à votre application. - -
- -
- La trousse SDK React Auth0 récupère le user’s profile (profil utilisateur) associé aux utilisateurs connectés dans n’importe quel composant dont vous avez besoin, comme leur nom ou leur image de profil, pour personnaliser l’interface utilisateur. Les informations de profil sont accessibles via la propriété `user` exposée par l’appel `useAuth0()`. - - L’initialisation de la trousse SDK est asynchrone, et vous devez protéger le profil utilisateur en activant les propriétés `isLoading` et `user`. Une fois que `isLoading` est `false` et que `user` a une valeur, le profil utilisateur peut être utilisé. - - - ##### Point de contrôle - Fournir un moyen pour que vos utilisateurs puissent voir leurs détails de profil utilisateur dans l’application et vérifiez que vous êtes en mesure de récupérer et d’afficher les informations de votre profil à l’écran une fois que vous avez ouvert une session. - -
- - ## Étapes suivantes - - Beau travail! Si vous en êtes arrivé là, vous devriez avoir la connexion, la déconnexion et les informations de profil utilisateur actives dans votre application. - - Cela conclut notre tutoriel de démarrage rapide, mais il y a tellement plus à explorer. Pour en savoir plus sur ce que vous pouvez faire avec Auth0, consultez : - - * [Auth0 Dashboard](https://manage.auth0.com/#) : apprenez à configurer et gérer votre locataire et vos applications Auth0 - * [Auth0 Marketplace](https://marketplace.auth0.com/) : découvrez des intégrations que vous pouvez activer pour étendre les fonctionnalités d’Auth0 -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+--- +title: "Ajouter la connexion à votre application Ionic React avec l’application Capacitor" +permalink: "interactive" +'description': "Ce guide explique comment intégrer Auth0 avec une application Ionic (React) & Capacitor en utilisant la trousse SDK React Auth0." +'og:title': "Ajouter la connexion à votre application Ionic React avec l’application Capacitor" +'og:description': "Ce guide explique comment intégrer Auth0 avec une application Ionic (React) & Capacitor en utilisant la trousse SDK React Auth0." +'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/ionic.jpeg" +'twitter:title': "Ajouter la connexion à votre application Ionic React avec l’application Capacitor" +'twitter:description': "Ce guide explique comment intégrer Auth0 avec une application Ionic (React) & Capacitor en utilisant la trousse SDK React Auth0." +sidebarTitle: Ionic & Capacitor (React) +--- + +import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; +import { LoggedInForm } from "/snippets/Login.jsx"; +import Index from "/snippets/quickstart/native/ionic-react/index.tsx.mdx"; +import Loginbutton from "/snippets/quickstart/native/ionic-react/login-button.tsx.mdx"; +import Logoutbutton from "/snippets/quickstart/native/ionic-react/logout-button.tsx.mdx"; +import App from "/snippets/quickstart/native/ionic-react/app.tsx.mdx"; +import Userprofile from "/snippets/quickstart/native/ionic-react/user-profile.tsx.mdx"; + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + +export const sections = [ + { id: "démarrage", title: "Démarrage" }, + { id: "configuration-d-auth0", title: "Configuration d’Auth0" }, + { id: "installer-la-trousse-sdk-react-auth0", title: "Installer la trousse SDK React Auth0" }, + { id: "configurer-le-composant-auth0provider", title: "Configurer le composant Auth0Provider" }, + { id: "ajouter-une-fonctionnalité-de-connexion-à-votre-application", title: "Ajouter une fonctionnalité de connexion à votre application" }, + { id: "gérer-le-rappel-de-connexion", title: "Gérer le rappel de connexion" }, + { id: "ajouter-une-fonctionnalité-de-déconnexion-à-votre-application", title: "Ajouter une fonctionnalité de déconnexion à votre application" }, + { id: "afficher-le-profil-utilisateur", title: "Afficher le profil utilisateur" } +] + + + + Auth0 vous permet d’ajouter rapidement l’authentification et de pouvoir accéder aux informations relatives au profil utilisateur dans votre application. Ce guide explique comment intégrer Auth0 avec une application Ionic (React) & Capacitor en utilisant la [trousse SDK Auth0 React](https://github.com/auth0/auth0-react). + +
+ Ce guide de démarrage rapide suppose que vous avez déjà une application [Ionic](https://ionicframework.com/) en cours d’exécution avec [Capacitor](https://capacitorjs.com/). Si ce n’est pas le cas, consultez [Using Capacitor with Ionic Framework guide (Utiliser Capacitor avec le cadre d’applications Ionic)](https://capacitorjs.com/docs/getting-started/with-ionic) pour commencer avec une application simple ou clonez nos [our sample apps (exemples d’applications)](https://github.com/auth0-samples/auth0-ionic-samples). + + Vous devez également être familiarisé avec [Capacitor development workflow (le flux de production de développement Capacitor)](https://capacitorjs.com/docs/basics/workflow). +
+ +
+ Pour utiliser les services Auth0, vous devez avoir une application installée dans Auth0 Dashboard. L’application Auth0 est l’endroit où vous allez configurer le fonctionnement de l’authentification pour votre projet. + + + Tout au long de cet article, `YOUR\_PACKAGE\_ID` est l’identifiant du package de votre application. Ceci peut être trouvé et configuré dans le champ `appId` de votre fichier `capacitor.config.ts` . Voir [Capacitor’s Config schema (Schéma de configuration du Capacitor)](https://capacitorjs.com/docs/config#schema) pour plus d’informations. + + + ### Configurer une application + + Utilisez le sélecteur interactif pour créer une nouvelle application Auth0 ou sélectionner une application existante qui représente le projet avec lequel vous souhaitez effectuer l’intégration. Dans Auth0, il est attribué à chaque application un identifiant client unique alphanumérique que votre code d’application utilisera pour appeler les API Auth0 via la trousse SDK. + + Tous les paramètres que vous configurez à l’aide de ce guide rapide seront automatiquement mis à jour pour votre application dans le [Dashboard](https://manage.auth0.com/#/), qui est l’endroit où vous pourrez gérer vos applications à l’avenir. + + Si vous préférez explorer une configuration complète, consultez plutôt un exemple d’application. + + ### Configuration des URL de rappel + + Une URL de rappel est une URL intégrée dans votre application vers laquelle vous souhaitez qu’Auth0 redirige les utilisateurs après leur authentification. Si elle n’est pas définie, les utilisateurs ne seront pas redirigés vers votre application après s’être connectés. + + + Si vous suivez notre projet à titre d’exemple, définissez ceci sur : + `YOUR\_PACKAGE\_ID://{yourTenant}.auth0.com/capacitor/YOUR\_PACKAGE\_ID/callback`. + + + ### Configuration des URL de déconnexion + + Une URL de déconnexion est une URL intégrée dans votre application vers laquelle vous souhaitez qu’Auth0 redirige les utilisateurs après leur déconnexion. Si elle n’est pas définie, les utilisateurs ne pourront pas se déconnecter de votre application et recevront un message d’erreur. + + + Si vous suivez notre projet à titre d’exemple, définissez ceci sur : + `YOUR\_PACKAGE\_ID://{yourTenant}.auth0.com/capacitor/YOUR\_PACKAGE\_ID/callback`. + + + ### Configurer les origines autorisées + + Pour pouvoir faire des requêtes à partir de votre application d’origine vers Auth0, définissez les **origines autorisées** dans vos [Application Settings (Paramètres d’application)](https://manage.auth0.com/dashboard/#/applications/%7ByourClientId%7D/settings). + + + Si vous suivez notre projet faisant office d’exemple, définissez ceci sur `capacitor://localhost, http://localhost` pour iOS et Android respectivement. + + + Enfin, assurez-vous que le **type d’application** pour votre application est défini sur **Native** dans les [Application Settings (Paramètres d’application)](https://manage.auth0.com/dashboard/#/applications/%7ByourClientId%7D/settings). +
+ +
+ Exécutez la commande suivante dans le répertoire de votre projet pour installer la trousse SDK React Auth0 : + + `npm install @auth0/auth0-react` + + La trousse SDK expose des méthodes et variables qui vous aident à intégrer Auth0 avec votre application React en utilisant les [Crochets React](https://reactjs.org/docs/hooks-overview.html) ou les [Composants d’ordre supérieur](https://reactjs.org/docs/higher-order-components.html). + + ### Installer les plugiciels Capacitor + + Ce guide rapide et cet exemple utilisent certains des plugiciels officiels Capacitor. Installez-les dans votre application à l’aide de la commande suivante : + + `npm install @capacitor/browser @capacitor/app` + + - [`@capacitor/browser`](https://capacitorjs.com/docs/apis/browser) : Vous permet d’interagir avec le navigateur de système de l’appareil, et est utilisé pour ouvrir l’URL vers le point de terminaison d’autorisation d’Auth0. + - [`@capacitor/app`](https://capacitorjs.com/docs/apis/app) : Vous permet de vous abonner à des événements d’application de haut niveau, utiles pour la gestion des Callbacks depuis Auth0. + + + Le plugiciel de navigateur de Capacitor sur iOS utilise [`SFSafariViewController`](https://developer.apple.com/documentation/safariservices/sfsafariviewcontroller), qui sur iOS 11+ ne partage pas les témoins avec Safari sur l’appareil. Cela signifie que SSO ne fonctionnera pas sur ces appareils. Si vous avez besoin de SSO, veuillez utiliser un plugiciel compatible qui utilise [ASWebAuthenticationSession](https://developer.apple.com/documentation/authenticationservices/aswebauthenticationsession). + +
+ +
+ Au cours de son fonctionnement, la trousse SDK React Auth0 utilise [React Context](https://reactjs.org/docs/context.html) pour gérer l’état d’authentification de vos utilisateurs. Une façon d’intégrer Auth0 avec votre application React est d’envelopper votre composant racine avec un `Auth0Provider` que vous pouvez importer à partir de la trousse SDK. + + Le composant `Auth0Provider` prend les props suivants : + + - `domain` : La valeur du `domain` présente dans les **paramètres** de l’application que vous avez créée dans votre Auth0 Dashboard, ou votre domaine personnalisé si vous utilisez la fonctionnalité Domaines personnalisés d’Auth0. + - `clientId` : La valeur de l’identifiant du client présente dans les **paramètres** de l’application que vous avez créée dans votre Auth0 Dashboard. + - `useRefreshTokens` : Pour utiliser auth0-react avec Ionic sur Android et iOS, il est nécessaire d’activer les jetons d’actualisation. + - `useRefreshTokensFallback` : Pour utiliser auth0-react avec Ionic sur Android et iOS, il est nécessaire de désactiver le iframe de substitution. + - `authorizationParams.redirect_uri` : L’URL vers laquelle vous souhaitez rediriger vos utilisateurs après qu’ils se soient authentifiés avec Auth0. + + + Pour conserver l’authentification après la fermeture et la réouverture de l’application, vous pouvez définir `cacheLocation` sur `localstorage` lors de la configuration du SDK, mais soyez conscient des [risques liés au stockage de jetons dans localstorage](/docs/libraries/auth0-single-page-app-sdk#change-storage-options). De plus, localstorage devrait être traité comme **transitoire** dans l’application Capacitor car les données pourraient être récupérées de façon inattendue dans certaines circonstances. Veuillez lire les [directives sur le stockage dans la documentation Capacitor](https://capacitorjs.com/docs/guides/storage#why-cant-i-just-use-localstorage-or-indexeddb). + En outre, le SDK a la capacité [d’utiliser une implémentation de cache personnalisée](https://github.com/auth0/auth0-spa-js/blob/master/EXAMPLES.md#creating-a-custom-cache) pour stocker des jetons, si vous avez une exigence d’utiliser un mécanisme de stockage plus sûr et persistant. + **Notez** que nous recommandons **de ne pas** utiliser le [plugiciel Capacitor pour stocker](https://capacitorjs.com/docs/apis/storage) les jetons, car cela est soutenu par [UserDefaults](https://developer.apple.com/documentation/foundation/userdefaults) et [SharedPreferences](https://developer.android.com/reference/android/content/SharedPreferences) sur iOS et Android respectivement. Les données stockées à l’aide de ces API ne sont pas cryptées, non sécurisées et peuvent également être synchronisées dans le nuage. + + + + ##### Point de contrôle + Ajoutez le composant `Auth0Provider` d’une manière qui enveloppe votre composant `App`, puis exécutez votre application pour vérifier que le SDK est initialisé correctement et que votre application ne lance pas d’erreurs liées à Auth0. + +
+ +
+ Dans une application Capacitor, le plugiciel [Capacitor’s Browser](https://capacitorjs.com/docs/apis/browser) effectue une redirection vers la [Universal Login Page (page de connexion universelle) d’Auth0](https://auth0.com/universal-login) Auth0. Définissez le paramètre `openUrl` sur la fonction `loginWithRedirect` pour utiliser `Browser.open` afin que l’URL soit ouverte à l’aide du composant de navigateur système de l’appareil ([SFSafariViewController](https://developer.apple.com/documentation/safariservices/sfsafariviewcontroller) sur iOS et [Chrome Custom Tabs [Onglets personnalisés Chrome]](https://developer.chrome.com/docs/android/custom-tabs) sur Android). + + + Par défaut, la méthode `loginWithRedirect` de la trousse SDK utilise `window.location.href` pour accéder à la page de connexion dans l’application de navigateur par défaut sur l’appareil de l’utilisateur plutôt que dans le composant de navigateur système approprié pour la plate-forme. L’utilisateur quitterait votre application pour s’authentifier et pourrait rendre l’expérience utilisateur sous-optimale. + + + + ##### Point de contrôle + La fonction `loginWithRedirect` indique à la trousse SDK d’initier le flux de connexion, en utilisant la fonction `Browser.open` pour ouvrir l’URL de connexion avec le composant navigateur du système de la plateforme en définissant le paramètre `openUrl`. Cela permet à votre utilisateur de se connecter à votre application. Les utilisateurs sont redirigés vers la page de connexion à Auth0 et ne reçoivent aucune erreur. + +
+ +
+ Une fois que les utilisateurs sont connectés avec la page de connexion universelle, ils sont redirigés vers votre application au moyen d’une URL avec un schéma d’URL personnalisé. L’événement `appUrlOpen` doit être traité au sein de votre application. Vous pouvez appeler la méthode `handleRedirectCallback` à partir de la trousse SDK Auth0 pour initialiser l’état d’authentification. + + Vous pouvez utiliser cette méthode uniquement sur une redirection depuis Auth0. Vérifiez que les paramètres `code` et `state` sont présents dans l’URL. + + La méthode `Browser.close()` devrait fermer le navigateur lorsque cet événement est déclenché. + + + Cet article suppose que vous utiliserez des schémas d’URL personnalisés pour gérer le rappel dans votre application. Pour ce faire, enregistrez votre `YOUR\_PACKAGE\_ID` comme schéma d’URL pour la plateforme de votre choix. Pour en savoir plus, lire [Defining a Custom URL Scheme (Définition d’un schéma d’URL personnalisé)](https://developer.apple.com/documentation/xcode/defining-a-custom-url-scheme-for-your-app) pour iOS ou [Create Deep Links to App Content (Création de liens profonds vers le contenu des applications)](https://developer.android.com/training/app-links/deep-linking) pour Android. + + + + ##### Point de contrôle + Ajoutez `appUrlOpen` au composant `App` de votre application et connectez-vous. La fenêtre du navigateur devrait se fermer une fois que l’utilisateur s’authentifie et se connecte à votre application. + +
+ +
+ Maintenant que les utilisateurs peuvent se connecter, vous devez configurer [une façon de se déconnecter](https://auth0.com/docs/logout/guides/logout-auth0). Les utilisateurs doivent être redirigés vers le point de terminaison de déconnexion Auth0 dans le navigateur pour effacer leur session de navigation. Encore une fois, le plugiciel du navigateur de Capacitor doit effectuer cette redirection afin que l’utilisateur ne quitte pas votre application et ne vive pas une expérience frustrante. + + Pour y parvenir avec Ionic et Capacitor en conjonction avec le SDK Auth0 : + + - Créez l’URL de votre application vers laquelle Auth0 doit rediriger après la déconnexion. Il s’agit d’une URL qui utilise votre schéma personnalisé enregistré et le domaine Auth0. Ajoutez-la à votre configuration **URL de déconnexions autorisées** dans Auth0 Dashboard + - Déconnectez-vous de la trousse SDK en appelant `logout` et transmettez votre URL de redirection comme paramètre `logoutParams.returnTo`. + - Définissez le paramètre `openUrl` sur un callback qui utilise le plugiciel de navigateur Capacitor pour ouvrir l’URL à l’aide de `Browser.open`. + + + De la même manière que pour l’étape de connexion, si vous ne définissez pas `openUrl` lors de l’appel de `logout`, le SDK redirige l’utilisateur vers l’URL de déconnexion à l’aide de l’application de navigateur par défaut sur l’appareil, ce qui offre une expérience utilisateur sous-optimale. + + + + ##### Point de contrôle + Fournir un moyen pour vos utilisateurs de se déconnecter de votre application. Vérifiez que vous redirigez vers Auth0, puis vers l’adresse spécifiée dans le paramètre `returnTo`. Vérifiez que vous n’êtes plus connecté à votre application. + +
+ +
+ La trousse SDK React Auth0 récupère le user’s profile (profil utilisateur) associé aux utilisateurs connectés dans n’importe quel composant dont vous avez besoin, comme leur nom ou leur image de profil, pour personnaliser l’interface utilisateur. Les informations de profil sont accessibles via la propriété `user` exposée par l’appel `useAuth0()`. + + L’initialisation de la trousse SDK est asynchrone, et vous devez protéger le profil utilisateur en activant les propriétés `isLoading` et `user`. Une fois que `isLoading` est `false` et que `user` a une valeur, le profil utilisateur peut être utilisé. + + + ##### Point de contrôle + Fournir un moyen pour que vos utilisateurs puissent voir leurs détails de profil utilisateur dans l’application et vérifiez que vous êtes en mesure de récupérer et d’afficher les informations de votre profil à l’écran une fois que vous avez ouvert une session. + +
+ + ## Étapes suivantes + + Beau travail! Si vous en êtes arrivé là, vous devriez avoir la connexion, la déconnexion et les informations de profil utilisateur actives dans votre application. + + Cela conclut notre tutoriel de démarrage rapide, mais il y a tellement plus à explorer. Pour en savoir plus sur ce que vous pouvez faire avec Auth0, consultez : + + * [Auth0 Dashboard](https://manage.auth0.com/#) : apprenez à configurer et gérer votre locataire et vos applications Auth0 + * [Auth0 Marketplace](https://marketplace.auth0.com/) : découvrez des intégrations que vous pouvez activer pour étendre les fonctionnalités d’Auth0 +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
diff --git a/main/docs/fr-ca/quickstart/native/ionic-vue/interactive.mdx b/main/docs/fr-ca/quickstart/native/ionic-vue/interactive.mdx index 6fff44449..6408f16e4 100644 --- a/main/docs/fr-ca/quickstart/native/ionic-vue/interactive.mdx +++ b/main/docs/fr-ca/quickstart/native/ionic-vue/interactive.mdx @@ -1,256 +1,258 @@ ---- -title: "Ajouter la connexion à votre application Ionic Vue avec l’application Capacitor" -permalink: "interactive" -'description': "Ce guide montre comment intégrer Auth0 avec une application Ionic (Vue) et Capacitor en utilisant la trousse SDK Vue Auth0." -'og:title': "Ajouter la connexion à votre application Ionic Vue avec l’application Capacitor" -'og:description': "Ce guide montre comment intégrer Auth0 avec une application Ionic (Vue) et Capacitor en utilisant la trousse SDK Vue Auth0." -'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/ionic.jpeg" -'twitter:title': "Ajouter la connexion à votre application Ionic Vue avec l’application Capacitor" -'twitter:description': "Ce guide montre comment intégrer Auth0 avec une application Ionic (Vue) et Capacitor en utilisant la trousse SDK Vue Auth0." -sidebarTitle: Ionic & Capacitor (Vue) ---- - -import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; -import { LoggedInForm } from "/snippets/Login.jsx"; -import Main from "/snippets/quickstart/native/ionic-vue/main.ts.mdx"; -import Loginbutton from "/snippets/quickstart/native/ionic-vue/LoginButton.vue.mdx"; -import Logoutbutton from "/snippets/quickstart/native/ionic-vue/LogoutButton.vue.mdx"; -import Userprofile from "/snippets/quickstart/native/ionic-vue/UserProfile.vue.mdx"; - -export const sections = [ - { id: "démarrage", title: "Démarrage" }, - { id: "configuration-d-auth0", title: "Configuration d’Auth0" }, - { id: "installer-la-trousse-sdk-vue-auth0", title: "Installer la trousse SDK Vue Auth0" }, - { id: "configurer-le-plugiciel-createauht0", title: "Configurer le plugiciel CreateAuht0" }, - { id: "ajouter-une-fonctionnalité-de-connexion-à-votre-application", title: "Ajouter une fonctionnalité de connexion à votre application" }, - { id: "gérer-le-rappel-de-connexion", title: "Gérer le rappel de connexion" }, - { id: "ajouter-une-fonctionnalité-de-déconnexion-à-votre-application", title: "Ajouter une fonctionnalité de déconnexion à votre application" }, - { id: "afficher-le-profil-utilisateur", title: "Afficher le profil utilisateur" } -] - - - - Auth0 vous permet d’ajouter rapidement l’authentification et de pouvoir accéder aux informations relatives au profil utilisateur dans votre application. Ce guide montre comment intégrer Auth0 avec une application Ionic (Vue) et Capacitor en utilisant la trousse [SDK Vue Auth0](https://github.com/auth0/auth0-vue). - -
- Ce guide de démarrage rapide suppose que vous avez déjà une application [Ionic](https://ionicframework.com/) en cours d’exécution avec [Capacitor](https://capacitorjs.com/). Si ce n’est pas le cas, consultez [Utiliser Capacitor avec Ionic Framework](https://capacitorjs.com/docs/getting-started/with-ionic) pour commencer avec une application simple ou clonez nos [our sample apps (exemples d’applications)](https://github.com/auth0-samples/auth0-ionic-samples). - - Vous devez également être familiarisé avec [Capacitor development workflow (le flux de production de développement Capacitor)](https://capacitorjs.com/docs/basics/workflow). -
- -
- Pour utiliser les services Auth0, vous devez avoir une application installée dans Auth0 Dashboard. L’application Auth0 est l’endroit où vous allez configurer le fonctionnement de l’authentification pour votre projet. - - - Tout au long de cet article, `YOUR\_PACKAGE\_ID` est l’identificateur du package de votre application. Il peut être trouvé et configuré dans le champ `appId` de votre fichier `capacitor.config.ts`. Voir [Schéma de configuration de Capacitor](https://capacitorjs.com/docs/config#schema) pour plus d’informations. - - - ### Configurer une application - - Utilisez le sélecteur interactif pour créer une nouvelle application Auth0 ou sélectionner une application existante qui représente le projet avec lequel vous souhaitez effectuer l’intégration. Dans Auth0, il est attribué à chaque application un identifiant client unique alphanumérique que votre code d’application utilisera pour appeler les API Auth0 via la trousse SDK. - - Tous les paramètres que vous configurez à l’aide de ce guide rapide seront automatiquement mis à jour pour votre application dans le [Dashboard](https://manage.auth0.com/#/), qui est l’endroit où vous pourrez gérer vos applications à l’avenir. - - Si vous préférez explorer une configuration complète, consultez plutôt un exemple d’application. - - ### Configurer les URL de rappel - - Une URL de rappel est une URL intégrée dans votre application vers laquelle vous souhaitez qu’Auth0 redirige les utilisateurs après leur authentification. Si elle n’est pas définie, les utilisateurs ne seront pas redirigés vers votre application après s’être connectés. - - - Si vous suivez notre projet à titre d’exemple, définissez ceci sur `YOUR\_PACKAGE\_ID://{yourDomain}/capacitor/YOUR\_PACKAGE\_ID/callback` - - - ### Configuration des URL de déconnexion - - Une URL de déconnexion est une URL intégrée dans votre application vers laquelle vous souhaitez qu’Auth0 redirige les utilisateurs après leur déconnexion. Si elle n’est pas définie, les utilisateurs ne pourront pas se déconnecter de votre application et recevront un message d’erreur. - - - Si vous suivez notre projet à titre d’exemple, définissez ceci sur `YOUR\_PACKAGE\_ID://{yourDomain}/capacitor/YOUR\_PACKAGE\_ID/callback`. - - - ### Configurer les origines autorisées - - Pour pouvoir faire des requêtes à partir de votre application d’origine vers Auth0, définissez les **origines autorisées** dans vos [Application Settings (Paramètres d’application)](https://manage.auth0.com/#/applications/%7ByourClientId%7D/settings). - - - Si vous suivez notre projet à titre d’exemple, définissez ceci sur `capacitor://localhost, http://localhost` pour iOS et Android respectivement. - - - Enfin, assurez-vous que le **type d’application** pour votre application est défini sur **Native** dans les [Application Settings (Paramètres d’application)](https://manage.auth0.com/#/applications/%7ByourClientId%7D/settings). -
- -
- Exécutez la commande suivante dans le répertoire de votre projet pour installer la trousse SDK Vue Auth0 : - - `npm install @auth0/auth0-vue` - - La trousse SDK expose plusieurs types qui vous aident à intégrer Auth0 avec votre application Vue, y compris un module et un service d’authentification. - - ### Installer les plugiciels Capacitor - - Ce guide rapide et cet exemple utilisent certains des plugiciels officiels Capacitor. Installez-les dans votre application à l’aide de la commande suivante : - - npm install @capacitor/browser @capacitor/app - - - [`@capacitor/browser`](https://capacitorjs.com/docs/apis/browser) : vous permet d’interagir avec le navigateur de système de l’appareil et est utilisé pour ouvrir l’URL vers le point de terminaison d’autorisation de Auth0 - - [`@capacitor/app`](https://capacitorjs.com/docs/apis/app) : vous permet de souscrire à des événements d’application de haut niveau, utiles pour la gestion des Callbacks depuis Auth0 - - - Le plugiciel de navigateur de Capacitor sur iOS utilise [`SFSafariViewController`](https://developer.apple.com/documentation/safariservices/sfsafariviewcontroller), qui sur iOS 11+ ne partage pas les témoins avec Safari sur l’appareil. Cela signifie que [SSO](https://auth0.com/docs/sso) ne fonctionnera pas sur ces appareils. Si vous avez besoin de SSO, veuillez utiliser un plugiciel compatible qui utilise [ASWebAuthenticationSession](https://developer.apple.com/documentation/authenticationservices/aswebauthenticationsession). - -
- -
- La trousse SDK exporte `createAuth0`, un composable qui contient tous les services nécessaires au fonctionnement du SDK. Ce composable doit être enregistré avec votre application et être configuré avec votre domaine Auth0 et votre ID client. - - Le composable `createAuth0` prend la configuration suivante : - - - `domain` : La valeur `domain` présente dans les **Settings (Paramètres)** de l’application que vous avez créée dans le Auth0 Dashboard, ou votre domaine personnalisé si vous utilisez la [fonctionnalité de domaines personnalisés](http://localhost:3000/docs/custom-domains) d’Auth0. - - `clientId` : La valeur de l’identificateur client présente dans les **Settings (Paramètres)** de l’application que vous avez créée dans l’Auth0 Dashboard. - - `useRefreshTokens` : Pour utiliser auth0-vue avec Ionic sur Android et iOS, il est nécessaire d’activer les jetons d’actualisation. - - `useRefreshTokensFallback` : Pour utiliser auth0-vue avec Ionic sur Android et iOS, il est nécessaire de désactiver le iframe de substitution. - - `authorizationParams.redirect_uri` : URL pour rediriger vos utilisateurs après qu’ils se sont authentifiés avec Auth0. - - - Pour conserver l’authentification après la fermeture et la réouverture de l’application, vous pouvez définir `cacheLocation` sur `localstorage` lors de la configuration de la trousse SDK, mais soyez conscient des [risques liés au stockage de jetons dans localstorage](https://auth0.com/docs/libraries/auth0-single-page-app-sdk#change-storage-options). De plus, localstorage devrait être traité comme **transitoire** dans l’application Capacitor car les données pourraient être récupérées de façon inattendue dans certaines circonstances. Veuillez lire les [directives sur le stockage dans la documentation Capacitor](https://capacitorjs.com/docs/guides/storage#why-cant-i-just-use-localstorage-or-indexeddb). - En outre, la trousse SDK a la capacité [d’utiliser une implémentation de cache personnalisée](https://github.com/auth0/auth0-spa-js/blob/master/EXAMPLES.md#creating-a-custom-cache) pour stocker des jetons, si vous avez une exigence d’utiliser un mécanisme de stockage plus sûr et persistant. - **Notez** que nous recommandons **de ne pas** utiliser le [plugiciel Capacitor pour stocker](https://capacitorjs.com/docs/apis/storage) les jetons, car cela est soutenu par [UserDefaults](https://developer.apple.com/documentation/foundation/userdefaults) et [SharedPreferences](https://developer.android.com/reference/android/content/SharedPreferences) sur iOS et Android respectivement. Les données stockées à l’aide de ces API ne sont pas chiffrées, non sécurisées et peuvent également être synchronisées dans le nuage. - - - - ##### Point de contrôle - Maintenant que vous avez configuré votre application avec la trousse SDK Vue Auth0, exécutez votre application pour vérifier que la trousse SDK est initialisée sans erreur et que votre application s’exécute comme auparavant. - -
- -
- Dans une application Capacitor, le [plugicielCapacitor’s Browser](https://capacitorjs.com/docs/apis/browser) effectue une redirection vers la [Universal Login Page (page de connexion universelle)](https://auth0.com/universal-login) Auth0. Définissez le paramètre `openUrl` sur la fonction `loginWithRedirect` pour utiliser `Browser.open` afin que l’URL soit ouverte à l’aide du composant de navigateur système de l’appareil ([SFSafariViewController](https://developer.apple.com/documentation/safariservices/sfsafariviewcontroller) sur iOS et [Chrome Custom Tabs [Onglets personnalisés Chrome]](https://developer.chrome.com/docs/android/custom-tabs) sur Android). - - - Par défaut, la méthode `loginWithRedirect` de la trousse SDK utilise `window.location.href` pour accéder à la page de connexion dans l’application de navigateur par défaut sur l’appareil de l’utilisateur plutôt que dans le composant de navigateur système approprié pour la plateforme. L’utilisateur quitterait votre application pour s’authentifier et pourrait rendre l’expérience utilisateur frustrante. - - - - ##### Point de contrôle - La fonction `loginWithRedirect` indique à la trousse SDK d’initier le flux de connexion, en utilisant la fonction `Browser.open` pour ouvrir l’URL de connexion avec le composant navigateur du système de la plateforme en définissant le paramètre `openUrl`. Cela permet à votre utilisateur de se connecter à votre application. Les utilisateurs sont redirigés vers la page de connexion à Auth0 et ne reçoivent aucune erreur. - -
- -
- Une fois que les utilisateurs sont connectés avec la page de connexion universelle, ils sont redirigés vers votre application au moyen d’une URL avec un schéma d’URL personnalisé. L’événement `appUrlOpen` doit être traité au sein de votre application. Vous pouvez appeler la méthode `handleRedirectCallback` à partir de la trousse SDK Auth0 pour initialiser l’état d’authentification. - - Vous pouvez utiliser cette méthode uniquement sur une redirection depuis Auth0. Vérifiez que les paramètres `code` et `state` sont présents dans l’URL. - - La méthode `Browser.close()` devrait fermer le navigateur lorsque cet événement est déclenché. - - - Cet article suppose que vous utiliserez des schémas d’URL personnalisés pour gérer le callback dans votre application. Pour ce faire, enregistrez votre `YOUR\_PACKAGE\_ID` comme schéma d’URL pour la plateforme de votre choix. Pour en savoir plus, lisez [Définition d’un schéma d’URL personnalisé](https://developer.apple.com/documentation/xcode/defining-a-custom-url-scheme-for-your-app) pour iOS ou [Création de liens profonds vers le contenu des applications](https://developer.android.com/training/app-links/deep-linking) pour Android. - - - - ##### Point de contrôle - Ajoutez `appUrlOpen` au composant `App` de votre application et connectez-vous. La fenêtre du navigateur devrait se fermer une fois que l’utilisateur s’authentifie et se connecte à votre application. - -
- -
- Maintenant que les utilisateurs peuvent se connecter, vous devez configurer [une façon de se déconnecter](https://auth0.com/docs/logout/guides/logout-auth0). Les utilisateurs doivent être redirigés vers le point de terminaison de déconnexion Auth0 dans le navigateur pour effacer leur session de navigation. Encore une fois, le plugiciel du navigateur de Capacitor doit effectuer cette redirection afin que l’utilisateur ne quitte pas votre application et ne vive pas une expérience frustrante. - - Pour y parvenir avec Ionic et Capacitor en conjonction avec le SDK Auth0 : - - - Créez l’URL de votre application vers laquelle Auth0 doit rediriger après la déconnexion. Il s’agit d’une URL qui utilise votre schéma personnalisé enregistré et le domaine Auth0. Ajoutez-la à votre configuration **URL de déconnexions autorisées** dans Auth0 Dashboard - - Déconnectez-vous de la trousse SDK en appelant `logout` et transmettez votre URL de redirection comme paramètre `logoutParams.returnTo`. - - Définissez le paramètre `openUrl` sur un callback qui utilise le plugiciel de navigateur Capacitor pour ouvrir l’URL à l’aide de `Browser.open`. - - - De la même manière que pour l’étape de connexion, si vous ne définissez pas `openUrl` lors de l’appel de `logout`, la trousse SDK redirige l’utilisateur vers l’URL de déconnexion à l’aide de l’application de navigateur par défaut sur l’appareil, ce qui offre une expérience utilisateur sous-optimale. - - - - ##### Point de contrôle - Fournir un moyen pour vos utilisateurs de se déconnecter de votre application. Vérifiez que vous redirigez vers Auth0, puis vers l’adresse spécifiée dans le paramètre `returnTo`. Vérifiez que vous n’êtes plus connecté à votre application. - -
- -
- La trousse SDK Vue Auth0 récupère le [profil utilisateur](https://auth0.com/docs/users/concepts/overview-user-profile) associé aux utilisateurs connectés dans n’importe quel composant dont vous avez besoin, comme leur nom ou leur image de profil, pour personnaliser l’interface utilisateur. Les informations de profil sont accessibles à partir de la propriété `user` exposée par la fonction composable `useAuth0()`. - - L’initialisation de la trousse SDK est asynchrone, et vous devez protéger le profil utilisateur en activant les propriétés `isLoading` et `user`. Une fois que `isLoading` est `false` et que `user` a une valeur, le profil utilisateur peut être utilisé. - - - ##### Point de contrôle - Assurez-vous que vos utilisateurs ont un moyen de consulter leurs informations de profil dans l’application et vérifiez que vous êtes en mesure de récupérer et d’afficher les informations de votre profil à l’écran une fois que vous vous êtes connecté. - -
- - ## Étapes suivantes - - Beau travail! Si vous en êtes arrivé là, vous devriez avoir la connexion, la déconnexion et les informations de profil utilisateur actives dans votre application. - - Cela conclut notre tutoriel de démarrage rapide, mais il y a tellement plus à explorer. Pour en savoir plus sur ce que vous pouvez faire avec Auth0, consultez : - - * [Auth0 Dashboard](https://manage.auth0.com/#) : apprenez à configurer et gérer votre locataire et vos applications Auth0 - * [Auth0 Marketplace](https://marketplace.auth0.com/) : découvrez des intégrations que vous pouvez activer pour étendre les fonctionnalités d’Auth0 -
- - - - - - - - - - - - - - - - -
- - - - - - - - - -
- - - - - - - -
- - - - - - - - - -
- - - - - - - - -
- - - - - - - +--- +title: "Ajouter la connexion à votre application Ionic Vue avec l’application Capacitor" +permalink: "interactive" +'description': "Ce guide montre comment intégrer Auth0 avec une application Ionic (Vue) et Capacitor en utilisant la trousse SDK Vue Auth0." +'og:title': "Ajouter la connexion à votre application Ionic Vue avec l’application Capacitor" +'og:description': "Ce guide montre comment intégrer Auth0 avec une application Ionic (Vue) et Capacitor en utilisant la trousse SDK Vue Auth0." +'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/ionic.jpeg" +'twitter:title': "Ajouter la connexion à votre application Ionic Vue avec l’application Capacitor" +'twitter:description': "Ce guide montre comment intégrer Auth0 avec une application Ionic (Vue) et Capacitor en utilisant la trousse SDK Vue Auth0." +sidebarTitle: Ionic & Capacitor (Vue) +--- + +import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; +import { LoggedInForm } from "/snippets/Login.jsx"; +import Main from "/snippets/quickstart/native/ionic-vue/main.ts.mdx"; +import Loginbutton from "/snippets/quickstart/native/ionic-vue/LoginButton.vue.mdx"; +import Logoutbutton from "/snippets/quickstart/native/ionic-vue/LogoutButton.vue.mdx"; +import Userprofile from "/snippets/quickstart/native/ionic-vue/UserProfile.vue.mdx"; + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + +export const sections = [ + { id: "démarrage", title: "Démarrage" }, + { id: "configuration-d-auth0", title: "Configuration d’Auth0" }, + { id: "installer-la-trousse-sdk-vue-auth0", title: "Installer la trousse SDK Vue Auth0" }, + { id: "configurer-le-plugiciel-createauht0", title: "Configurer le plugiciel CreateAuht0" }, + { id: "ajouter-une-fonctionnalité-de-connexion-à-votre-application", title: "Ajouter une fonctionnalité de connexion à votre application" }, + { id: "gérer-le-rappel-de-connexion", title: "Gérer le rappel de connexion" }, + { id: "ajouter-une-fonctionnalité-de-déconnexion-à-votre-application", title: "Ajouter une fonctionnalité de déconnexion à votre application" }, + { id: "afficher-le-profil-utilisateur", title: "Afficher le profil utilisateur" } +] + + + + Auth0 vous permet d’ajouter rapidement l’authentification et de pouvoir accéder aux informations relatives au profil utilisateur dans votre application. Ce guide montre comment intégrer Auth0 avec une application Ionic (Vue) et Capacitor en utilisant la trousse [SDK Vue Auth0](https://github.com/auth0/auth0-vue). + +
+ Ce guide de démarrage rapide suppose que vous avez déjà une application [Ionic](https://ionicframework.com/) en cours d’exécution avec [Capacitor](https://capacitorjs.com/). Si ce n’est pas le cas, consultez [Utiliser Capacitor avec Ionic Framework](https://capacitorjs.com/docs/getting-started/with-ionic) pour commencer avec une application simple ou clonez nos [our sample apps (exemples d’applications)](https://github.com/auth0-samples/auth0-ionic-samples). + + Vous devez également être familiarisé avec [Capacitor development workflow (le flux de production de développement Capacitor)](https://capacitorjs.com/docs/basics/workflow). +
+ +
+ Pour utiliser les services Auth0, vous devez avoir une application installée dans Auth0 Dashboard. L’application Auth0 est l’endroit où vous allez configurer le fonctionnement de l’authentification pour votre projet. + + + Tout au long de cet article, `YOUR\_PACKAGE\_ID` est l’identificateur du package de votre application. Il peut être trouvé et configuré dans le champ `appId` de votre fichier `capacitor.config.ts`. Voir [Schéma de configuration de Capacitor](https://capacitorjs.com/docs/config#schema) pour plus d’informations. + + + ### Configurer une application + + Utilisez le sélecteur interactif pour créer une nouvelle application Auth0 ou sélectionner une application existante qui représente le projet avec lequel vous souhaitez effectuer l’intégration. Dans Auth0, il est attribué à chaque application un identifiant client unique alphanumérique que votre code d’application utilisera pour appeler les API Auth0 via la trousse SDK. + + Tous les paramètres que vous configurez à l’aide de ce guide rapide seront automatiquement mis à jour pour votre application dans le [Dashboard](https://manage.auth0.com/#/), qui est l’endroit où vous pourrez gérer vos applications à l’avenir. + + Si vous préférez explorer une configuration complète, consultez plutôt un exemple d’application. + + ### Configurer les URL de rappel + + Une URL de rappel est une URL intégrée dans votre application vers laquelle vous souhaitez qu’Auth0 redirige les utilisateurs après leur authentification. Si elle n’est pas définie, les utilisateurs ne seront pas redirigés vers votre application après s’être connectés. + + + Si vous suivez notre projet à titre d’exemple, définissez ceci sur `YOUR\_PACKAGE\_ID://{yourDomain}/capacitor/YOUR\_PACKAGE\_ID/callback` + + + ### Configuration des URL de déconnexion + + Une URL de déconnexion est une URL intégrée dans votre application vers laquelle vous souhaitez qu’Auth0 redirige les utilisateurs après leur déconnexion. Si elle n’est pas définie, les utilisateurs ne pourront pas se déconnecter de votre application et recevront un message d’erreur. + + + Si vous suivez notre projet à titre d’exemple, définissez ceci sur `YOUR\_PACKAGE\_ID://{yourDomain}/capacitor/YOUR\_PACKAGE\_ID/callback`. + + + ### Configurer les origines autorisées + + Pour pouvoir faire des requêtes à partir de votre application d’origine vers Auth0, définissez les **origines autorisées** dans vos [Application Settings (Paramètres d’application)](https://manage.auth0.com/#/applications/%7ByourClientId%7D/settings). + + + Si vous suivez notre projet à titre d’exemple, définissez ceci sur `capacitor://localhost, http://localhost` pour iOS et Android respectivement. + + + Enfin, assurez-vous que le **type d’application** pour votre application est défini sur **Native** dans les [Application Settings (Paramètres d’application)](https://manage.auth0.com/#/applications/%7ByourClientId%7D/settings). +
+ +
+ Exécutez la commande suivante dans le répertoire de votre projet pour installer la trousse SDK Vue Auth0 : + + `npm install @auth0/auth0-vue` + + La trousse SDK expose plusieurs types qui vous aident à intégrer Auth0 avec votre application Vue, y compris un module et un service d’authentification. + + ### Installer les plugiciels Capacitor + + Ce guide rapide et cet exemple utilisent certains des plugiciels officiels Capacitor. Installez-les dans votre application à l’aide de la commande suivante : + + npm install @capacitor/browser @capacitor/app + + - [`@capacitor/browser`](https://capacitorjs.com/docs/apis/browser) : vous permet d’interagir avec le navigateur de système de l’appareil et est utilisé pour ouvrir l’URL vers le point de terminaison d’autorisation de Auth0 + - [`@capacitor/app`](https://capacitorjs.com/docs/apis/app) : vous permet de souscrire à des événements d’application de haut niveau, utiles pour la gestion des Callbacks depuis Auth0 + + + Le plugiciel de navigateur de Capacitor sur iOS utilise [`SFSafariViewController`](https://developer.apple.com/documentation/safariservices/sfsafariviewcontroller), qui sur iOS 11+ ne partage pas les témoins avec Safari sur l’appareil. Cela signifie que [SSO](https://auth0.com/docs/sso) ne fonctionnera pas sur ces appareils. Si vous avez besoin de SSO, veuillez utiliser un plugiciel compatible qui utilise [ASWebAuthenticationSession](https://developer.apple.com/documentation/authenticationservices/aswebauthenticationsession). + +
+ +
+ La trousse SDK exporte `createAuth0`, un composable qui contient tous les services nécessaires au fonctionnement du SDK. Ce composable doit être enregistré avec votre application et être configuré avec votre domaine Auth0 et votre ID client. + + Le composable `createAuth0` prend la configuration suivante : + + - `domain` : La valeur `domain` présente dans les **Settings (Paramètres)** de l’application que vous avez créée dans le Auth0 Dashboard, ou votre domaine personnalisé si vous utilisez la [fonctionnalité de domaines personnalisés](http://localhost:3000/docs/custom-domains) d’Auth0. + - `clientId` : La valeur de l’identificateur client présente dans les **Settings (Paramètres)** de l’application que vous avez créée dans l’Auth0 Dashboard. + - `useRefreshTokens` : Pour utiliser auth0-vue avec Ionic sur Android et iOS, il est nécessaire d’activer les jetons d’actualisation. + - `useRefreshTokensFallback` : Pour utiliser auth0-vue avec Ionic sur Android et iOS, il est nécessaire de désactiver le iframe de substitution. + - `authorizationParams.redirect_uri` : URL pour rediriger vos utilisateurs après qu’ils se sont authentifiés avec Auth0. + + + Pour conserver l’authentification après la fermeture et la réouverture de l’application, vous pouvez définir `cacheLocation` sur `localstorage` lors de la configuration de la trousse SDK, mais soyez conscient des [risques liés au stockage de jetons dans localstorage](https://auth0.com/docs/libraries/auth0-single-page-app-sdk#change-storage-options). De plus, localstorage devrait être traité comme **transitoire** dans l’application Capacitor car les données pourraient être récupérées de façon inattendue dans certaines circonstances. Veuillez lire les [directives sur le stockage dans la documentation Capacitor](https://capacitorjs.com/docs/guides/storage#why-cant-i-just-use-localstorage-or-indexeddb). + En outre, la trousse SDK a la capacité [d’utiliser une implémentation de cache personnalisée](https://github.com/auth0/auth0-spa-js/blob/master/EXAMPLES.md#creating-a-custom-cache) pour stocker des jetons, si vous avez une exigence d’utiliser un mécanisme de stockage plus sûr et persistant. + **Notez** que nous recommandons **de ne pas** utiliser le [plugiciel Capacitor pour stocker](https://capacitorjs.com/docs/apis/storage) les jetons, car cela est soutenu par [UserDefaults](https://developer.apple.com/documentation/foundation/userdefaults) et [SharedPreferences](https://developer.android.com/reference/android/content/SharedPreferences) sur iOS et Android respectivement. Les données stockées à l’aide de ces API ne sont pas chiffrées, non sécurisées et peuvent également être synchronisées dans le nuage. + + + + ##### Point de contrôle + Maintenant que vous avez configuré votre application avec la trousse SDK Vue Auth0, exécutez votre application pour vérifier que la trousse SDK est initialisée sans erreur et que votre application s’exécute comme auparavant. + +
+ +
+ Dans une application Capacitor, le [plugicielCapacitor’s Browser](https://capacitorjs.com/docs/apis/browser) effectue une redirection vers la [Universal Login Page (page de connexion universelle)](https://auth0.com/universal-login) Auth0. Définissez le paramètre `openUrl` sur la fonction `loginWithRedirect` pour utiliser `Browser.open` afin que l’URL soit ouverte à l’aide du composant de navigateur système de l’appareil ([SFSafariViewController](https://developer.apple.com/documentation/safariservices/sfsafariviewcontroller) sur iOS et [Chrome Custom Tabs [Onglets personnalisés Chrome]](https://developer.chrome.com/docs/android/custom-tabs) sur Android). + + + Par défaut, la méthode `loginWithRedirect` de la trousse SDK utilise `window.location.href` pour accéder à la page de connexion dans l’application de navigateur par défaut sur l’appareil de l’utilisateur plutôt que dans le composant de navigateur système approprié pour la plateforme. L’utilisateur quitterait votre application pour s’authentifier et pourrait rendre l’expérience utilisateur frustrante. + + + + ##### Point de contrôle + La fonction `loginWithRedirect` indique à la trousse SDK d’initier le flux de connexion, en utilisant la fonction `Browser.open` pour ouvrir l’URL de connexion avec le composant navigateur du système de la plateforme en définissant le paramètre `openUrl`. Cela permet à votre utilisateur de se connecter à votre application. Les utilisateurs sont redirigés vers la page de connexion à Auth0 et ne reçoivent aucune erreur. + +
+ +
+ Une fois que les utilisateurs sont connectés avec la page de connexion universelle, ils sont redirigés vers votre application au moyen d’une URL avec un schéma d’URL personnalisé. L’événement `appUrlOpen` doit être traité au sein de votre application. Vous pouvez appeler la méthode `handleRedirectCallback` à partir de la trousse SDK Auth0 pour initialiser l’état d’authentification. + + Vous pouvez utiliser cette méthode uniquement sur une redirection depuis Auth0. Vérifiez que les paramètres `code` et `state` sont présents dans l’URL. + + La méthode `Browser.close()` devrait fermer le navigateur lorsque cet événement est déclenché. + + + Cet article suppose que vous utiliserez des schémas d’URL personnalisés pour gérer le callback dans votre application. Pour ce faire, enregistrez votre `YOUR\_PACKAGE\_ID` comme schéma d’URL pour la plateforme de votre choix. Pour en savoir plus, lisez [Définition d’un schéma d’URL personnalisé](https://developer.apple.com/documentation/xcode/defining-a-custom-url-scheme-for-your-app) pour iOS ou [Création de liens profonds vers le contenu des applications](https://developer.android.com/training/app-links/deep-linking) pour Android. + + + + ##### Point de contrôle + Ajoutez `appUrlOpen` au composant `App` de votre application et connectez-vous. La fenêtre du navigateur devrait se fermer une fois que l’utilisateur s’authentifie et se connecte à votre application. + +
+ +
+ Maintenant que les utilisateurs peuvent se connecter, vous devez configurer [une façon de se déconnecter](https://auth0.com/docs/logout/guides/logout-auth0). Les utilisateurs doivent être redirigés vers le point de terminaison de déconnexion Auth0 dans le navigateur pour effacer leur session de navigation. Encore une fois, le plugiciel du navigateur de Capacitor doit effectuer cette redirection afin que l’utilisateur ne quitte pas votre application et ne vive pas une expérience frustrante. + + Pour y parvenir avec Ionic et Capacitor en conjonction avec le SDK Auth0 : + + - Créez l’URL de votre application vers laquelle Auth0 doit rediriger après la déconnexion. Il s’agit d’une URL qui utilise votre schéma personnalisé enregistré et le domaine Auth0. Ajoutez-la à votre configuration **URL de déconnexions autorisées** dans Auth0 Dashboard + - Déconnectez-vous de la trousse SDK en appelant `logout` et transmettez votre URL de redirection comme paramètre `logoutParams.returnTo`. + - Définissez le paramètre `openUrl` sur un callback qui utilise le plugiciel de navigateur Capacitor pour ouvrir l’URL à l’aide de `Browser.open`. + + + De la même manière que pour l’étape de connexion, si vous ne définissez pas `openUrl` lors de l’appel de `logout`, la trousse SDK redirige l’utilisateur vers l’URL de déconnexion à l’aide de l’application de navigateur par défaut sur l’appareil, ce qui offre une expérience utilisateur sous-optimale. + + + + ##### Point de contrôle + Fournir un moyen pour vos utilisateurs de se déconnecter de votre application. Vérifiez que vous redirigez vers Auth0, puis vers l’adresse spécifiée dans le paramètre `returnTo`. Vérifiez que vous n’êtes plus connecté à votre application. + +
+ +
+ La trousse SDK Vue Auth0 récupère le [profil utilisateur](https://auth0.com/docs/users/concepts/overview-user-profile) associé aux utilisateurs connectés dans n’importe quel composant dont vous avez besoin, comme leur nom ou leur image de profil, pour personnaliser l’interface utilisateur. Les informations de profil sont accessibles à partir de la propriété `user` exposée par la fonction composable `useAuth0()`. + + L’initialisation de la trousse SDK est asynchrone, et vous devez protéger le profil utilisateur en activant les propriétés `isLoading` et `user`. Une fois que `isLoading` est `false` et que `user` a une valeur, le profil utilisateur peut être utilisé. + + + ##### Point de contrôle + Assurez-vous que vos utilisateurs ont un moyen de consulter leurs informations de profil dans l’application et vérifiez que vous êtes en mesure de récupérer et d’afficher les informations de votre profil à l’écran une fois que vous vous êtes connecté. + +
+ + ## Étapes suivantes + + Beau travail! Si vous en êtes arrivé là, vous devriez avoir la connexion, la déconnexion et les informations de profil utilisateur actives dans votre application. + + Cela conclut notre tutoriel de démarrage rapide, mais il y a tellement plus à explorer. Pour en savoir plus sur ce que vous pouvez faire avec Auth0, consultez : + + * [Auth0 Dashboard](https://manage.auth0.com/#) : apprenez à configurer et gérer votre locataire et vos applications Auth0 + * [Auth0 Marketplace](https://marketplace.auth0.com/) : découvrez des intégrations que vous pouvez activer pour étendre les fonctionnalités d’Auth0 +
+ + + + + + + + + + + + + + + + +
+ + + + + + + + + +
+ + + + + + + +
+ + + + + + + + + +
+ + + + + + + + +
+ + + + + + + diff --git a/main/docs/fr-ca/quickstart/native/ios-swift/interactive.mdx b/main/docs/fr-ca/quickstart/native/ios-swift/interactive.mdx index 951da2587..31a611fdd 100644 --- a/main/docs/fr-ca/quickstart/native/ios-swift/interactive.mdx +++ b/main/docs/fr-ca/quickstart/native/ios-swift/interactive.mdx @@ -1,284 +1,286 @@ ---- -title: "Ajouter une connexion à votre application iOS ou macOS" -permalink: "interactive" -'description': "Ce guide explique comment intégrer Auth0 à n’importe quelle application iOS/macOS à l’aide du SDK Auth0.swift." -'og:title': "Ajouter une connexion à votre application iOS ou macOS" -'og:description': "Ce guide explique comment intégrer Auth0 à n’importe quelle application iOS/macOS à l’aide du SDK Auth0.swift." -'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/ios.png" -'twitter:title': "Ajouter une connexion à votre application iOS ou macOS" -'twitter:description': "Ce guide explique comment intégrer Auth0 à n’importe quelle application iOS/macOS à l’aide du SDK Auth0.swift." -sidebarTitle: iOS / macOS ---- - -import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; -import { LoggedInForm } from "/snippets/Login.jsx"; -import Auth0 from "/snippets/quickstart/native/ios-swift/Auth0.plist.mdx"; -import Mainview from "/snippets/quickstart/native/ios-swift/MainView.swift.mdx"; -import Mainview2 from "/snippets/quickstart/native/ios-swift/MainView.swift2.mdx"; -import Profileview from "/snippets/quickstart/native/ios-swift/ProfileView.swift.mdx"; -import User from "/snippets/quickstart/native/ios-swift/User.swift.mdx"; - -export const sections = [ - { id: "configuration-d-auth0", title: "Configuration d’Auth0" }, - { id: "installer-la-trousse-sdk", title: "Installer la trousse SDK" }, - { id: "configuration-de-la-trousse-sdk", title: "Configuration de la trousse SDK" }, - { id: "ajouter-une-fonctionnalité-de-connexion-à-votre-application", title: "Ajouter une fonctionnalité de connexion à votre application" }, - { id: "ajouter-une-fonctionnalité-de-déconnexion-à-votre-application", title: "Ajouter une fonctionnalité de déconnexion à votre application" }, - { id: "accéder-aux-informations-du-profil-utilisateur", title: "Accéder aux informations du profil utilisateur" } -] - - - - Ce guide explique comment ajouter l’authentification et accéder aux informations du profil utilisateur dans n’importe quelle application iOS/macOS à l’aide du SDK [Auth0.swift](https://github.com/auth0/Auth0.swift). - - Pour utiliser ce guide rapide, vous devez : - - - vous inscrire à un compte Auth0 gratuit ou vous connecter à Auth0. - - avoir une application iOS/macOS existante que vous souhaitez intégrer. Vous pouvez également consulter ou télécharger une application faisant office d’exemple lorsque vous vous connectez. - -
- Pour utiliser les services Auth0, vous devez avoir une application configurée dans Auth0 Dashboard. L’application Auth0 est l’endroit où vous allez configurer le fonctionnement de l’authentification pour l’application que vous développez. - - ### Configurer une application Auth0 - - Utilisez le sélecteur interactif pour créer une nouvelle application Auth0 ou sélectionnez une application Auth0 **native** existante. Auth0 attribue à chaque application un ID client unique alphanumérique que votre application utilise pour appeler les API Auth0 via la trousse SDK. - - Tous les paramètres que vous configurez à l’aide de ce démarrage rapide met automatiquement à jour votre application Auth0 dans le [Dashboard](https://manage.auth0.com/#/), qui est l’endroit où vous pourrez gérer vos applications à l’avenir. - - Consultez un exemple d’application si vous préférez explorer une configuration complète. - - ### Configuration des Callback URL et des URL de déconnexion. - - Auth0 fait appel aux Callback URL et aux URL de déconnexion pour rediriger les utilisateurs vers votre application. Auth0 fait appel à une URL de rappel après avoir authentifié l’utilisateur et à une URL de déconnexion après avoir supprimé le témoin de session. Si vous ne définissez pas les Callback URL et les URL de déconnexion, les utilisateurs ne pourront pas se connecter et se déconnecter de l’application, et votre application produira une erreur. - - - Sur iOS 17.4+ et macOS 14.4+, il est possible d’utiliser des liens universels comme callback URL et URL de déconnexion. Lorsqu’activé, Auth0.swift reviendra à l’utilisation d’un schéma d’URL personnalisé sur les anciennes versions iOS/MacOS. - **Cette fonctionnalité nécessite un Xcode 15.3+ et un compte Apple Developer payant.** - - - Ajoutez les URL suivantes aux **URL de rappel** et **URL de déconnexion**, selon la plateforme de votre app. Si vous avez un domaine personnalisé, utilisez-le à la place du domaine de votre locataire Auth0. - - #### iOS - - ``` - https://{yourDomain}/ios/YOUR_BUNDLE_IDENTIFIER/callback, - YOUR_BUNDLE_IDENTIFIER://{yourDomain}/ios/YOUR_BUNDLE_IDENTIFIER/callback - ``` - - #### macOS - - ``` - https://{yourDomain}/macos/YOUR_BUNDLE_IDENTIFIER/callback, - YOUR_BUNDLE_IDENTIFIER://{yourDomain}/macos/YOUR_BUNDLE_IDENTIFIER/callback - ``` - - Par exemple, si l’identifiant de votre ensemble iOS est `com.example.MyApp` et votre domaine Auth0 est `example.us.auth0.com`, cette valeur sera alors : - - ``` - https://example.us.auth0.com/ios/com.example.MyApp/callback, - com.example.MyApp://example.us.auth0.com/ios/com.example.MyApp/callback - ``` - - ### Configurer le domaine associé - - - Cette étape nécessite un compte Apple Developer payant. Il est nécessaire d’utiliser des liens universels comme callback URL et URL de déconnexion. Ignorez cette étape pour utiliser plutôt un schéma d’URL personnalisé. - - - #### Configurer l’ID Team et l’identifiant de l’ensemble - - Allez à la [page des paramètres](https://manage.auth0.com/dashboard/us/#/applications/) de votre application Auth0, faites défiler jusqu’en bas, et ouvrez **Advanced Settings (Paramètres avancés) > (Paramètres de l’appareil)**. Dans la section **iOS**, définissez **Team ID** sur votre Apple [Apple Team ID](https://developer.apple.com/help/account/manage-your-team/locate-your-team-id/) et **App ID** sur l’identifiant de l’ensemble de votre application. - - ![Auth0 Dashboard> Applications > Applications > [Native App] > Settings tab (Onglet des paramètres) > Advanced Settings (Paramètres avancés) > Device Settings tab (Onglet des paramètres de l’appareil)](/docs/images/fr-ca/cdy7uua7fh8z/62v9bB3bUVMw9XLND5lcMI/a44aa1441c4a91d615accddb0c23ea80/IOS_Settings_-_French.png) - - Cette action ajoutera votre application au fichier `apple-app-site-association` de votre locataire Auth0. - - #### Ajouter la capacité de domaine associé - - Dans Xcode, allez à l’[onglet](https://developer.apple.com/documentation/xcode/adding-capabilities-to-your-app#Add-a-capability)**Signing and Capabilities (Signature et capacités)** des paramètres cibles de votre application, puis appuyez sur le bouton **+ Capability (Capacité)**. Sélectionnez ensuite **Associated Domains (Domaines associés)**. - - ![Xcode> Onglet Signing and Capabilities (Signature et capacités) > Add New (Ajouter nouveau) > Associated Domains (Domaines associés)](/docs/images/fr-ca/cdy7uua7fh8z/72eVE104zKB5Q4NPnx6MCa/66c81ee64f104583bd00b9916778f989/ios-xcode-capabilities.png) - - Ajoutez l’[entry](https://developer.apple.com/documentation/xcode/configuring-an-associated-domain#Define-a-service-and-its-associated-domain) suivante sous **Associated Domains (Domaines associés)** : - - ``` - webcredentials:labs-fundtraining.us.auth0.com - ``` - - Si vous avez un domaine personnalisé, utilisez-le à la place du domaine de votre locataire Auth0. - - - Pour que le domaine associé fonctionne, votre application doit être signée avec votre certificat d’équipe **même lors de la construction du simulateur iOS**. Assurez-vous d’utiliser l’équipe Apple dont l’ID d’équipe est configuré dans la page des paramètres de votre application Auth0. - -
- -
- ### Utilisation du gestionnaire de packages Swift - - Ouvrez l’élément de menu suivant dans Xcode : - - **File (Fichier) > Add Package Dependencies (Ajouter des dépendances de package)...** - - Dans la zone de recherche **Search or Enter Package URL (Rechercher ou saisir l’URL du package)** entrez cette URL : - - ``` - https://github.com/auth0/Auth0.swift - ``` - - Ensuite, sélectionnez la règle de dépendance et appuyez sur **Add Package (Ajouter le package)**. - - - Pour plus d’informations sur SPM consultez la [documentation officielle](https://developer.apple.com/documentation/xcode/adding-package-dependencies-to-your-app). - - - ### Utilisation de Cocoapods - - Ajoutez la ligne suivante à votre `Podfile` : - - ``` - pod 'Auth0', '~> 2.0' - ``` - - Ensuite, exécutez `pod install`. - - - Pour plus d’informations sur CocoaPods, consultez la [documentation officielle](https://guides.cocoapods.org/using/getting-started.html). - - - ### Utilisation de Carthage - - Ajoutez la ligne suivante à votre `Cartfile` : - - ``` - github "auth0/Auth0.swift" ~> 2.0 - ``` - - Ensuite, exécutez `carthage bootstrap --use-xcframeworks`. - - - Pour en savoir plus sur Carthage, consultez la [documentation officielle](https://github.com/Carthage/Carthage#getting-started). - -
- -
- La trousse SDK Auth0.swift a besoin de votre **domain (domaine)** Auth0 et de votre **Client ID (Identifiant client)**. Ces valeurs se trouvent dans la [page des paramètres](https://manage.auth0.com/dashboard/us/#/applications/) de votre application Auth0. - - - **domain (domaine)** : Le domaine de votre locataire Auth0. Si vous avez un domaine personnalisé, utilisez-le à la place du domaine de votre locataire Auth0. - - **Client ID (Identifiant client)** L’identifiant alphanumérique unique de l’application Auth0 que vous avez configuré précédemment dans ce démarrage rapide. - - Créez un fichier `plist` nommé `Auth0.plist` dans votre ensemble d’application contenant les valeurs du domaine Auth0 et de l’identifiant client. - - - Vous pouvez également configurer la trousse SDK de manière programmatique. Consultez [README](https://github.com/auth0/Auth0.swift#configure-client-id-and-domain-programmatically) pour en savoir plus. - - - - ##### Point de contrôle - Vous avez configuré la trousse SDK Auth0.swift. Exécutez votre application afin de vérifier qu’elle ne produit pas d’erreurs liées à la trousse SDK. - -
- -
- Importez le module `Auth0` dans le fichier où vous souhaitez présenter la page de connexion. Ensuite, présentez la page Universal Login (Connexion universelle) dans l’action de votre bouton **Login (Connexion)**. - - - Vous pouvez utiliser async/await ou Combine au lieu de l’API basée sur les rappels. Consultez [README](https://github.com/auth0/Auth0.swift#web-auth-login-ios--macos) pour en savoir plus. - - - ![Un exemple d’écran de connexion universelle pour une application iOS.](/docs/images/fr-ca/cdy7uua7fh8z/3ZRDXpjlUXEcQpXq6Q00L1/f3a4616c28881bbb5a3711fcbbf1f7b1/Staff0_Login_screen_-_French.png) - - - ##### Point de contrôle - Appuyez sur le bouton **Login (Connexion)** et vérifiez que : - Une [boîte d’alerte](https://github.com/auth0/Auth0.swift#sso-alert-box-ios--macos) s’affiche demandant le consentement. - Sélectionner **Continue (Continuer)** ouvre la page de connexion universelle dans un modal Safari. - Vous pouvez vous connecter ou vous inscrire en utilisant un nom d’utilisateur et un mot de passe ou un fournisseur social. - Le modal Safari se ferme automatiquement par la suite. - -
- -
- Maintenant que vous pouvez vous connecter à votre application, vous avez besoin d’un moyen de vous [déconnecter](https://auth0.com/docs/authenticate/login/logout). Dans l’action de votre bouton **Logout (Déconnexion)**, faites usage de la méthode `clearSession()` pour effacer le témoin de session de la connexion universelle. - - - ##### Point de contrôle - Appuyez sur le bouton **Logout (Déconnexion)** et vérifiez que : - Une boîte d’alerte s’affiche demandant le consentement. - Choisir **Continue (Poursuivre)** ouvre une page dans une boîte de dialogue modale Safari. - La boîte de dialogue modale Safari se ferme automatiquement par la suite. - -
- -
- L’instance `Credentials` que vous avez obtenue après vous être connecté inclut un jeton d’ID. Le jeton d’ID contient les informations de profil associées à l’utilisateur connecté, telles que son courriel et sa photo de profil. Vous pouvez utiliser ces informations pour personnaliser l’interface utilisateur de votre application. - - La trousse SDK Auth0.swift inclut un [utilitaire](https://github.com/auth0/JWTDecode.swift) pour décoder les [JWT](https://jwt.io/), comme le jeton d’ID. Commencez par importer le module `JWTDecode` dans le fichier où vous souhaitez accéder aux informations du profil utilisateur. Ensuite, utilisez la méthode `decode(jwt:)` pour décoder le jeton d’ID et accéder aux demandes qu’il contient. - - - Vous pouvez récupérer les dernières informations utilisateur avec la méthode `userInfo(withAccessToken:)`. Consultez les [EXAMPLES (EXEMPLES)](https://github.com/auth0/Auth0.swift/blob/master/EXAMPLES.md#retrieve-user-information) pour en savoir plus. - - - - ##### Point de contrôle - Vérifiez que vous pouvez accéder à `email`, `picture`, ou à toute autre demande après vous être connecté. - -
- - ## Étapes suivantes - - Beau travail! Si vous en êtes arrivé là, vous devriez avoir la connexion, la déconnexion et les informations de profil utilisateur actives dans votre application. - - Cela conclut notre tutoriel de démarrage rapide, mais il y a tellement plus à explorer. Pour en savoir plus sur ce que vous pouvez faire avec Auth0, consultez : - - * [Auth0 Dashboard](https://manage.auth0.com/#) : apprenez à configurer et gérer votre locataire et vos applications Auth0 - * [Trousse SDK Auth0.swift](https://github.com/auth0/Auth0.swift) : explorez en détail la trousse SDK utilisée dans ce tutoriel - * [Auth0 Marketplace](https://marketplace.auth0.com/) : découvrez des intégrations que vous pouvez activer pour étendre les fonctionnalités d’Auth0 -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+--- +title: "Ajouter une connexion à votre application iOS ou macOS" +permalink: "interactive" +'description': "Ce guide explique comment intégrer Auth0 à n’importe quelle application iOS/macOS à l’aide du SDK Auth0.swift." +'og:title': "Ajouter une connexion à votre application iOS ou macOS" +'og:description': "Ce guide explique comment intégrer Auth0 à n’importe quelle application iOS/macOS à l’aide du SDK Auth0.swift." +'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/ios.png" +'twitter:title': "Ajouter une connexion à votre application iOS ou macOS" +'twitter:description': "Ce guide explique comment intégrer Auth0 à n’importe quelle application iOS/macOS à l’aide du SDK Auth0.swift." +sidebarTitle: iOS / macOS +--- + +import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; +import { LoggedInForm } from "/snippets/Login.jsx"; +import Auth0 from "/snippets/quickstart/native/ios-swift/Auth0.plist.mdx"; +import Mainview from "/snippets/quickstart/native/ios-swift/MainView.swift.mdx"; +import Mainview2 from "/snippets/quickstart/native/ios-swift/MainView.swift2.mdx"; +import Profileview from "/snippets/quickstart/native/ios-swift/ProfileView.swift.mdx"; +import User from "/snippets/quickstart/native/ios-swift/User.swift.mdx"; + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + +export const sections = [ + { id: "configuration-d-auth0", title: "Configuration d’Auth0" }, + { id: "installer-la-trousse-sdk", title: "Installer la trousse SDK" }, + { id: "configuration-de-la-trousse-sdk", title: "Configuration de la trousse SDK" }, + { id: "ajouter-une-fonctionnalité-de-connexion-à-votre-application", title: "Ajouter une fonctionnalité de connexion à votre application" }, + { id: "ajouter-une-fonctionnalité-de-déconnexion-à-votre-application", title: "Ajouter une fonctionnalité de déconnexion à votre application" }, + { id: "accéder-aux-informations-du-profil-utilisateur", title: "Accéder aux informations du profil utilisateur" } +] + + + + Ce guide explique comment ajouter l’authentification et accéder aux informations du profil utilisateur dans n’importe quelle application iOS/macOS à l’aide du SDK [Auth0.swift](https://github.com/auth0/Auth0.swift). + + Pour utiliser ce guide rapide, vous devez : + + - vous inscrire à un compte Auth0 gratuit ou vous connecter à Auth0. + - avoir une application iOS/macOS existante que vous souhaitez intégrer. Vous pouvez également consulter ou télécharger une application faisant office d’exemple lorsque vous vous connectez. + +
+ Pour utiliser les services Auth0, vous devez avoir une application configurée dans Auth0 Dashboard. L’application Auth0 est l’endroit où vous allez configurer le fonctionnement de l’authentification pour l’application que vous développez. + + ### Configurer une application Auth0 + + Utilisez le sélecteur interactif pour créer une nouvelle application Auth0 ou sélectionnez une application Auth0 **native** existante. Auth0 attribue à chaque application un ID client unique alphanumérique que votre application utilise pour appeler les API Auth0 via la trousse SDK. + + Tous les paramètres que vous configurez à l’aide de ce démarrage rapide met automatiquement à jour votre application Auth0 dans le [Dashboard](https://manage.auth0.com/#/), qui est l’endroit où vous pourrez gérer vos applications à l’avenir. + + Consultez un exemple d’application si vous préférez explorer une configuration complète. + + ### Configuration des Callback URL et des URL de déconnexion. + + Auth0 fait appel aux Callback URL et aux URL de déconnexion pour rediriger les utilisateurs vers votre application. Auth0 fait appel à une URL de rappel après avoir authentifié l’utilisateur et à une URL de déconnexion après avoir supprimé le témoin de session. Si vous ne définissez pas les Callback URL et les URL de déconnexion, les utilisateurs ne pourront pas se connecter et se déconnecter de l’application, et votre application produira une erreur. + + + Sur iOS 17.4+ et macOS 14.4+, il est possible d’utiliser des liens universels comme callback URL et URL de déconnexion. Lorsqu’activé, Auth0.swift reviendra à l’utilisation d’un schéma d’URL personnalisé sur les anciennes versions iOS/MacOS. + **Cette fonctionnalité nécessite un Xcode 15.3+ et un compte Apple Developer payant.** + + + Ajoutez les URL suivantes aux **URL de rappel** et **URL de déconnexion**, selon la plateforme de votre app. Si vous avez un domaine personnalisé, utilisez-le à la place du domaine de votre locataire Auth0. + + #### iOS + + ``` + https://{yourDomain}/ios/YOUR_BUNDLE_IDENTIFIER/callback, + YOUR_BUNDLE_IDENTIFIER://{yourDomain}/ios/YOUR_BUNDLE_IDENTIFIER/callback + ``` + + #### macOS + + ``` + https://{yourDomain}/macos/YOUR_BUNDLE_IDENTIFIER/callback, + YOUR_BUNDLE_IDENTIFIER://{yourDomain}/macos/YOUR_BUNDLE_IDENTIFIER/callback + ``` + + Par exemple, si l’identifiant de votre ensemble iOS est `com.example.MyApp` et votre domaine Auth0 est `example.us.auth0.com`, cette valeur sera alors : + + ``` + https://example.us.auth0.com/ios/com.example.MyApp/callback, + com.example.MyApp://example.us.auth0.com/ios/com.example.MyApp/callback + ``` + + ### Configurer le domaine associé + + + Cette étape nécessite un compte Apple Developer payant. Il est nécessaire d’utiliser des liens universels comme callback URL et URL de déconnexion. Ignorez cette étape pour utiliser plutôt un schéma d’URL personnalisé. + + + #### Configurer l’ID Team et l’identifiant de l’ensemble + + Allez à la [page des paramètres](https://manage.auth0.com/dashboard/us/#/applications/) de votre application Auth0, faites défiler jusqu’en bas, et ouvrez **Advanced Settings (Paramètres avancés) > (Paramètres de l’appareil)**. Dans la section **iOS**, définissez **Team ID** sur votre Apple [Apple Team ID](https://developer.apple.com/help/account/manage-your-team/locate-your-team-id/) et **App ID** sur l’identifiant de l’ensemble de votre application. + + ![Auth0 Dashboard> Applications > Applications > [Native App] > Settings tab (Onglet des paramètres) > Advanced Settings (Paramètres avancés) > Device Settings tab (Onglet des paramètres de l’appareil)](/docs/images/fr-ca/cdy7uua7fh8z/62v9bB3bUVMw9XLND5lcMI/a44aa1441c4a91d615accddb0c23ea80/IOS_Settings_-_French.png) + + Cette action ajoutera votre application au fichier `apple-app-site-association` de votre locataire Auth0. + + #### Ajouter la capacité de domaine associé + + Dans Xcode, allez à l’[onglet](https://developer.apple.com/documentation/xcode/adding-capabilities-to-your-app#Add-a-capability)**Signing and Capabilities (Signature et capacités)** des paramètres cibles de votre application, puis appuyez sur le bouton **+ Capability (Capacité)**. Sélectionnez ensuite **Associated Domains (Domaines associés)**. + + ![Xcode> Onglet Signing and Capabilities (Signature et capacités) > Add New (Ajouter nouveau) > Associated Domains (Domaines associés)](/docs/images/fr-ca/cdy7uua7fh8z/72eVE104zKB5Q4NPnx6MCa/66c81ee64f104583bd00b9916778f989/ios-xcode-capabilities.png) + + Ajoutez l’[entry](https://developer.apple.com/documentation/xcode/configuring-an-associated-domain#Define-a-service-and-its-associated-domain) suivante sous **Associated Domains (Domaines associés)** : + + ``` + webcredentials:labs-fundtraining.us.auth0.com + ``` + + Si vous avez un domaine personnalisé, utilisez-le à la place du domaine de votre locataire Auth0. + + + Pour que le domaine associé fonctionne, votre application doit être signée avec votre certificat d’équipe **même lors de la construction du simulateur iOS**. Assurez-vous d’utiliser l’équipe Apple dont l’ID d’équipe est configuré dans la page des paramètres de votre application Auth0. + +
+ +
+ ### Utilisation du gestionnaire de packages Swift + + Ouvrez l’élément de menu suivant dans Xcode : + + **File (Fichier) > Add Package Dependencies (Ajouter des dépendances de package)...** + + Dans la zone de recherche **Search or Enter Package URL (Rechercher ou saisir l’URL du package)** entrez cette URL : + + ``` + https://github.com/auth0/Auth0.swift + ``` + + Ensuite, sélectionnez la règle de dépendance et appuyez sur **Add Package (Ajouter le package)**. + + + Pour plus d’informations sur SPM consultez la [documentation officielle](https://developer.apple.com/documentation/xcode/adding-package-dependencies-to-your-app). + + + ### Utilisation de Cocoapods + + Ajoutez la ligne suivante à votre `Podfile` : + + ``` + pod 'Auth0', '~> 2.0' + ``` + + Ensuite, exécutez `pod install`. + + + Pour plus d’informations sur CocoaPods, consultez la [documentation officielle](https://guides.cocoapods.org/using/getting-started.html). + + + ### Utilisation de Carthage + + Ajoutez la ligne suivante à votre `Cartfile` : + + ``` + github "auth0/Auth0.swift" ~> 2.0 + ``` + + Ensuite, exécutez `carthage bootstrap --use-xcframeworks`. + + + Pour en savoir plus sur Carthage, consultez la [documentation officielle](https://github.com/Carthage/Carthage#getting-started). + +
+ +
+ La trousse SDK Auth0.swift a besoin de votre **domain (domaine)** Auth0 et de votre **Client ID (Identifiant client)**. Ces valeurs se trouvent dans la [page des paramètres](https://manage.auth0.com/dashboard/us/#/applications/) de votre application Auth0. + + - **domain (domaine)** : Le domaine de votre locataire Auth0. Si vous avez un domaine personnalisé, utilisez-le à la place du domaine de votre locataire Auth0. + - **Client ID (Identifiant client)** L’identifiant alphanumérique unique de l’application Auth0 que vous avez configuré précédemment dans ce démarrage rapide. + + Créez un fichier `plist` nommé `Auth0.plist` dans votre ensemble d’application contenant les valeurs du domaine Auth0 et de l’identifiant client. + + + Vous pouvez également configurer la trousse SDK de manière programmatique. Consultez [README](https://github.com/auth0/Auth0.swift#configure-client-id-and-domain-programmatically) pour en savoir plus. + + + + ##### Point de contrôle + Vous avez configuré la trousse SDK Auth0.swift. Exécutez votre application afin de vérifier qu’elle ne produit pas d’erreurs liées à la trousse SDK. + +
+ +
+ Importez le module `Auth0` dans le fichier où vous souhaitez présenter la page de connexion. Ensuite, présentez la page Universal Login (Connexion universelle) dans l’action de votre bouton **Login (Connexion)**. + + + Vous pouvez utiliser async/await ou Combine au lieu de l’API basée sur les rappels. Consultez [README](https://github.com/auth0/Auth0.swift#web-auth-login-ios--macos) pour en savoir plus. + + + ![Un exemple d’écran de connexion universelle pour une application iOS.](/docs/images/fr-ca/cdy7uua7fh8z/3ZRDXpjlUXEcQpXq6Q00L1/f3a4616c28881bbb5a3711fcbbf1f7b1/Staff0_Login_screen_-_French.png) + + + ##### Point de contrôle + Appuyez sur le bouton **Login (Connexion)** et vérifiez que : + Une [boîte d’alerte](https://github.com/auth0/Auth0.swift#sso-alert-box-ios--macos) s’affiche demandant le consentement. + Sélectionner **Continue (Continuer)** ouvre la page de connexion universelle dans un modal Safari. + Vous pouvez vous connecter ou vous inscrire en utilisant un nom d’utilisateur et un mot de passe ou un fournisseur social. + Le modal Safari se ferme automatiquement par la suite. + +
+ +
+ Maintenant que vous pouvez vous connecter à votre application, vous avez besoin d’un moyen de vous [déconnecter](https://auth0.com/docs/authenticate/login/logout). Dans l’action de votre bouton **Logout (Déconnexion)**, faites usage de la méthode `clearSession()` pour effacer le témoin de session de la connexion universelle. + + + ##### Point de contrôle + Appuyez sur le bouton **Logout (Déconnexion)** et vérifiez que : + Une boîte d’alerte s’affiche demandant le consentement. + Choisir **Continue (Poursuivre)** ouvre une page dans une boîte de dialogue modale Safari. + La boîte de dialogue modale Safari se ferme automatiquement par la suite. + +
+ +
+ L’instance `Credentials` que vous avez obtenue après vous être connecté inclut un jeton d’ID. Le jeton d’ID contient les informations de profil associées à l’utilisateur connecté, telles que son courriel et sa photo de profil. Vous pouvez utiliser ces informations pour personnaliser l’interface utilisateur de votre application. + + La trousse SDK Auth0.swift inclut un [utilitaire](https://github.com/auth0/JWTDecode.swift) pour décoder les [JWT](https://jwt.io/), comme le jeton d’ID. Commencez par importer le module `JWTDecode` dans le fichier où vous souhaitez accéder aux informations du profil utilisateur. Ensuite, utilisez la méthode `decode(jwt:)` pour décoder le jeton d’ID et accéder aux demandes qu’il contient. + + + Vous pouvez récupérer les dernières informations utilisateur avec la méthode `userInfo(withAccessToken:)`. Consultez les [EXAMPLES (EXEMPLES)](https://github.com/auth0/Auth0.swift/blob/master/EXAMPLES.md#retrieve-user-information) pour en savoir plus. + + + + ##### Point de contrôle + Vérifiez que vous pouvez accéder à `email`, `picture`, ou à toute autre demande après vous être connecté. + +
+ + ## Étapes suivantes + + Beau travail! Si vous en êtes arrivé là, vous devriez avoir la connexion, la déconnexion et les informations de profil utilisateur actives dans votre application. + + Cela conclut notre tutoriel de démarrage rapide, mais il y a tellement plus à explorer. Pour en savoir plus sur ce que vous pouvez faire avec Auth0, consultez : + + * [Auth0 Dashboard](https://manage.auth0.com/#) : apprenez à configurer et gérer votre locataire et vos applications Auth0 + * [Trousse SDK Auth0.swift](https://github.com/auth0/Auth0.swift) : explorez en détail la trousse SDK utilisée dans ce tutoriel + * [Auth0 Marketplace](https://marketplace.auth0.com/) : découvrez des intégrations que vous pouvez activer pour étendre les fonctionnalités d’Auth0 +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
diff --git a/main/docs/fr-ca/quickstart/native/net-android-ios/interactive.mdx b/main/docs/fr-ca/quickstart/native/net-android-ios/interactive.mdx index 1514803a3..d1ac4b310 100644 --- a/main/docs/fr-ca/quickstart/native/net-android-ios/interactive.mdx +++ b/main/docs/fr-ca/quickstart/native/net-android-ios/interactive.mdx @@ -1,269 +1,271 @@ ---- -title: "Ajouter une connexion à votre application .NET Android ou iOS" -permalink: "interactive" -'description': "Ce tutoriel explique comment ajouter une connexion utilisateur avec Auth0 à une application .NET Android ou iOS" -'og:title': "Ajouter une connexion à votre application .NET Android ou iOS" -'og:description': "Ce tutoriel explique comment ajouter une connexion utilisateur avec Auth0 à une application .NET Android ou iOS" -'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/xamarin.png" -'twitter:title': "Ajouter une connexion à votre application .NET Android ou iOS" -'twitter:description': "Ce tutoriel explique comment ajouter une connexion utilisateur avec Auth0 à une application .NET Android ou iOS" -sidebarTitle: .NET Android and iOS ---- - -import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; -import { LoggedInForm } from "/snippets/Login.jsx"; -import Mainactivity from "/snippets/quickstart/native/net-android-ios/MainActivity.cs.mdx"; -import Appdelegate from "/snippets/quickstart/native/net-android-ios/AppDelegate.cs.mdx"; -import Myviewcontroller from "/snippets/quickstart/native/net-android-ios/MyViewController.cs.mdx"; - -export const sections = [ - { id: "configuration-d-auth0", title: "Configuration d’Auth0" }, - { id: "installer-la-trousse-sdk-auth0", title: "Installer la trousse SDK Auth0" }, - { id: "instancier-auth0client", title: "Instancier Auth0Client" }, - { id: "configurer-android", title: "Configurer Android" }, - { id: "configurer-ios", title: "Configurer iOS" }, - { id: "ajouter-une-fonctionnalité-de-connexion-à-votre-application", title: "Ajouter une fonctionnalité de connexion à votre application" }, - { id: "ajouter-une-fonctionnalité-de-déconnexion-à-votre-application", title: "Ajouter une fonctionnalité de déconnexion à votre application" }, - { id: "afficher-les-informations-du-profil-utilisateur", title: "Afficher les informations du profil utilisateur" } -] - - - - Auth0 vous permet d’ajouter rapidement l’authentification à presque tous les types d’application. Ce guide explique comment intégrer Auth0, ajouter l’authentification et afficher les informations de profil utilisateur dans n’importe quelle application .NET Android et iOS à l’aide des SDK Auth0 pour [Android](https://www.nuget.org/packages/Auth0.OidcClient.AndroidX/) et [iOS](https://www.nuget.org/packages/Auth0.OidcClient.iOS). - - - Ce guide de démarrage couvre .NET Android et iOS, les futures générations de `Xamarin.Android` et de `Xamarin.iOS`. Si vous utilisez encore `Xamarin.Android` et `Xamarin.iOS`, vous pouvez suivre ce guide, car l’intégration est identique et les SDK sont compatibles. - - - Pour utiliser ce guide rapide, vous devez : - - - Vous inscrire à un compte Auth0 gratuit ou vous connecter à Auth0. - - Avoir un projet Android ou iOS fonctionnel utilisant .NET 6 (ou une version ultérieure) avec lequel vous souhaitez vous intégrer. Vous pouvez également consulter ou télécharger une application faisant office d’exemple lorsque vous vous connectez. - -
- Pour utiliser les services Auth0, vous devez avoir une application installée dans Auth0 Dashboard. L’application Auth0 est l’endroit où vous allez configurer le fonctionnement de l’authentification pour votre projet. - - ### Configurer une application - - Utilisez le sélecteur interactif pour créer une nouvelle application « Application native », ou sélectionnez une application existante qui représente le projet avec lequel vous souhaitez vous intégrer. Dans Auth0, il est attribué à chaque application un identifiant client unique alphanumérique que votre code d’application utilisera pour appeler les API Auth0 via la trousse SDK. - - Tous les paramètres que vous configurez à l’aide de ce démarrage rapide seront automatiquement mis à jour pour votre application dans le [Dashboard](https://manage.auth0.com/#/), qui est l’endroit où vous pourrez gérer vos applications à l’avenir. - - Si vous préférez explorer une configuration complète, consultez plutôt un exemple d’application. - - ### Configuration des URL de rappel - - Une URL de rappel est une URL intégrée dans votre application vers laquelle vous souhaitez qu’Auth0 redirige les utilisateurs après leur authentification. Si elle n’est pas définie, les utilisateurs ne seront pas redirigés vers votre application après s’être connectés. - - - Si vous suivez notre exemple de projet, définissez l’une des URL suivantes selon votre plateforme : - - **Android** : `YOUR\_PACKAGE\_NAME://{yourDomain}/android/YOUR\_PACKAGE\_NAME/callback` - - **iOS** : `YOUR\_BUNDLE\_ID://{yourDomain}/ios/YOUR\_BUNDLE\_ID/callback` - - - ### Configuration des URL de déconnexion - - Une URL de déconnexion est une URL intégrée dans votre application vers laquelle vous souhaitez qu’Auth0 redirige les utilisateurs après leur déconnexion. Si elle n’est pas définie, les utilisateurs ne pourront pas se déconnecter de votre application et recevront un message d’erreur. - - - Si vous suivez notre exemple de projet, définissez l’une des URL suivantes selon votre plateforme : - - **Android** : `YOUR\_PACKAGE\_NAME://{yourDomain}/android/YOUR\_PACKAGE\_NAME/callback` - - **iOS** : `YOUR\_BUNDLE\_ID://{yourDomain}/ios/YOUR\_BUNDLE\_ID/callback` - - - Enfin, assurez-vous que le **type d’application** pour votre application est défini sur **Native** dans les [Application Settings (Paramètres d’application)](https://manage.auth0.com/#/applications/). -
- -
- Auth0 propose une trousse SDK [Android](https://www.nuget.org/packages/Auth0.OidcClient.AndroidX/) et [iOS](https://www.nuget.org/packages/Auth0.OidcClient.iOS) pour simplifier le processus d’implémentation de l’authentification Auth0 dans les applications .NET Android et iOS. - - Utilisez le gestionnaire de packages NuGet (Tools (Outils) -> Library Package Manager (Gestionnaire de packages de bibliothèque) -> Package Manager Console (Console du gestionnaire de packages)) pour installer le package `Auth0.OidcClient.AndroidX` ou `Auth0.OidcClient.iOS`, pour développer une application Android ou iOS. - - Sinon, vous pouvez utiliser la Console du gestionnaire de packages NuGet (`Install-Package`) ou le `dotnet` CLI (`dotnet add`). - - ``` - Install-Package Auth0.OidcClient.AndroidX - Install-Package Auth0.OidcClient.iOS - ``` - - ``` - dotnet add Auth0.OidcClient.AndroidX - dotnet add Auth0.OidcClient.iOS - ``` -
- -
- Pour intégrer Auth0 dans votre application, instanciez une instance de la classe `Auth0Client` en passant une instance de `Auth0ClientOptions` qui contient votre domaine Auth0 et votre identificateur client. - - ``` - using Auth0.OidcClient; - var client = new Auth0Client(new Auth0ClientOptions { - Domain = "{yourDomain}", - ClientId = "{yourClientId}" - }, this); - ``` - - Par défaut, la trousse SDK utilisera les onglets personnalisés Chrome pour Android et ASWebAuthenticationSession pour iOS. - - - ##### Point de contrôle - Votre `Auth0Client` devrait maintenant être correctement instancié. Exécutez votre application pour vérifier que : - l’`Auth0Client` est instancié correctement dans `Activity` (Android) ou `UIViewController` (iOS) ; - votre application ne génère aucune erreur liée à Auth0. - -
- -
- Une fois un utilisateur authentifié avec succès, il est redirigé vers l’URL de rappel que vous avez configurée précédemment dans ce guide rapide. - - Pour gérer la fonction Callback sur les appareils Android, vous devez enregistrer une intention qui gère cette URL de rappel. Une façon simple de le faire est d’enregistrer l’intention sur la même activité à partir de laquelle vous avez appelé la méthode LoginAsync pour instancier le flux d’authentification. - - Assurez-vous de remplacer `YOUR_ANDROID_PACKAGE_NAME` dans l’exemple de code par le nom réel du package de votre application, comme `com.mycompany.myapplication`, et de vous assurer que tout le texte des champs `DataScheme`, `DataHostet` et `DataPathPrefix` est en majuscules. De plus, définissez `LaunchMode = LaunchMode.SingleTask` pour l’activité; sinon, le système créera une nouvelle instance de l’activité chaque fois que l’URL de rappel est appelée. - - De plus, vous devez gérer l’intention dans l’événement `OnNewIntent` dans votre classe `Activity`. Vous devez notifier le client OIDC Auth0 pour terminer le flux d’authentification en appelant la méthode `Send` du singleton `ActivityMediator`, en transmettant l’URL qui a été envoyée. - - ``` - protected override void OnNewIntent(Intent intent) - { - - base.OnNewIntent(intent); - - ActivityMediator.Instance.Send(intent.DataString); - - } - ``` -
- -
- Une fois un utilisateur authentifié avec succès, il est redirigé vers l’URL de rappel que vous avez configurée précédemment dans ce guide rapide. - - Pour gérer la callback sur les appareils iOS : - - 1. Ouvrez le fichier `Info.plist` de votre application dans Visual Studio, puis accédez à l’onglet **Advanced (Avancé)**. - 2. Sous **URL Types (Types d’URL)**, cliquez sur le bouton **Add URL Type (Ajouter le type d’URL)**. - 3. Définissez **Identifier (Identificateur)** sur Auth0, les **URL Schemes (Schémas d’URL)** identiques à Bundle Identifier**`Role (Rôle)`** - - Voici un exemple de la représentation XML de votre fichier `Info.plist` après avoir ajouté le type d’URL : - - ```html - CFBundleURLTypes - - - CFBundleTypeRole - None - CFBundleURLName - Auth0 - CFBundleURLSchemes - - YOUR_BUNDLE_IDENTIFIER - - - - ``` - - De plus, vous devez gérer l’URL de rappel dans l’événement `OpenUrl` dans votre classe `AppDelegate`. Vous devez notifier le client OIDC Auth0 pour terminer le flux d’authentification en appelant la méthode `Send` du singleton `ActivityMediator`, en transmettant l’URL qui a été envoyée. -
- -
- À présent que vous avez configuré votre application Auth0 et la trousse SDK Auth0, vous devez configurer la connexion pour votre projet. Pour ce faire, vous utiliserez la méthode `LoginAsync()` de la trousse SDK pour créer un bouton de connexion qui redirige les utilisateurs vers la page de connexion universelle Auth0. - - ```js - var loginResult = await client.LoginAsync(); - ``` - - S’il n’y a pas d’erreur, vous pouvez accéder à `User`, `IdentityToken`, `AccessToken` et `RefreshToken` dans le `LoginResult` renvoyé par `LoginAsync()`. - - - ##### Point de contrôle - Vous devez désormais pouvoir vous connecter ou vous inscrire en utilisant un nom d’utilisateur et un mot de passe. - Appuyez sur le bouton de connexion et vérifiez que : - Votre application Android ou iOS vous redirige vers la page de connexion universelle Auth0. - Vous pouvez vous connecter ou vous inscrire. - Auth0 vous redirige vers votre application. - -
- -
- Les utilisateurs qui se connectent à votre projet auront également besoin d’un moyen de se déconnecter. Créez un bouton de déconnexion en utilisant la méthode `LogoutAsync()` de la trousse SDK. Lorsque les utilisateurs se déconnectent, ils seront redirigés vers votre point de terminaison de déconnexion Auth0, qui par la suite les redirigera immédiatement vers l’URL de déconnexion que vous avez configurée précédemment dans ce démarrage rapide. - - ``` - await client.LogoutAsync(); - ``` - - - ##### Point de contrôle - Exécutez votre application et cliquez sur le bouton de déconnexion. Veuillez vérifiez que : - Votre application Android ou iOS vous redirige vers l’adresse que vous avez spécifiée comme l’une des URL de déconnexion autorisées dans les paramètres de votre application. - Vous n’êtes plus connecté à votre application. - -
- -
- Vu que vos utilisateurs peuvent désormais se connecter et se déconnecter, vous voudrez probablement pouvoir récupérer les informations de profil associées aux utilisateurs authentifiés. Par exemple, vous voudrez peut-être afficher le nom ou la photo de profil d’un utilisateur connecté dans votre projet. - - La trousse SDK Auth0 pour Android et iOS fournit des informations sur l’utilisateur via la propriété `LoginResult.User`. - - ``` - if loginResult.IsError == false { - var user = loginResult.User - var name = user.FindFirst(c => c.Type == "name")?.Value - var email = user.FindFirst(c => c.Type == "email")?.Value - var picture = user.FindFirst(c => c.Type == "picture")?.Value - } - ``` -
- - ## Étapes suivantes - - Beau travail! Si vous en êtes arrivé là, vous devriez avoir la connexion, la déconnexion et les informations de profil utilisateur actives dans votre application. - - Cela conclut notre tutoriel de démarrage rapide, mais il y a tellement plus à explorer. Pour en savoir plus sur ce que vous pouvez faire avec Auth0, consultez : - - * [Auth0 Dashboard](https://manage.auth0.com/#) : apprenez à configurer et gérer votre locataire et vos applications Auth0 - * [Trousse SDK auth0-oidc-client-net](https://github.com/auth0/auth0-oidc-client-net) : explorez en détail la trousse SDK utilisée dans ce tutoriel - * [Auth0 Marketplace](https://marketplace.auth0.com/) : découvrez des intégrations que vous pouvez activer pour étendre les fonctionnalités d’Auth0 -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+--- +title: "Ajouter une connexion à votre application .NET Android ou iOS" +permalink: "interactive" +'description': "Ce tutoriel explique comment ajouter une connexion utilisateur avec Auth0 à une application .NET Android ou iOS" +'og:title': "Ajouter une connexion à votre application .NET Android ou iOS" +'og:description': "Ce tutoriel explique comment ajouter une connexion utilisateur avec Auth0 à une application .NET Android ou iOS" +'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/xamarin.png" +'twitter:title': "Ajouter une connexion à votre application .NET Android ou iOS" +'twitter:description': "Ce tutoriel explique comment ajouter une connexion utilisateur avec Auth0 à une application .NET Android ou iOS" +sidebarTitle: .NET Android and iOS +--- + +import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; +import { LoggedInForm } from "/snippets/Login.jsx"; +import Mainactivity from "/snippets/quickstart/native/net-android-ios/MainActivity.cs.mdx"; +import Appdelegate from "/snippets/quickstart/native/net-android-ios/AppDelegate.cs.mdx"; +import Myviewcontroller from "/snippets/quickstart/native/net-android-ios/MyViewController.cs.mdx"; + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + +export const sections = [ + { id: "configuration-d-auth0", title: "Configuration d’Auth0" }, + { id: "installer-la-trousse-sdk-auth0", title: "Installer la trousse SDK Auth0" }, + { id: "instancier-auth0client", title: "Instancier Auth0Client" }, + { id: "configurer-android", title: "Configurer Android" }, + { id: "configurer-ios", title: "Configurer iOS" }, + { id: "ajouter-une-fonctionnalité-de-connexion-à-votre-application", title: "Ajouter une fonctionnalité de connexion à votre application" }, + { id: "ajouter-une-fonctionnalité-de-déconnexion-à-votre-application", title: "Ajouter une fonctionnalité de déconnexion à votre application" }, + { id: "afficher-les-informations-du-profil-utilisateur", title: "Afficher les informations du profil utilisateur" } +] + + + + Auth0 vous permet d’ajouter rapidement l’authentification à presque tous les types d’application. Ce guide explique comment intégrer Auth0, ajouter l’authentification et afficher les informations de profil utilisateur dans n’importe quelle application .NET Android et iOS à l’aide des SDK Auth0 pour [Android](https://www.nuget.org/packages/Auth0.OidcClient.AndroidX/) et [iOS](https://www.nuget.org/packages/Auth0.OidcClient.iOS). + + + Ce guide de démarrage couvre .NET Android et iOS, les futures générations de `Xamarin.Android` et de `Xamarin.iOS`. Si vous utilisez encore `Xamarin.Android` et `Xamarin.iOS`, vous pouvez suivre ce guide, car l’intégration est identique et les SDK sont compatibles. + + + Pour utiliser ce guide rapide, vous devez : + + - Vous inscrire à un compte Auth0 gratuit ou vous connecter à Auth0. + - Avoir un projet Android ou iOS fonctionnel utilisant .NET 6 (ou une version ultérieure) avec lequel vous souhaitez vous intégrer. Vous pouvez également consulter ou télécharger une application faisant office d’exemple lorsque vous vous connectez. + +
+ Pour utiliser les services Auth0, vous devez avoir une application installée dans Auth0 Dashboard. L’application Auth0 est l’endroit où vous allez configurer le fonctionnement de l’authentification pour votre projet. + + ### Configurer une application + + Utilisez le sélecteur interactif pour créer une nouvelle application « Application native », ou sélectionnez une application existante qui représente le projet avec lequel vous souhaitez vous intégrer. Dans Auth0, il est attribué à chaque application un identifiant client unique alphanumérique que votre code d’application utilisera pour appeler les API Auth0 via la trousse SDK. + + Tous les paramètres que vous configurez à l’aide de ce démarrage rapide seront automatiquement mis à jour pour votre application dans le [Dashboard](https://manage.auth0.com/#/), qui est l’endroit où vous pourrez gérer vos applications à l’avenir. + + Si vous préférez explorer une configuration complète, consultez plutôt un exemple d’application. + + ### Configuration des URL de rappel + + Une URL de rappel est une URL intégrée dans votre application vers laquelle vous souhaitez qu’Auth0 redirige les utilisateurs après leur authentification. Si elle n’est pas définie, les utilisateurs ne seront pas redirigés vers votre application après s’être connectés. + + + Si vous suivez notre exemple de projet, définissez l’une des URL suivantes selon votre plateforme : + - **Android** : `YOUR\_PACKAGE\_NAME://{yourDomain}/android/YOUR\_PACKAGE\_NAME/callback` + - **iOS** : `YOUR\_BUNDLE\_ID://{yourDomain}/ios/YOUR\_BUNDLE\_ID/callback` + + + ### Configuration des URL de déconnexion + + Une URL de déconnexion est une URL intégrée dans votre application vers laquelle vous souhaitez qu’Auth0 redirige les utilisateurs après leur déconnexion. Si elle n’est pas définie, les utilisateurs ne pourront pas se déconnecter de votre application et recevront un message d’erreur. + + + Si vous suivez notre exemple de projet, définissez l’une des URL suivantes selon votre plateforme : + - **Android** : `YOUR\_PACKAGE\_NAME://{yourDomain}/android/YOUR\_PACKAGE\_NAME/callback` + - **iOS** : `YOUR\_BUNDLE\_ID://{yourDomain}/ios/YOUR\_BUNDLE\_ID/callback` + + + Enfin, assurez-vous que le **type d’application** pour votre application est défini sur **Native** dans les [Application Settings (Paramètres d’application)](https://manage.auth0.com/#/applications/). +
+ +
+ Auth0 propose une trousse SDK [Android](https://www.nuget.org/packages/Auth0.OidcClient.AndroidX/) et [iOS](https://www.nuget.org/packages/Auth0.OidcClient.iOS) pour simplifier le processus d’implémentation de l’authentification Auth0 dans les applications .NET Android et iOS. + + Utilisez le gestionnaire de packages NuGet (Tools (Outils) -> Library Package Manager (Gestionnaire de packages de bibliothèque) -> Package Manager Console (Console du gestionnaire de packages)) pour installer le package `Auth0.OidcClient.AndroidX` ou `Auth0.OidcClient.iOS`, pour développer une application Android ou iOS. + + Sinon, vous pouvez utiliser la Console du gestionnaire de packages NuGet (`Install-Package`) ou le `dotnet` CLI (`dotnet add`). + + ``` + Install-Package Auth0.OidcClient.AndroidX + Install-Package Auth0.OidcClient.iOS + ``` + + ``` + dotnet add Auth0.OidcClient.AndroidX + dotnet add Auth0.OidcClient.iOS + ``` +
+ +
+ Pour intégrer Auth0 dans votre application, instanciez une instance de la classe `Auth0Client` en passant une instance de `Auth0ClientOptions` qui contient votre domaine Auth0 et votre identificateur client. + + ``` + using Auth0.OidcClient; + var client = new Auth0Client(new Auth0ClientOptions { + Domain = "{yourDomain}", + ClientId = "{yourClientId}" + }, this); + ``` + + Par défaut, la trousse SDK utilisera les onglets personnalisés Chrome pour Android et ASWebAuthenticationSession pour iOS. + + + ##### Point de contrôle + Votre `Auth0Client` devrait maintenant être correctement instancié. Exécutez votre application pour vérifier que : + l’`Auth0Client` est instancié correctement dans `Activity` (Android) ou `UIViewController` (iOS) ; + votre application ne génère aucune erreur liée à Auth0. + +
+ +
+ Une fois un utilisateur authentifié avec succès, il est redirigé vers l’URL de rappel que vous avez configurée précédemment dans ce guide rapide. + + Pour gérer la fonction Callback sur les appareils Android, vous devez enregistrer une intention qui gère cette URL de rappel. Une façon simple de le faire est d’enregistrer l’intention sur la même activité à partir de laquelle vous avez appelé la méthode LoginAsync pour instancier le flux d’authentification. + + Assurez-vous de remplacer `YOUR_ANDROID_PACKAGE_NAME` dans l’exemple de code par le nom réel du package de votre application, comme `com.mycompany.myapplication`, et de vous assurer que tout le texte des champs `DataScheme`, `DataHostet` et `DataPathPrefix` est en majuscules. De plus, définissez `LaunchMode = LaunchMode.SingleTask` pour l’activité; sinon, le système créera une nouvelle instance de l’activité chaque fois que l’URL de rappel est appelée. + + De plus, vous devez gérer l’intention dans l’événement `OnNewIntent` dans votre classe `Activity`. Vous devez notifier le client OIDC Auth0 pour terminer le flux d’authentification en appelant la méthode `Send` du singleton `ActivityMediator`, en transmettant l’URL qui a été envoyée. + + ``` + protected override void OnNewIntent(Intent intent) + { + + base.OnNewIntent(intent); + + ActivityMediator.Instance.Send(intent.DataString); + + } + ``` +
+ +
+ Une fois un utilisateur authentifié avec succès, il est redirigé vers l’URL de rappel que vous avez configurée précédemment dans ce guide rapide. + + Pour gérer la callback sur les appareils iOS : + + 1. Ouvrez le fichier `Info.plist` de votre application dans Visual Studio, puis accédez à l’onglet **Advanced (Avancé)**. + 2. Sous **URL Types (Types d’URL)**, cliquez sur le bouton **Add URL Type (Ajouter le type d’URL)**. + 3. Définissez **Identifier (Identificateur)** sur Auth0, les **URL Schemes (Schémas d’URL)** identiques à Bundle Identifier**`Role (Rôle)`** + + Voici un exemple de la représentation XML de votre fichier `Info.plist` après avoir ajouté le type d’URL : + + ```html + CFBundleURLTypes + + + CFBundleTypeRole + None + CFBundleURLName + Auth0 + CFBundleURLSchemes + + YOUR_BUNDLE_IDENTIFIER + + + + ``` + + De plus, vous devez gérer l’URL de rappel dans l’événement `OpenUrl` dans votre classe `AppDelegate`. Vous devez notifier le client OIDC Auth0 pour terminer le flux d’authentification en appelant la méthode `Send` du singleton `ActivityMediator`, en transmettant l’URL qui a été envoyée. +
+ +
+ À présent que vous avez configuré votre application Auth0 et la trousse SDK Auth0, vous devez configurer la connexion pour votre projet. Pour ce faire, vous utiliserez la méthode `LoginAsync()` de la trousse SDK pour créer un bouton de connexion qui redirige les utilisateurs vers la page de connexion universelle Auth0. + + ```js + var loginResult = await client.LoginAsync(); + ``` + + S’il n’y a pas d’erreur, vous pouvez accéder à `User`, `IdentityToken`, `AccessToken` et `RefreshToken` dans le `LoginResult` renvoyé par `LoginAsync()`. + + + ##### Point de contrôle + Vous devez désormais pouvoir vous connecter ou vous inscrire en utilisant un nom d’utilisateur et un mot de passe. + Appuyez sur le bouton de connexion et vérifiez que : + Votre application Android ou iOS vous redirige vers la page de connexion universelle Auth0. + Vous pouvez vous connecter ou vous inscrire. + Auth0 vous redirige vers votre application. + +
+ +
+ Les utilisateurs qui se connectent à votre projet auront également besoin d’un moyen de se déconnecter. Créez un bouton de déconnexion en utilisant la méthode `LogoutAsync()` de la trousse SDK. Lorsque les utilisateurs se déconnectent, ils seront redirigés vers votre point de terminaison de déconnexion Auth0, qui par la suite les redirigera immédiatement vers l’URL de déconnexion que vous avez configurée précédemment dans ce démarrage rapide. + + ``` + await client.LogoutAsync(); + ``` + + + ##### Point de contrôle + Exécutez votre application et cliquez sur le bouton de déconnexion. Veuillez vérifiez que : + Votre application Android ou iOS vous redirige vers l’adresse que vous avez spécifiée comme l’une des URL de déconnexion autorisées dans les paramètres de votre application. + Vous n’êtes plus connecté à votre application. + +
+ +
+ Vu que vos utilisateurs peuvent désormais se connecter et se déconnecter, vous voudrez probablement pouvoir récupérer les informations de profil associées aux utilisateurs authentifiés. Par exemple, vous voudrez peut-être afficher le nom ou la photo de profil d’un utilisateur connecté dans votre projet. + + La trousse SDK Auth0 pour Android et iOS fournit des informations sur l’utilisateur via la propriété `LoginResult.User`. + + ``` + if loginResult.IsError == false { + var user = loginResult.User + var name = user.FindFirst(c => c.Type == "name")?.Value + var email = user.FindFirst(c => c.Type == "email")?.Value + var picture = user.FindFirst(c => c.Type == "picture")?.Value + } + ``` +
+ + ## Étapes suivantes + + Beau travail! Si vous en êtes arrivé là, vous devriez avoir la connexion, la déconnexion et les informations de profil utilisateur actives dans votre application. + + Cela conclut notre tutoriel de démarrage rapide, mais il y a tellement plus à explorer. Pour en savoir plus sur ce que vous pouvez faire avec Auth0, consultez : + + * [Auth0 Dashboard](https://manage.auth0.com/#) : apprenez à configurer et gérer votre locataire et vos applications Auth0 + * [Trousse SDK auth0-oidc-client-net](https://github.com/auth0/auth0-oidc-client-net) : explorez en détail la trousse SDK utilisée dans ce tutoriel + * [Auth0 Marketplace](https://marketplace.auth0.com/) : découvrez des intégrations que vous pouvez activer pour étendre les fonctionnalités d’Auth0 +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
diff --git a/main/docs/fr-ca/quickstart/spa/angular/interactive.mdx b/main/docs/fr-ca/quickstart/spa/angular/interactive.mdx index d4a3aec2c..ba98ef79f 100644 --- a/main/docs/fr-ca/quickstart/spa/angular/interactive.mdx +++ b/main/docs/fr-ca/quickstart/spa/angular/interactive.mdx @@ -1,217 +1,220 @@ ---- -title: "Ajouter une connexion à votre application Angular" -permalink: "interactive" -'description': "Ce guide explique comment intégrer Auth0, ajouter l’authentification et afficher les informations de profil utilisateur dans n’importe quelle application Angular à l’aide de la trousse SDK Angular Auth0." -'og:title': "Ajouter une connexion à votre application Angular" -'og:description': "Ce guide explique comment intégrer Auth0, ajouter l’authentification et afficher les informations de profil utilisateur dans n’importe quelle application Angular à l’aide de la trousse SDK Angular Auth0." -'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/angular.png" -'twitter:title': "Ajouter une connexion à votre application Angular" -'twitter:description': "Ce guide explique comment intégrer Auth0, ajouter l’authentification et afficher les informations de profil utilisateur dans n’importe quelle application Angular à l’aide de la trousse SDK Angular Auth0." -sidebarTitle: Angular ---- - -import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx" -import Main from "/snippets/quickstart/spa/angular/main.mdx" -import LoginButton from "/snippets/quickstart/spa/angular/login-button.mdx" -import LogoutButton from "/snippets/quickstart/spa/angular/logout-button.mdx" -import UserProfile from "/snippets/quickstart/spa/angular/user-profile.mdx" - -export const sections = [ - { id: "configuration-d-auth0", title: "Configuration d’Auth0" }, - { id: "installer-la-trousse-sdk-react-auth0", title: "Installer la trousse SDK React Auth0" }, - { id: "enregistrer-et-fournir-auth0", title: "Enregistrer et fournir Auth0" }, - { id: "ajouter-une-fonctionnalité-de-connexion-à-votre-application", title: "Ajouter une fonctionnalité de connexion à votre application" }, - { id: "ajouter-une-fonctionnalité-de-déconnexion-à-votre-application", title: "Ajouter une fonctionnalité de déconnexion à votre application" }, - { id: "afficher-les-informations-du-profil-utilisateur", title: "Afficher les informations du profil utilisateur" } -] - - - - - Consultez le guide [Angular Authentication By Example](https://developer.auth0.com/resources/guides/spa/angular/basic-authentication) pour un examen approfondi de l’implémentation de l’authentification des utilisateurs dans Angular. Ce guide fournit des détails supplémentaires sur la façon de créer un bouton d’inscription, d’ajouter des protections de routage et d’appeler une API protégée à partir de Angular. - - - Auth0 vous permet d’ajouter rapidement l’authentification à presque tous les types d’application. Ce guide explique comment intégrer Auth0, ajouter l’authentification et afficher les informations de profil utilisateur dans n’importe quelle application Angular à l’aide de la trousse [SDK Angular Auth0](https://github.com/auth0/auth0-angular). - - Pour utiliser ce guide rapide, vous devez : - - - Vous inscrire à un compte Auth0 gratuit ou vous connecter à Auth0. - - Disposer d’un projet Angular fonctionnel avec lequel vous souhaitez vous intégrer. Vous pouvez également consulter ou télécharger une application faisant office d’exemple lorsque vous vous connectez. - -
- Pour utiliser les services Auth0, vous devez avoir une application installée dans Auth0 Dashboard. L’application Auth0 est l’endroit où vous allez configurer le fonctionnement de l’authentification pour le projet que vous développez. - - ### Configurer une application - - Utilisez le sélecteur interactif pour créer une nouvelle application Auth0 ou sélectionner une application existante qui représente le projet avec lequel vous souhaitez effectuer l’intégration. Dans Auth0, il est attribué à chaque application un identifiant client unique alphanumérique que votre code d’application utilisera pour appeler les API Auth0 via la trousse SDK. - - Tous les paramètres que vous configurez à l’aide de ce guide rapide seront automatiquement mis à jour pour votre application dans le [Dashboard](https://manage.auth0.com/#/), qui est l’endroit où vous pourrez gérer vos applications à l’avenir. - - Si vous préférez explorer une configuration complète, consultez plutôt un exemple d’application. - - ### Configuration des URL de rappel - - Une URL de rappel est une URL intégrée dans votre application vers laquelle vous souhaitez qu’Auth0 redirige les utilisateurs après leur authentification. Si elle n’est pas définie, les utilisateurs ne seront pas redirigés vers votre application après s’être connectés. - - - Si vous suivez notre projet à titre d’exemple, définissez ceci sur `http://localhost:4200`. - - - ### Configuration des URL de déconnexion - - Une URL de déconnexion est une URL intégrée dans votre application vers laquelle vous souhaitez qu’Auth0 redirige les utilisateurs après leur déconnexion Si elle n’est pas définie, les utilisateurs ne pourront pas se déconnecter de votre application et recevront un message d’erreur. - - - Si vous suivez notre projet à titre d’exemple, définissez ceci sur `http://localhost:4200`. - - - ### Configurer les origines Web autorisées - - Une origine Web autorisée est une URL que vous souhaitez autoriser à accéder à votre flux d’authentification. Elle doit contenir l’URL de votre projet. Si elle n’est pas configurée adéquatement, votre projet ne pourra pas actualiser silencieusement les jetons d’authentification, ce qui entraînera la déconnexion de vos utilisateurs lorsque prochainement ils visiteront votre application ou lors de l’actualisation d’une page. - - - Si vous suivez notre projet à titre d’exemple, définissez ceci sur `http://localhost:4200`. - -
- -
- Auth0 propose une [trousse SDK Angular](https://github.com/auth0/auth0-angular) pour simplifier le processus de mise en œuvre de l’authentification et de l’autorisation Auth0 dans les applications Angular. - - Installez la trousse SDK Angular Auth0 en exécutant les commandes suivantes dans votre terminal : - - `npm install @auth0/auth0-angular` - - La trousse SDK expose plusieurs types qui aident à intégrer Auth0 dans une application Angular, y compris un module et un service d’authentification. -
- -
- La trousse SDK exporte `provideAuth0`, qui est une fonction provide contenant tous les services nécessaires au fonctionnement de la trousse SDK. Pour l’enregistrer dans votre application : - - 1. Ouvrez le fichier `main.ts`. - 2. Importez la fonction `provideAuth0` du package `@auth0/auth0-angular`. - 3. Ajoutez `provideAuth0` à l’application en l’ajoutant aux `providers` dans `bootstrapApplication`. - 4. Injectez `AuthService` dans `AppComponent`. - - La fonction `provideAuth0` prend les propriétés `domain` et `clientId`; les valeurs de ces propriétés correspondent aux valeurs **Domain** et **Client ID** que vous pouvez trouver sous **Settings (Paramètres)** dans la Single-Page Application (Application à page unique) que vous avez enregistrée avec Auth0. En outre, nous configurons `authorizationParams.redirect_uri`, qui permet à Auth0 de rediriger l’utilisateur vers l’URL spécifique après une authentification réussie. - - - Si vous utilisez un [domaine personnalisé avec Auth0](https://auth0.com/docs/custom-domains), la valeur de la propriété de domaine est la valeur de votre domaine personnalisé au lieu de la valeur indiquée dans l’onglet « Settings (Paramètres) ». - -
- -
- À présent que vous avez configuré votre application Auth0 et la trousse SDK Angular Auth0, vous devez configurer la connexion pour votre projet. Pour ce faire, vous utiliserez la méthode `loginWithRedirect()` de la classe `AuthService` dans la trousse SDK pour rediriger les utilisateurs vers la page de connexion universelle Auth0 où Auth0 peut les authentifier. Après qu’un utilisateur se soit authentifié avec succès, il sera redirigé vers votre application et vers l’URL de rappel que vous avez configurée plus tôt dans ce guide. - - Créez un bouton de connexion dans votre application qui appelle `loginWithRedirect()` lorsqu’il est sélectionné. - - - ##### Point de contrôle - Vous devriez maintenant pouvoir vous connecter à votre application. - - Exécutez votre application et sélectionnez le bouton de connexion. Vérifiez que: - - Vous pouvez vous connecter ou vous inscrire en utilisant un nom d’utilisateur et un mot de passe. - - Votre application vous redirige vers la page [Connexion universelle Auth0](https://auth0.com/universal-login). - - Vous êtes redirigé vers Auth0 pour l’authentification. - - Auth0 redirige bien vers votre application après l’authentification. - - Vous ne recevez aucun message d’erreur dans la console lié à Auth0. - -
- -
- Les utilisateurs qui se connectent à votre projet auront également besoin d’[un moyen de se déconnecter](https://auth0.com/docs/logout/guides/logout-auth0). La trousse SDK fournit une méthode `logout()` sur la classe `AuthService` que vous pouvez utiliser pour déconnecter un utilisateur de votre application. Lorsque les utilisateurs se déconnectent, ils seront redirigés vers votre [point de terminaison de déconnexion Auth0](https://auth0.com/docs/api/authentication?javascript#logout), qui par la suite les redirigera immédiatement vers votre application et l’URL de déconnexion que vous avez configurée précédemment dans ce démarrage rapide. - - Créez un bouton de déconnexion dans votre application qui appelle `logout()` lorsqu’il est sélectionné. - - - La trousse SDK expose un observable `isAuthenticated$` sur la classe `AuthService` qui vous permet de vérifier si un utilisateur est authentifié ou non. Vous pouvez produire les boutons de connexion et de déconnexion de manière conditionnelle en fonction de la valeur de l’observable `isAuthenticated$`. Vous pouvez également utiliser un seul bouton pour combiner les boutons de connexion et de déconnexion ainsi que leur rendu conditionnel. - - - - ##### Point de contrôle - Vous devriez maintenant pouvoir vous connecter à votre application. - - Exécutez votre application, connectez-vous et sélectionnez le bouton de déconnexion. Vérifiez que: - - vous êtes redirigé vers le point de terminaison de déconnexion Auth0. - - Auth0 redirige bien vers votre application et l’URL de déconnexion correcte. - - vous n’êtes plus connecté à votre application. - - Vous ne recevez aucun message d’erreur dans la console lié à Auth0. - -
- -
- Étant donné que vos utilisateurs peuvent désormais se connecter et se déconnecter, vous voudrez probablement pouvoir récupérer les [informations de profil](https://auth0.com/docs/users/concepts/overview-user-profile) associées aux utilisateurs authentifiés. Par exemple, vous voudrez peut-être pouvoir personnaliser l’interface utilisateur en affichant le nom ou la photo de profil d’un utilisateur connecté. - - La trousse SDK Angular Auth0 fournit des informations sur les utilisateurs par l’intermédiaire de l’observable `user$` exposé par la classe `AuthService`. L’observable `user$` contenant des informations et des artefacts sensibles liés à l’identité de l’utilisateur, sa disponibilité dépend de l’état d’authentification de l’utilisateur. Heureusement, l’observable `user$` est configuré pour émettre des valeurs uniquement lorsque l’observable `isAuthenticated$` est défini sur vrai, de sorte qu’il n’est pas nécessaire de vérifier manuellement l’état de l’authentification avant d’accéder aux données du profil utilisateur. - - La trousse SDK expose également un observable `isAuthenticated$` sur la classe `AuthService` qui vous permet de vérifier si un utilisateur est authentifié ou non, ce qui vous aide à décider s’il faut afficher ou masquer des éléments de l’interface utilisateur, par exemple. - - Examinez le code `UserProfileComponent` dans le panneau interactif pour voir des exemples d’utilisation de ces fonctions. - - - ##### Point de contrôle - Vous devriez maintenant être en mesure d’afficher les informations relatives au profil utilisateur. - - Exécutez votre application et vérifiez que: - - Les informations sur l’utilisateur s’affichent correctement après la connexion. - - Les informations sur l’utilisateur ne s’affichent pas après la déconnexion. - -
- - ## Étapes suivantes - - Beau travail! Si vous en êtes arrivé là, vous devriez avoir la connexion, la déconnexion et les informations de profil utilisateur actives dans votre application. - - Cela conclut notre tutoriel de démarrage rapide, mais il y a tellement plus à explorer. Pour en savoir plus sur ce que vous pouvez faire avec Auth0, consultez : - - * [Auth0 Dashboard](https://manage.auth0.com/#) : apprenez à configurer et gérer votre locataire et vos applications Auth0 - * [Trousse SDK auth0-angular](https://github.com/auth0/auth0-angular) : explorez en détail la trousse SDK utilisée dans ce tutoriel - * [Auth0 Marketplace](https://marketplace.auth0.com/) : découvrez des intégrations que vous pouvez activer pour étendre les fonctionnalités d’Auth0 -
- - - - - - - - - - - - -
- - - - - - - - - -
- - - - - - - - -
- - - - - - - - -
- - - - - - - +--- +title: "Ajouter une connexion à votre application Angular" +permalink: "interactive" +'description': "Ce guide explique comment intégrer Auth0, ajouter l’authentification et afficher les informations de profil utilisateur dans n’importe quelle application Angular à l’aide de la trousse SDK Angular Auth0." +'og:title': "Ajouter une connexion à votre application Angular" +'og:description': "Ce guide explique comment intégrer Auth0, ajouter l’authentification et afficher les informations de profil utilisateur dans n’importe quelle application Angular à l’aide de la trousse SDK Angular Auth0." +'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/angular.png" +'twitter:title': "Ajouter une connexion à votre application Angular" +'twitter:description': "Ce guide explique comment intégrer Auth0, ajouter l’authentification et afficher les informations de profil utilisateur dans n’importe quelle application Angular à l’aide de la trousse SDK Angular Auth0." +sidebarTitle: Angular +--- + + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + +import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx" +import Main from "/snippets/quickstart/spa/angular/main.mdx" +import LoginButton from "/snippets/quickstart/spa/angular/login-button.mdx" +import LogoutButton from "/snippets/quickstart/spa/angular/logout-button.mdx" +import UserProfile from "/snippets/quickstart/spa/angular/user-profile.mdx" + +export const sections = [ + { id: "configuration-d-auth0", title: "Configuration d’Auth0" }, + { id: "installer-la-trousse-sdk-react-auth0", title: "Installer la trousse SDK React Auth0" }, + { id: "enregistrer-et-fournir-auth0", title: "Enregistrer et fournir Auth0" }, + { id: "ajouter-une-fonctionnalité-de-connexion-à-votre-application", title: "Ajouter une fonctionnalité de connexion à votre application" }, + { id: "ajouter-une-fonctionnalité-de-déconnexion-à-votre-application", title: "Ajouter une fonctionnalité de déconnexion à votre application" }, + { id: "afficher-les-informations-du-profil-utilisateur", title: "Afficher les informations du profil utilisateur" } +] + + + + + Consultez le guide [Angular Authentication By Example](https://developer.auth0.com/resources/guides/spa/angular/basic-authentication) pour un examen approfondi de l’implémentation de l’authentification des utilisateurs dans Angular. Ce guide fournit des détails supplémentaires sur la façon de créer un bouton d’inscription, d’ajouter des protections de routage et d’appeler une API protégée à partir de Angular. + + + Auth0 vous permet d’ajouter rapidement l’authentification à presque tous les types d’application. Ce guide explique comment intégrer Auth0, ajouter l’authentification et afficher les informations de profil utilisateur dans n’importe quelle application Angular à l’aide de la trousse [SDK Angular Auth0](https://github.com/auth0/auth0-angular). + + Pour utiliser ce guide rapide, vous devez : + + - Vous inscrire à un compte Auth0 gratuit ou vous connecter à Auth0. + - Disposer d’un projet Angular fonctionnel avec lequel vous souhaitez vous intégrer. Vous pouvez également consulter ou télécharger une application faisant office d’exemple lorsque vous vous connectez. + +
+ Pour utiliser les services Auth0, vous devez avoir une application installée dans Auth0 Dashboard. L’application Auth0 est l’endroit où vous allez configurer le fonctionnement de l’authentification pour le projet que vous développez. + + ### Configurer une application + + Utilisez le sélecteur interactif pour créer une nouvelle application Auth0 ou sélectionner une application existante qui représente le projet avec lequel vous souhaitez effectuer l’intégration. Dans Auth0, il est attribué à chaque application un identifiant client unique alphanumérique que votre code d’application utilisera pour appeler les API Auth0 via la trousse SDK. + + Tous les paramètres que vous configurez à l’aide de ce guide rapide seront automatiquement mis à jour pour votre application dans le [Dashboard](https://manage.auth0.com/#/), qui est l’endroit où vous pourrez gérer vos applications à l’avenir. + + Si vous préférez explorer une configuration complète, consultez plutôt un exemple d’application. + + ### Configuration des URL de rappel + + Une URL de rappel est une URL intégrée dans votre application vers laquelle vous souhaitez qu’Auth0 redirige les utilisateurs après leur authentification. Si elle n’est pas définie, les utilisateurs ne seront pas redirigés vers votre application après s’être connectés. + + + Si vous suivez notre projet à titre d’exemple, définissez ceci sur `http://localhost:4200`. + + + ### Configuration des URL de déconnexion + + Une URL de déconnexion est une URL intégrée dans votre application vers laquelle vous souhaitez qu’Auth0 redirige les utilisateurs après leur déconnexion Si elle n’est pas définie, les utilisateurs ne pourront pas se déconnecter de votre application et recevront un message d’erreur. + + + Si vous suivez notre projet à titre d’exemple, définissez ceci sur `http://localhost:4200`. + + + ### Configurer les origines Web autorisées + + Une origine Web autorisée est une URL que vous souhaitez autoriser à accéder à votre flux d’authentification. Elle doit contenir l’URL de votre projet. Si elle n’est pas configurée adéquatement, votre projet ne pourra pas actualiser silencieusement les jetons d’authentification, ce qui entraînera la déconnexion de vos utilisateurs lorsque prochainement ils visiteront votre application ou lors de l’actualisation d’une page. + + + Si vous suivez notre projet à titre d’exemple, définissez ceci sur `http://localhost:4200`. + +
+ +
+ Auth0 propose une [trousse SDK Angular](https://github.com/auth0/auth0-angular) pour simplifier le processus de mise en œuvre de l’authentification et de l’autorisation Auth0 dans les applications Angular. + + Installez la trousse SDK Angular Auth0 en exécutant les commandes suivantes dans votre terminal : + + `npm install @auth0/auth0-angular` + + La trousse SDK expose plusieurs types qui aident à intégrer Auth0 dans une application Angular, y compris un module et un service d’authentification. +
+ +
+ La trousse SDK exporte `provideAuth0`, qui est une fonction provide contenant tous les services nécessaires au fonctionnement de la trousse SDK. Pour l’enregistrer dans votre application : + + 1. Ouvrez le fichier `main.ts`. + 2. Importez la fonction `provideAuth0` du package `@auth0/auth0-angular`. + 3. Ajoutez `provideAuth0` à l’application en l’ajoutant aux `providers` dans `bootstrapApplication`. + 4. Injectez `AuthService` dans `AppComponent`. + + La fonction `provideAuth0` prend les propriétés `domain` et `clientId`; les valeurs de ces propriétés correspondent aux valeurs **Domain** et **Client ID** que vous pouvez trouver sous **Settings (Paramètres)** dans la Single-Page Application (Application à page unique) que vous avez enregistrée avec Auth0. En outre, nous configurons `authorizationParams.redirect_uri`, qui permet à Auth0 de rediriger l’utilisateur vers l’URL spécifique après une authentification réussie. + + + Si vous utilisez un [domaine personnalisé avec Auth0](https://auth0.com/docs/custom-domains), la valeur de la propriété de domaine est la valeur de votre domaine personnalisé au lieu de la valeur indiquée dans l’onglet « Settings (Paramètres) ». + +
+ +
+ À présent que vous avez configuré votre application Auth0 et la trousse SDK Angular Auth0, vous devez configurer la connexion pour votre projet. Pour ce faire, vous utiliserez la méthode `loginWithRedirect()` de la classe `AuthService` dans la trousse SDK pour rediriger les utilisateurs vers la page de connexion universelle Auth0 où Auth0 peut les authentifier. Après qu’un utilisateur se soit authentifié avec succès, il sera redirigé vers votre application et vers l’URL de rappel que vous avez configurée plus tôt dans ce guide. + + Créez un bouton de connexion dans votre application qui appelle `loginWithRedirect()` lorsqu’il est sélectionné. + + + ##### Point de contrôle + Vous devriez maintenant pouvoir vous connecter à votre application. + + Exécutez votre application et sélectionnez le bouton de connexion. Vérifiez que: + - Vous pouvez vous connecter ou vous inscrire en utilisant un nom d’utilisateur et un mot de passe. + - Votre application vous redirige vers la page [Connexion universelle Auth0](https://auth0.com/universal-login). + - Vous êtes redirigé vers Auth0 pour l’authentification. + - Auth0 redirige bien vers votre application après l’authentification. + - Vous ne recevez aucun message d’erreur dans la console lié à Auth0. + +
+ +
+ Les utilisateurs qui se connectent à votre projet auront également besoin d’[un moyen de se déconnecter](https://auth0.com/docs/logout/guides/logout-auth0). La trousse SDK fournit une méthode `logout()` sur la classe `AuthService` que vous pouvez utiliser pour déconnecter un utilisateur de votre application. Lorsque les utilisateurs se déconnectent, ils seront redirigés vers votre [point de terminaison de déconnexion Auth0](https://auth0.com/docs/api/authentication?javascript#logout), qui par la suite les redirigera immédiatement vers votre application et l’URL de déconnexion que vous avez configurée précédemment dans ce démarrage rapide. + + Créez un bouton de déconnexion dans votre application qui appelle `logout()` lorsqu’il est sélectionné. + + + La trousse SDK expose un observable `isAuthenticated$` sur la classe `AuthService` qui vous permet de vérifier si un utilisateur est authentifié ou non. Vous pouvez produire les boutons de connexion et de déconnexion de manière conditionnelle en fonction de la valeur de l’observable `isAuthenticated$`. Vous pouvez également utiliser un seul bouton pour combiner les boutons de connexion et de déconnexion ainsi que leur rendu conditionnel. + + + + ##### Point de contrôle + Vous devriez maintenant pouvoir vous connecter à votre application. + + Exécutez votre application, connectez-vous et sélectionnez le bouton de déconnexion. Vérifiez que: + - vous êtes redirigé vers le point de terminaison de déconnexion Auth0. + - Auth0 redirige bien vers votre application et l’URL de déconnexion correcte. + - vous n’êtes plus connecté à votre application. + - Vous ne recevez aucun message d’erreur dans la console lié à Auth0. + +
+ +
+ Étant donné que vos utilisateurs peuvent désormais se connecter et se déconnecter, vous voudrez probablement pouvoir récupérer les [informations de profil](https://auth0.com/docs/users/concepts/overview-user-profile) associées aux utilisateurs authentifiés. Par exemple, vous voudrez peut-être pouvoir personnaliser l’interface utilisateur en affichant le nom ou la photo de profil d’un utilisateur connecté. + + La trousse SDK Angular Auth0 fournit des informations sur les utilisateurs par l’intermédiaire de l’observable `user$` exposé par la classe `AuthService`. L’observable `user$` contenant des informations et des artefacts sensibles liés à l’identité de l’utilisateur, sa disponibilité dépend de l’état d’authentification de l’utilisateur. Heureusement, l’observable `user$` est configuré pour émettre des valeurs uniquement lorsque l’observable `isAuthenticated$` est défini sur vrai, de sorte qu’il n’est pas nécessaire de vérifier manuellement l’état de l’authentification avant d’accéder aux données du profil utilisateur. + + La trousse SDK expose également un observable `isAuthenticated$` sur la classe `AuthService` qui vous permet de vérifier si un utilisateur est authentifié ou non, ce qui vous aide à décider s’il faut afficher ou masquer des éléments de l’interface utilisateur, par exemple. + + Examinez le code `UserProfileComponent` dans le panneau interactif pour voir des exemples d’utilisation de ces fonctions. + + + ##### Point de contrôle + Vous devriez maintenant être en mesure d’afficher les informations relatives au profil utilisateur. + + Exécutez votre application et vérifiez que: + - Les informations sur l’utilisateur s’affichent correctement après la connexion. + - Les informations sur l’utilisateur ne s’affichent pas après la déconnexion. + +
+ + ## Étapes suivantes + + Beau travail! Si vous en êtes arrivé là, vous devriez avoir la connexion, la déconnexion et les informations de profil utilisateur actives dans votre application. + + Cela conclut notre tutoriel de démarrage rapide, mais il y a tellement plus à explorer. Pour en savoir plus sur ce que vous pouvez faire avec Auth0, consultez : + + * [Auth0 Dashboard](https://manage.auth0.com/#) : apprenez à configurer et gérer votre locataire et vos applications Auth0 + * [Trousse SDK auth0-angular](https://github.com/auth0/auth0-angular) : explorez en détail la trousse SDK utilisée dans ce tutoriel + * [Auth0 Marketplace](https://marketplace.auth0.com/) : découvrez des intégrations que vous pouvez activer pour étendre les fonctionnalités d’Auth0 +
+ + + + + + + + + + + + +
+ + + + + + + + + +
+ + + + + + + + +
+ + + + + + + + +
+ + + + + + + diff --git a/main/docs/fr-ca/quickstart/spa/flutter/interactive.mdx b/main/docs/fr-ca/quickstart/spa/flutter/interactive.mdx index aa015d226..cb12f51e7 100644 --- a/main/docs/fr-ca/quickstart/spa/flutter/interactive.mdx +++ b/main/docs/fr-ca/quickstart/spa/flutter/interactive.mdx @@ -1,186 +1,189 @@ ---- -title: "Ajouter une fonctionnalité de connexion à votre application Flutter" -permalink: "interactive" -'description': "Ce guide explique comment intégrer Auth0 à une application Flutter à l’aide de la trousse SDK Auth0 Flutter." -'og:title': "Ajouter une fonctionnalité de connexion à votre application Flutter" -'og:description': "Ce guide explique comment intégrer Auth0 à une application Flutter à l’aide de la trousse SDK Auth0 Flutter." -'og:image': "https://cdn2.auth0.com/docs/1.14567.0/img/share-image.png" -'twitter:title': "Ajouter une fonctionnalité de connexion à votre application Flutter" -'twitter:description': "Ce guide explique comment intégrer Auth0 à une application Flutter à l’aide de la trousse SDK Auth0 Flutter." -sidebarTitle: Flutter ---- - -import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx" -import MainView from "/snippets/quickstart/spa/flutter/main_view.mdx" -import ProfileView from "/snippets/quickstart/spa/flutter/profile_view.mdx" - -export const sections = [ - { id: "configuration-d-auth0", title: "Configuration d’Auth0" }, - { id: "installer-la-trousse-sdk-flutter-auth0", title: "Installer la trousse SDK Flutter Auth0" }, - { id: "ajouter-une-fonctionnalité-de-connexion-à-votre-application", title: "Ajouter une fonctionnalité de connexion à votre application" }, - { id: "ajouter-une-fonctionnalité-de-déconnexion-à-votre-application", title: "Ajouter une fonctionnalité de déconnexion à votre application" }, - { id: "afficher-les-informations-du-profil-utilisateur", title: "Afficher les informations du profil utilisateur" } -] - - - - Auth0 vous permet d’ajouter rapidement l’authentification et d’accéder aux informations relatives au profil de l’utilisateur dans votre application. Ce guide explique comment intégrer Auth0 à une application Flutter à l’aide de la trousse [SDK Auth0 Flutter](https://github.com/auth0/auth0-flutter). - - - La trousse SDK Flutter ne prend actuellement en charge que les applications Flutter s’exécutant sur les plateformes Android, iOS ou Web. - - - Ce guide rapide suppose que vous avez déjà une application [Flutter](https://flutter.dev/) installée et active. Si ce n’est pas le cas, consultez les [guides de démarrage de Flutter](https://docs.flutter.dev/get-started/install) pour commencer l’utilisation d’une application simple. - - Vous devez également être familiarisé avec l’[outil de ligne de commande Flutter](https://docs.flutter.dev/reference/flutter-cli). - -
- Lorsque vous vous êtes inscrit à Auth0, une nouvelle application a été créée pour vous, ou vous auriez pu en créer une nouvelle. Vous aurez besoin de quelques informations à propos de cette application pour communiquer avec Auth0. Vous pouvez obtenir ces informations dans la section [Paramètres d’application](https://manage.auth0.com/#/applications) d’Auth0 Dashboard. - - ![null](/docs/images/fr-ca/cdy7uua7fh8z/6SC7KnyzCyO8cwXQfril1X/7f204d6b4eb87562043e7f1083aca651/My_App_-_Settings_-_French.png) - - - Si vous utilisez l’application par défaut avec une application native ou une application à page unique, veillez à mettre à jour la **méthode d’authentification du point de terminaison des jetons** en la réglant sur `None` et à définir le **type d’application** sur `SPA` ou `Native`. - - - Les informations suivantes sont nécessaires : - - - **Domaine** - - **Identifiant client** - - - Si vous téléchargez l’exemple en haut de cette page, les détails sont renseignés pour vous. - - - ### Configuration des URL de rappel - - Une URL de rappel est une URL intégrée dans votre application vers laquelle Auth0 redirige l’utilisateur après qu’il s’est authentifié. L’URL de rappel de votre application doit être ajoutée au champ **URL de rappel autorisées** dans les [Paramètres d’application](https://manage.auth0.com/#/applications). Si ce champ n’est pas défini, les utilisateurs ne pourront pas se connecter à l’application et obtiendront un message d’erreur. - - - Si vous suivez l’exemple de projet que vous avez téléchargé en haut de cette page, vous devez définir l’**URL de rappel autorisée** sur `http://localhost:3000`. - - - ### Configuration des URL de déconnexion - - Une URL de déconnexion est une URL intégrée dans votre application vers laquelle Auth0 peut se rediriger une fois que l’utilisateur a été déconnecté du serveur d’autorisations. Cette URL est spécifiée dans le paramètre de requête `returnTo`. L’URL de déconnexion de votre application doit être ajoutée au champ **URL de déconnexions autorisées** dans les [Application Settings (Paramètres d’application)](https://manage.auth0.com/#/applications). Si ce champ n’est pas défini, les utilisateurs ne pourront pas se déconnecter de l’application et obtiendront un message d’erreur. - - - Si vous suivez l’exemple de projet que vous avez téléchargé en haut de cette page, l’URL de déconnexion que vous devez ajouter au champ **URL de déconnexions autorisées** est `http://localhost:3000`. - - - ### Configurer les origines Web autorisées - - Vous devez ajouter l’URL de votre application au champ **Origines Web autorisées** dans vos [Application Settings (Paramètres d’application)](https://manage.auth0.com/#/applications/%7ByourClientId%7D/settings). Si vous n’enregistrez pas l’URL de votre application ici, l’application ne pourra pas actualiser silencieusement les jetons d’authentification et vos utilisateurs seront déconnectés la prochaine fois qu’ils visiteront l’application ou qu’ils actualiseront la page. - - - Si vous suivez l’exemple de projet que vous avez téléchargé en haut de cette page, vous devez définir l’option **Origines Web autorisées** sur `http://localhost:3000`. - -
- -
- Ajoutez la trousse SDK Flutter Auth0 au projet : - - ``` - flutter pub add auth0_flutter - ``` - - Ajoutez l’étiquette de script suivante à votre page `index.html` : - - ```html - - ``` -
- -
- La [connexion universelle](https://auth0.com/docs/authenticate/login/auth0-universal-login) est le moyen le plus simple de mettre en place l’authentification dans votre application. Nous recommandons de l’utiliser pour une meilleure expérience, une meilleure sécurité et un plus grand nombre de fonctionnalités. - - Intégrez la connexion universelle Auth0 dans votre application Flutter (Web) en utilisant la classe `Auth0Web`. Redirigez vos utilisateurs vers la page de connexion universelle Auth0 en utilisant `loginWithRedirect()`. - - - Vous devrez normalement définir le paramètre `redirectUrl` sur `loginWithRedirect`. Si ce paramètre n’est pas spécifié, Auth0 utilisera la [route de connexion par défaut](https://auth0.com/docs/authenticate/login/auth0-universal-login/configure-default-login-routes), qui n’est pas configurée par défaut. - - - Lorsqu’un utilisateur se connecte, il est redirigé vers votre application. Vous pouvez alors accéder à l’identificateur et aux jetons d’accès de cet utilisateur en appelant `onLoad` lors du démarrage et en gérant les informations d’identification qui vous sont communiquées : - - ``` - auth0.onLoad().then((final credentials) => setState(() { - // Handle or store credentials here - - _credentials = credentials; - - })); - ``` - - - ##### Point de contrôle - Ajoutez un bouton à votre application qui appelle `loginWithRedirect()` et déconnecte l’utilisateur de votre application. Vérifiez que vous êtes redirigé vers Auth0 pour l’authentification, puis renvoyé vers votre application. - Vérifiez que vous pouvez accéder aux `credentials` après avoir appelé `onLoad` et que vous pouvez accéder à l’identifiant et aux jetons d’accès. - -
- -
- Pour déconnecter les utilisateurs, redirigez-les vers le point de terminaison Auth0 pour effacer leur session de connexion en appelant la trousse SDK Flutter Auth0 `logout()`. [En savoir plus sur la déconnexion d’Auth0](https://auth0.com/docs/authenticate/login/logout). - - - Vous devez normalement spécifier `returnToUrl` lorsque vous appelez `logout`, sinon Auth0 [utilisera par défaut la première URL de la liste URL de déconnexion autorisées](https://auth0.com/docs/authenticate/login/logout/redirect-users-after-logout). - - - - ##### Point de contrôle - Ajoutez un bouton à votre application qui appelle `logout()` et déconnecte l’utilisateur de votre application. Lorsque vous le sélectionnez, vérifiez que votre application Flutter vous redirige vers le point de terminaison de déconnexion et vice-versa. Vous ne devriez pas être connecté à votre application. - -
- -
- Le profil utilisateur récupère automatiquement les propriétés du profil utilisateur lors du chargement de la page. Il est possible d’y accéder et de les stocker en appelant `onLoad` lors du démarrage de l’application. L’objet retourné à partir de `onLoad` contient une propriété `user` avec toutes les propriétés du profil utilisateur. Cette propriété est alimentée en interne par le décodage du jeton d’ID. - - - ##### Point de contrôle - Connectez-vous et inspectez la propriété `user` par rapport au résultat. Vérifiez les informations de profil utilisateur actuel, telles que son `email` ou `name`. - -
- - ## Étapes suivantes - - Beau travail! Si vous en êtes arrivé là, vous devriez avoir la connexion, la déconnexion et les informations de profil utilisateur actives dans votre application. - - Cela conclut notre tutoriel de démarrage rapide, mais il y a tellement plus à explorer. Pour en savoir plus sur ce que vous pouvez faire avec Auth0, consultez : - - * [Auth0 Dashboard](https://manage.auth0.com/#) : apprenez à configurer et gérer votre locataire et vos applications Auth0 - * [Trousse SDK auth0-flutter](https://www.github.com/auth0/auth0-flutter/) : explorez en détail la trousse SDK utilisée dans ce tutoriel - * [Auth0 Marketplace](https://marketplace.auth0.com/) : découvrez des intégrations que vous pouvez activer pour étendre les fonctionnalités d’Auth0 - * [Configure other identity providers](/docs/identityproviders) - * [Enable multifactor authentication](/docs/multifactor-authentication) - * [Learn about attack protection](/docs/attack-protection) - * [Learn about Actions](/docs/customize/actions) -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+--- +title: "Ajouter une fonctionnalité de connexion à votre application Flutter" +permalink: "interactive" +'description': "Ce guide explique comment intégrer Auth0 à une application Flutter à l’aide de la trousse SDK Auth0 Flutter." +'og:title': "Ajouter une fonctionnalité de connexion à votre application Flutter" +'og:description': "Ce guide explique comment intégrer Auth0 à une application Flutter à l’aide de la trousse SDK Auth0 Flutter." +'og:image': "https://cdn2.auth0.com/docs/1.14567.0/img/share-image.png" +'twitter:title': "Ajouter une fonctionnalité de connexion à votre application Flutter" +'twitter:description': "Ce guide explique comment intégrer Auth0 à une application Flutter à l’aide de la trousse SDK Auth0 Flutter." +sidebarTitle: Flutter +--- + + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + +import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx" +import MainView from "/snippets/quickstart/spa/flutter/main_view.mdx" +import ProfileView from "/snippets/quickstart/spa/flutter/profile_view.mdx" + +export const sections = [ + { id: "configuration-d-auth0", title: "Configuration d’Auth0" }, + { id: "installer-la-trousse-sdk-flutter-auth0", title: "Installer la trousse SDK Flutter Auth0" }, + { id: "ajouter-une-fonctionnalité-de-connexion-à-votre-application", title: "Ajouter une fonctionnalité de connexion à votre application" }, + { id: "ajouter-une-fonctionnalité-de-déconnexion-à-votre-application", title: "Ajouter une fonctionnalité de déconnexion à votre application" }, + { id: "afficher-les-informations-du-profil-utilisateur", title: "Afficher les informations du profil utilisateur" } +] + + + + Auth0 vous permet d’ajouter rapidement l’authentification et d’accéder aux informations relatives au profil de l’utilisateur dans votre application. Ce guide explique comment intégrer Auth0 à une application Flutter à l’aide de la trousse [SDK Auth0 Flutter](https://github.com/auth0/auth0-flutter). + + + La trousse SDK Flutter ne prend actuellement en charge que les applications Flutter s’exécutant sur les plateformes Android, iOS ou Web. + + + Ce guide rapide suppose que vous avez déjà une application [Flutter](https://flutter.dev/) installée et active. Si ce n’est pas le cas, consultez les [guides de démarrage de Flutter](https://docs.flutter.dev/get-started/install) pour commencer l’utilisation d’une application simple. + + Vous devez également être familiarisé avec l’[outil de ligne de commande Flutter](https://docs.flutter.dev/reference/flutter-cli). + +
+ Lorsque vous vous êtes inscrit à Auth0, une nouvelle application a été créée pour vous, ou vous auriez pu en créer une nouvelle. Vous aurez besoin de quelques informations à propos de cette application pour communiquer avec Auth0. Vous pouvez obtenir ces informations dans la section [Paramètres d’application](https://manage.auth0.com/#/applications) d’Auth0 Dashboard. + + ![null](/docs/images/fr-ca/cdy7uua7fh8z/6SC7KnyzCyO8cwXQfril1X/7f204d6b4eb87562043e7f1083aca651/My_App_-_Settings_-_French.png) + + + Si vous utilisez l’application par défaut avec une application native ou une application à page unique, veillez à mettre à jour la **méthode d’authentification du point de terminaison des jetons** en la réglant sur `None` et à définir le **type d’application** sur `SPA` ou `Native`. + + + Les informations suivantes sont nécessaires : + + - **Domaine** + - **Identifiant client** + + + Si vous téléchargez l’exemple en haut de cette page, les détails sont renseignés pour vous. + + + ### Configuration des URL de rappel + + Une URL de rappel est une URL intégrée dans votre application vers laquelle Auth0 redirige l’utilisateur après qu’il s’est authentifié. L’URL de rappel de votre application doit être ajoutée au champ **URL de rappel autorisées** dans les [Paramètres d’application](https://manage.auth0.com/#/applications). Si ce champ n’est pas défini, les utilisateurs ne pourront pas se connecter à l’application et obtiendront un message d’erreur. + + + Si vous suivez l’exemple de projet que vous avez téléchargé en haut de cette page, vous devez définir l’**URL de rappel autorisée** sur `http://localhost:3000`. + + + ### Configuration des URL de déconnexion + + Une URL de déconnexion est une URL intégrée dans votre application vers laquelle Auth0 peut se rediriger une fois que l’utilisateur a été déconnecté du serveur d’autorisations. Cette URL est spécifiée dans le paramètre de requête `returnTo`. L’URL de déconnexion de votre application doit être ajoutée au champ **URL de déconnexions autorisées** dans les [Application Settings (Paramètres d’application)](https://manage.auth0.com/#/applications). Si ce champ n’est pas défini, les utilisateurs ne pourront pas se déconnecter de l’application et obtiendront un message d’erreur. + + + Si vous suivez l’exemple de projet que vous avez téléchargé en haut de cette page, l’URL de déconnexion que vous devez ajouter au champ **URL de déconnexions autorisées** est `http://localhost:3000`. + + + ### Configurer les origines Web autorisées + + Vous devez ajouter l’URL de votre application au champ **Origines Web autorisées** dans vos [Application Settings (Paramètres d’application)](https://manage.auth0.com/#/applications/%7ByourClientId%7D/settings). Si vous n’enregistrez pas l’URL de votre application ici, l’application ne pourra pas actualiser silencieusement les jetons d’authentification et vos utilisateurs seront déconnectés la prochaine fois qu’ils visiteront l’application ou qu’ils actualiseront la page. + + + Si vous suivez l’exemple de projet que vous avez téléchargé en haut de cette page, vous devez définir l’option **Origines Web autorisées** sur `http://localhost:3000`. + +
+ +
+ Ajoutez la trousse SDK Flutter Auth0 au projet : + + ``` + flutter pub add auth0_flutter + ``` + + Ajoutez l’étiquette de script suivante à votre page `index.html` : + + ```html + + ``` +
+ +
+ La [connexion universelle](https://auth0.com/docs/authenticate/login/auth0-universal-login) est le moyen le plus simple de mettre en place l’authentification dans votre application. Nous recommandons de l’utiliser pour une meilleure expérience, une meilleure sécurité et un plus grand nombre de fonctionnalités. + + Intégrez la connexion universelle Auth0 dans votre application Flutter (Web) en utilisant la classe `Auth0Web`. Redirigez vos utilisateurs vers la page de connexion universelle Auth0 en utilisant `loginWithRedirect()`. + + + Vous devrez normalement définir le paramètre `redirectUrl` sur `loginWithRedirect`. Si ce paramètre n’est pas spécifié, Auth0 utilisera la [route de connexion par défaut](https://auth0.com/docs/authenticate/login/auth0-universal-login/configure-default-login-routes), qui n’est pas configurée par défaut. + + + Lorsqu’un utilisateur se connecte, il est redirigé vers votre application. Vous pouvez alors accéder à l’identificateur et aux jetons d’accès de cet utilisateur en appelant `onLoad` lors du démarrage et en gérant les informations d’identification qui vous sont communiquées : + + ``` + auth0.onLoad().then((final credentials) => setState(() { + // Handle or store credentials here + + _credentials = credentials; + + })); + ``` + + + ##### Point de contrôle + Ajoutez un bouton à votre application qui appelle `loginWithRedirect()` et déconnecte l’utilisateur de votre application. Vérifiez que vous êtes redirigé vers Auth0 pour l’authentification, puis renvoyé vers votre application. + Vérifiez que vous pouvez accéder aux `credentials` après avoir appelé `onLoad` et que vous pouvez accéder à l’identifiant et aux jetons d’accès. + +
+ +
+ Pour déconnecter les utilisateurs, redirigez-les vers le point de terminaison Auth0 pour effacer leur session de connexion en appelant la trousse SDK Flutter Auth0 `logout()`. [En savoir plus sur la déconnexion d’Auth0](https://auth0.com/docs/authenticate/login/logout). + + + Vous devez normalement spécifier `returnToUrl` lorsque vous appelez `logout`, sinon Auth0 [utilisera par défaut la première URL de la liste URL de déconnexion autorisées](https://auth0.com/docs/authenticate/login/logout/redirect-users-after-logout). + + + + ##### Point de contrôle + Ajoutez un bouton à votre application qui appelle `logout()` et déconnecte l’utilisateur de votre application. Lorsque vous le sélectionnez, vérifiez que votre application Flutter vous redirige vers le point de terminaison de déconnexion et vice-versa. Vous ne devriez pas être connecté à votre application. + +
+ +
+ Le profil utilisateur récupère automatiquement les propriétés du profil utilisateur lors du chargement de la page. Il est possible d’y accéder et de les stocker en appelant `onLoad` lors du démarrage de l’application. L’objet retourné à partir de `onLoad` contient une propriété `user` avec toutes les propriétés du profil utilisateur. Cette propriété est alimentée en interne par le décodage du jeton d’ID. + + + ##### Point de contrôle + Connectez-vous et inspectez la propriété `user` par rapport au résultat. Vérifiez les informations de profil utilisateur actuel, telles que son `email` ou `name`. + +
+ + ## Étapes suivantes + + Beau travail! Si vous en êtes arrivé là, vous devriez avoir la connexion, la déconnexion et les informations de profil utilisateur actives dans votre application. + + Cela conclut notre tutoriel de démarrage rapide, mais il y a tellement plus à explorer. Pour en savoir plus sur ce que vous pouvez faire avec Auth0, consultez : + + * [Auth0 Dashboard](https://manage.auth0.com/#) : apprenez à configurer et gérer votre locataire et vos applications Auth0 + * [Trousse SDK auth0-flutter](https://www.github.com/auth0/auth0-flutter/) : explorez en détail la trousse SDK utilisée dans ce tutoriel + * [Auth0 Marketplace](https://marketplace.auth0.com/) : découvrez des intégrations que vous pouvez activer pour étendre les fonctionnalités d’Auth0 + * [Configure other identity providers](/docs/identityproviders) + * [Enable multifactor authentication](/docs/multifactor-authentication) + * [Learn about attack protection](/docs/attack-protection) + * [Learn about Actions](/docs/customize/actions) +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
diff --git a/main/docs/fr-ca/quickstart/spa/react/interactive.mdx b/main/docs/fr-ca/quickstart/spa/react/interactive.mdx index 53b08501d..818e28cc1 100644 --- a/main/docs/fr-ca/quickstart/spa/react/interactive.mdx +++ b/main/docs/fr-ca/quickstart/spa/react/interactive.mdx @@ -1,208 +1,210 @@ ---- -title: "Ajouter une fonctionnalité de connexion à votre application React" -permalink: "interactive" -'description': "Ce guide explique comment intégrer Auth0 à n’importe quelle application React, nouvelle ou ancienne, à l’aide du SDK React Auth0." -'og:title': "Ajouter une fonctionnalité de connexion à votre application React" -'og:description': "Ce guide explique comment intégrer Auth0 à n’importe quelle application React, nouvelle ou ancienne, à l’aide du SDK React Auth0." -'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/react.png" -'twitter:title': "Ajouter une fonctionnalité de connexion à votre application React" -'twitter:description': "Ce guide explique comment intégrer Auth0 à n’importe quelle application React, nouvelle ou ancienne, à l’aide du SDK React Auth0." -sidebarTitle: React ---- - -import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; -import { LoggedInForm } from "/snippets/Login.jsx"; -import Index from "/snippets/quickstart/spa/react/index.mdx"; -import Login from "/snippets/quickstart/spa/react/login.mdx"; -import Logout from "/snippets/quickstart/spa/react/logout.mdx"; -import Profile from "/snippets/quickstart/spa/react/profile.mdx"; - -export const sections = [ - { id: "configuration-d-auth0", title: "Configuration d’Auth0" }, - { id: "installer-la-trousse-sdk-auth0-react", title: "Installer la trousse SDK Auth0 React" }, - { id: "ajouter-une-fonctionnalité-de-connexion-à-votre-application", title: "Ajouter une fonctionnalité de connexion à votre application" }, - { id: "ajouter-une-fonctionnalité-de-déconnexion-à-votre-application", title: "Ajouter une fonctionnalité de déconnexion à votre application" }, - { id: "afficher-les-informations-du-profil-utilisateur", title: "Afficher les informations du profil utilisateur" } -] - - - - Auth0 vous permet d’ajouter rapidement l’authentification à presque tous les types d’application. Ce guide explique comment intégrer Auth0, ajouter l’authentification et afficher les informations de profil utilisateur dans n’importe quelle application React à l’aide du SDK React Auth0. - - Pour utiliser ce guide rapide, vous devez : - - - Vous inscrire à un compte Auth0 gratuit ou vous connecter à Auth0. - - Disposer d’un projet React fonctionnel avec lequel vous souhaitez vous intégrer. Vous pouvez également consulter ou télécharger une application faisant office d’exemple lorsque vous vous connectez. - - - Consultez le guide [React Authentication By Example (Authentification React par l’exemple)](https://developer.auth0.com/resources/guides/spa/react/basic-authentication) pour un examen approfondi de l’implémentation de l’authentification des utilisateurs dans React. Ce guide fournit des détails supplémentaires sur la façon de créer un bouton d’inscription, d’ajouter des protections de routage en utilisant React Router, et d’appeler une API protégée à partir de React. - - -
- Pour utiliser les services Auth0, vous devez avoir une application installée dans Auth0 Dashboard. L’application Auth0 est l’endroit où vous allez configurer le fonctionnement de l’authentification pour le projet que vous développez. - - ### Configurer une application - - Utilisez le sélecteur interactif pour créer une nouvelle application Auth0 ou sélectionner une application existante qui représente le projet avec lequel vous souhaitez effectuer l’intégration. Dans Auth0, il est attribué à chaque application un identifiant client unique alphanumérique que votre code d’application utilisera pour appeler les API Auth0 via la trousse SDK. - - Tous les paramètres que vous configurez à l’aide de ce guide rapide seront automatiquement mis à jour pour votre application dans le [Dashboard](https://manage.auth0.com/#/), qui est l’endroit où vous pourrez gérer vos applications à l’avenir. - - Si vous préférez explorer une configuration complète, consultez plutôt un exemple d’application. - - ### Configuration des URL de rappel - - Une URL de rappel est une URL intégrée dans votre application vers laquelle vous souhaitez qu’Auth0 redirige les utilisateurs après leur authentification. Si elle n’est pas définie, les utilisateurs ne seront pas redirigés vers votre application après s’être connectés. - - - Si vous suivez notre exemple de projet, définissez cette URL comme suit : `http://localhost:3000`. - - - ### Configuration des URL de déconnexion - - Une URL de déconnexion est une URL intégrée dans votre application vers laquelle vous souhaitez qu’Auth0 redirige les utilisateurs après leur déconnexion. Si elle n’est pas définie, les utilisateurs ne pourront pas se déconnecter de votre application et recevront un message d’erreur. - - - Si vous suivez notre exemple de projet, définissez cette URL comme suit : `http://localhost:3000`. - - - ### Configurer les origines Web autorisées - - Une origine Web autorisée est une URL que vous souhaitez autoriser à accéder à votre flux d’authentification. Elle doit contenir l’URL de votre projet. Si elle n’est pas configurée adéquatement, votre projet ne pourra pas actualiser silencieusement les jetons d’authentification, ce qui entraînera la déconnexion de vos utilisateurs lorsque prochainement ils visiteront votre application ou lors de l’actualisation d’une page. - - - Si vous suivez notre exemple de projet, définissez cette URL comme suit : `http://localhost:3000`. - -
- -
- Auth0 propose une [trousse SDK React](https://github.com/auth0/auth0-react) (auth0-react.js) pour simplifier le processus de mise en œuvre de l’authentification et de l’autorisation Auth0 dans les applications React. - - Installez la trousse SDK React Auth0 en exécutant les commandes suivantes dans votre terminal : - - ``` - cd - npm install @auth0/auth0-react - ``` - - ### Configurer le composant Auth0Provider - - Pour que la trousse SDK fonctionne adéquatement, définissez les propriétés suivantes dans le composant Auth0Provider : - - - `domain`: Le domaine de votre locataire Auth0. En général, il figure dans Auth0 Dashboard dans vos paramètres d’application dans le champ Domaine. Si vous utilisez un [domaine personnalisé](https://auth0.com/docs/custom-domains), définissez-le plutôt sur la valeur de votre domaine personnalisé. - - `clientId`: L’identifiant de l’application Auth0 que vous avez configuré précédemment dans ce guide rapide. Il se trouve sur Auth0 Dashboard, dans la section Paramètres de l’application, dans le champ Identifiant client. - - `authorizationParams.redirect_uri`: L’URL dans votre application vers laquelle vous souhaitez qu’Auth0 redirige les utilisateurs après leur authentification. Cela correspond à l’URL de rappel que vous avez configurée précédemment dans ce guide de démarrage rapide. Cette valeur se trouve également dans Auth0 Dashboard, dans les paramètres de votre application, dans le champ URL de rappel. Assurez-vous que les informations que vous saisissez dans votre code correspondent à celles qui ont été configurées précédemment. Dans le cas contraire, vos utilisateurs verront un message d’erreur. - - - ##### Point de contrôle - Votre composant Auth0Provider devrait maintenant être correctement configuré. Exécutez votre application pour vérifier que: - - la trousse SDK s’initialise correctement, - - votre application ne génère aucune erreur liée à Auth0. - -
- -
- À présent que vous avez configuré votre application Auth0 et la trousse SDK Auth0 React, vous devez configurer la connexion pour votre projet. Pour ce faire, vous utiliserez la méthode loginWithRedirect() de la trousse SDK pour créer un bouton de connexion qui redirige les utilisateurs vers la page de connexion universelle Auth0. Une fois un utilisateur authentifié avec succès, il est redirigé vers l’URL de rappel que vous avez configurée précédemment dans ce Démarrage rapide. - - - Ce guide se concentre sur l’utilisation du hook React personnalisé `useAuth0()`. Si vous utilisez des composants de classe, consultez [le composant de niveau supérieur`withAuth0()`](https://github.com/auth0/auth0-react/blob/master/EXAMPLES.md#use-with-a-class-component). - - - Créez un nouveau fichier dans votre application appelé `login.js` pour le composant du bouton de connexion, et copiez le code du panneau interactif à droite, qui contient la logique nécessaire à la connexion. Ensuite, mettez à jour votre fichier `index.js` pour y intégrer le nouveau bouton de connexion. - - - ##### Point de contrôle - Vous devez désormais pouvoir vous connecter ou vous inscrire en utilisant un nom d’utilisateur et un mot de passe. - - Appuyez sur le bouton de connexion et vérifiez que: - - Votre application React vous redirige vers la page de connexion universelle Auth0. - - Vous pouvez vous connecter ou vous inscrire. - - Auth0 vous redirige vers votre application en utilisant la valeur `authorizationParams.redirect\_uri` que vous avez utilisée pour configurer `Auth0Provider.`. - -
- -
- Les utilisateurs qui se connectent à votre projet auront également besoin d’un moyen de se déconnecter. Créez un bouton de déconnexion en utilisant la méthode Logout() de la trousse SDK. Lorsque les utilisateurs se déconnecteront, ils seront redirigés vers votre point de terminaison [Auth0 logout](https://auth0.com/docs/api/authentication?javascript#logout) qui par la suite les redirigera immédiatement vers l’URL de déconnexion que vous avez configurée précédemment dans ce guide de démarrage rapide. - - Créez un nouveau fichier dans votre application appelé `logout.js` pour le composant du bouton de déconnexion, et copiez le code du panneau interactif, qui contient la logique nécessaire à la déconnexion. Ensuite, mettez à jour votre fichier `index.js` pour y intégrer le nouveau bouton de déconnexion. - - - ##### Point de contrôle - Exécutez votre application et cliquez sur le bouton de déconnexion, vérifiez que: - - Votre application React vous redirige vers l’adresse que vous avez précisée comme l’une des URL de déconnexion autorisées dans les paramètres de votre application. - - Vous n’êtes plus connecté à votre application. - -
- -
- Vu que vos utilisateurs peuvent désormais se connecter et se déconnecter, vous voudrez probablement pouvoir récupérer les [informations de profil](https://auth0.com/docs/users/concepts/overview-user-profile) associées aux utilisateurs authentifiés. Par exemple, vous voudrez peut-être pouvoir afficher le nom ou la photo de profil d’un utilisateur connecté dans votre projet. - - La trousse SDK React Auth0 fournit des informations sur l’utilisateur par l’intermédiaire de la propriété `user`. Examinez le code `profile.js` dans le panneau interactif pour voir un exemple de la façon de l’utiliser. - - Étant donné que la propriété `user` contient des informations sensibles liées à l’identité de l’utilisateur, sa disponibilité dépend de l’état d’authentification de l’utilisateur. Pour éviter les erreurs de rendu, vous devez toujours : - - - Utilisez la propriété `isAuthenticated` pour déterminer si Auth0 a authentifié l’utilisateur avant que React ne rende un composant qui consomme la propriété `user`. - - Assurez-vous que la trousse SDK a fini de se charger en vérifiant que `isLoading` est faux avant d’accéder à la propriété `isAuthenticated`. - - ![null](/docs/images/fr-ca/cdy7uua7fh8z/5Lp4Zahxd2v6wSJmy9JaM4/2fc68529fe5299c1fc514e3f28a8c998/Login_Screen_-_French.png) - - - ##### Point de contrôle - Vérifiez que: - - Vous pouvez afficher `user.name` ou toute autre propriété de l’utilisateur dans un composant correctement, après vous être connecté. - -
- - ## Étapes suivantes - - Beau travail! Si vous en êtes arrivé là, vous devriez avoir la connexion, la déconnexion et les informations de profil utilisateur actives dans votre application. - - Cela conclut notre tutoriel de démarrage rapide, mais il y a tellement plus à explorer. Pour en savoir plus sur ce que vous pouvez faire avec Auth0, consultez : - - * [Auth0 Dashboard](https://manage.auth0.com/#) : apprenez à configurer et gérer votre locataire et vos applications Auth0 - * [Trousse SDK auth0-react](https://www.github.com/auth0/auth0-react/) : explorez en détail la trousse SDK utilisée dans ce tutoriel - * [Auth0 Marketplace](https://marketplace.auth0.com/) : découvrez des intégrations que vous pouvez activer pour étendre les fonctionnalités d’Auth0 -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+--- +title: "Ajouter une fonctionnalité de connexion à votre application React" +permalink: "interactive" +'description': "Ce guide explique comment intégrer Auth0 à n’importe quelle application React, nouvelle ou ancienne, à l’aide du SDK React Auth0." +'og:title': "Ajouter une fonctionnalité de connexion à votre application React" +'og:description': "Ce guide explique comment intégrer Auth0 à n’importe quelle application React, nouvelle ou ancienne, à l’aide du SDK React Auth0." +'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/react.png" +'twitter:title': "Ajouter une fonctionnalité de connexion à votre application React" +'twitter:description': "Ce guide explique comment intégrer Auth0 à n’importe quelle application React, nouvelle ou ancienne, à l’aide du SDK React Auth0." +sidebarTitle: React +--- + +import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; +import { LoggedInForm } from "/snippets/Login.jsx"; +import Index from "/snippets/quickstart/spa/react/index.mdx"; +import Login from "/snippets/quickstart/spa/react/login.mdx"; +import Logout from "/snippets/quickstart/spa/react/logout.mdx"; +import Profile from "/snippets/quickstart/spa/react/profile.mdx"; + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + +export const sections = [ + { id: "configuration-d-auth0", title: "Configuration d’Auth0" }, + { id: "installer-la-trousse-sdk-auth0-react", title: "Installer la trousse SDK Auth0 React" }, + { id: "ajouter-une-fonctionnalité-de-connexion-à-votre-application", title: "Ajouter une fonctionnalité de connexion à votre application" }, + { id: "ajouter-une-fonctionnalité-de-déconnexion-à-votre-application", title: "Ajouter une fonctionnalité de déconnexion à votre application" }, + { id: "afficher-les-informations-du-profil-utilisateur", title: "Afficher les informations du profil utilisateur" } +] + + + + Auth0 vous permet d’ajouter rapidement l’authentification à presque tous les types d’application. Ce guide explique comment intégrer Auth0, ajouter l’authentification et afficher les informations de profil utilisateur dans n’importe quelle application React à l’aide du SDK React Auth0. + + Pour utiliser ce guide rapide, vous devez : + + - Vous inscrire à un compte Auth0 gratuit ou vous connecter à Auth0. + - Disposer d’un projet React fonctionnel avec lequel vous souhaitez vous intégrer. Vous pouvez également consulter ou télécharger une application faisant office d’exemple lorsque vous vous connectez. + + + Consultez le guide [React Authentication By Example (Authentification React par l’exemple)](https://developer.auth0.com/resources/guides/spa/react/basic-authentication) pour un examen approfondi de l’implémentation de l’authentification des utilisateurs dans React. Ce guide fournit des détails supplémentaires sur la façon de créer un bouton d’inscription, d’ajouter des protections de routage en utilisant React Router, et d’appeler une API protégée à partir de React. + + +
+ Pour utiliser les services Auth0, vous devez avoir une application installée dans Auth0 Dashboard. L’application Auth0 est l’endroit où vous allez configurer le fonctionnement de l’authentification pour le projet que vous développez. + + ### Configurer une application + + Utilisez le sélecteur interactif pour créer une nouvelle application Auth0 ou sélectionner une application existante qui représente le projet avec lequel vous souhaitez effectuer l’intégration. Dans Auth0, il est attribué à chaque application un identifiant client unique alphanumérique que votre code d’application utilisera pour appeler les API Auth0 via la trousse SDK. + + Tous les paramètres que vous configurez à l’aide de ce guide rapide seront automatiquement mis à jour pour votre application dans le [Dashboard](https://manage.auth0.com/#/), qui est l’endroit où vous pourrez gérer vos applications à l’avenir. + + Si vous préférez explorer une configuration complète, consultez plutôt un exemple d’application. + + ### Configuration des URL de rappel + + Une URL de rappel est une URL intégrée dans votre application vers laquelle vous souhaitez qu’Auth0 redirige les utilisateurs après leur authentification. Si elle n’est pas définie, les utilisateurs ne seront pas redirigés vers votre application après s’être connectés. + + + Si vous suivez notre exemple de projet, définissez cette URL comme suit : `http://localhost:3000`. + + + ### Configuration des URL de déconnexion + + Une URL de déconnexion est une URL intégrée dans votre application vers laquelle vous souhaitez qu’Auth0 redirige les utilisateurs après leur déconnexion. Si elle n’est pas définie, les utilisateurs ne pourront pas se déconnecter de votre application et recevront un message d’erreur. + + + Si vous suivez notre exemple de projet, définissez cette URL comme suit : `http://localhost:3000`. + + + ### Configurer les origines Web autorisées + + Une origine Web autorisée est une URL que vous souhaitez autoriser à accéder à votre flux d’authentification. Elle doit contenir l’URL de votre projet. Si elle n’est pas configurée adéquatement, votre projet ne pourra pas actualiser silencieusement les jetons d’authentification, ce qui entraînera la déconnexion de vos utilisateurs lorsque prochainement ils visiteront votre application ou lors de l’actualisation d’une page. + + + Si vous suivez notre exemple de projet, définissez cette URL comme suit : `http://localhost:3000`. + +
+ +
+ Auth0 propose une [trousse SDK React](https://github.com/auth0/auth0-react) (auth0-react.js) pour simplifier le processus de mise en œuvre de l’authentification et de l’autorisation Auth0 dans les applications React. + + Installez la trousse SDK React Auth0 en exécutant les commandes suivantes dans votre terminal : + + ``` + cd + npm install @auth0/auth0-react + ``` + + ### Configurer le composant Auth0Provider + + Pour que la trousse SDK fonctionne adéquatement, définissez les propriétés suivantes dans le composant Auth0Provider : + + - `domain`: Le domaine de votre locataire Auth0. En général, il figure dans Auth0 Dashboard dans vos paramètres d’application dans le champ Domaine. Si vous utilisez un [domaine personnalisé](https://auth0.com/docs/custom-domains), définissez-le plutôt sur la valeur de votre domaine personnalisé. + - `clientId`: L’identifiant de l’application Auth0 que vous avez configuré précédemment dans ce guide rapide. Il se trouve sur Auth0 Dashboard, dans la section Paramètres de l’application, dans le champ Identifiant client. + - `authorizationParams.redirect_uri`: L’URL dans votre application vers laquelle vous souhaitez qu’Auth0 redirige les utilisateurs après leur authentification. Cela correspond à l’URL de rappel que vous avez configurée précédemment dans ce guide de démarrage rapide. Cette valeur se trouve également dans Auth0 Dashboard, dans les paramètres de votre application, dans le champ URL de rappel. Assurez-vous que les informations que vous saisissez dans votre code correspondent à celles qui ont été configurées précédemment. Dans le cas contraire, vos utilisateurs verront un message d’erreur. + + + ##### Point de contrôle + Votre composant Auth0Provider devrait maintenant être correctement configuré. Exécutez votre application pour vérifier que: + - la trousse SDK s’initialise correctement, + - votre application ne génère aucune erreur liée à Auth0. + +
+ +
+ À présent que vous avez configuré votre application Auth0 et la trousse SDK Auth0 React, vous devez configurer la connexion pour votre projet. Pour ce faire, vous utiliserez la méthode loginWithRedirect() de la trousse SDK pour créer un bouton de connexion qui redirige les utilisateurs vers la page de connexion universelle Auth0. Une fois un utilisateur authentifié avec succès, il est redirigé vers l’URL de rappel que vous avez configurée précédemment dans ce Démarrage rapide. + + + Ce guide se concentre sur l’utilisation du hook React personnalisé `useAuth0()`. Si vous utilisez des composants de classe, consultez [le composant de niveau supérieur`withAuth0()`](https://github.com/auth0/auth0-react/blob/master/EXAMPLES.md#use-with-a-class-component). + + + Créez un nouveau fichier dans votre application appelé `login.js` pour le composant du bouton de connexion, et copiez le code du panneau interactif à droite, qui contient la logique nécessaire à la connexion. Ensuite, mettez à jour votre fichier `index.js` pour y intégrer le nouveau bouton de connexion. + + + ##### Point de contrôle + Vous devez désormais pouvoir vous connecter ou vous inscrire en utilisant un nom d’utilisateur et un mot de passe. + + Appuyez sur le bouton de connexion et vérifiez que: + - Votre application React vous redirige vers la page de connexion universelle Auth0. + - Vous pouvez vous connecter ou vous inscrire. + - Auth0 vous redirige vers votre application en utilisant la valeur `authorizationParams.redirect\_uri` que vous avez utilisée pour configurer `Auth0Provider.`. + +
+ +
+ Les utilisateurs qui se connectent à votre projet auront également besoin d’un moyen de se déconnecter. Créez un bouton de déconnexion en utilisant la méthode Logout() de la trousse SDK. Lorsque les utilisateurs se déconnecteront, ils seront redirigés vers votre point de terminaison [Auth0 logout](https://auth0.com/docs/api/authentication?javascript#logout) qui par la suite les redirigera immédiatement vers l’URL de déconnexion que vous avez configurée précédemment dans ce guide de démarrage rapide. + + Créez un nouveau fichier dans votre application appelé `logout.js` pour le composant du bouton de déconnexion, et copiez le code du panneau interactif, qui contient la logique nécessaire à la déconnexion. Ensuite, mettez à jour votre fichier `index.js` pour y intégrer le nouveau bouton de déconnexion. + + + ##### Point de contrôle + Exécutez votre application et cliquez sur le bouton de déconnexion, vérifiez que: + - Votre application React vous redirige vers l’adresse que vous avez précisée comme l’une des URL de déconnexion autorisées dans les paramètres de votre application. + - Vous n’êtes plus connecté à votre application. + +
+ +
+ Vu que vos utilisateurs peuvent désormais se connecter et se déconnecter, vous voudrez probablement pouvoir récupérer les [informations de profil](https://auth0.com/docs/users/concepts/overview-user-profile) associées aux utilisateurs authentifiés. Par exemple, vous voudrez peut-être pouvoir afficher le nom ou la photo de profil d’un utilisateur connecté dans votre projet. + + La trousse SDK React Auth0 fournit des informations sur l’utilisateur par l’intermédiaire de la propriété `user`. Examinez le code `profile.js` dans le panneau interactif pour voir un exemple de la façon de l’utiliser. + + Étant donné que la propriété `user` contient des informations sensibles liées à l’identité de l’utilisateur, sa disponibilité dépend de l’état d’authentification de l’utilisateur. Pour éviter les erreurs de rendu, vous devez toujours : + + - Utilisez la propriété `isAuthenticated` pour déterminer si Auth0 a authentifié l’utilisateur avant que React ne rende un composant qui consomme la propriété `user`. + - Assurez-vous que la trousse SDK a fini de se charger en vérifiant que `isLoading` est faux avant d’accéder à la propriété `isAuthenticated`. + + ![null](/docs/images/fr-ca/cdy7uua7fh8z/5Lp4Zahxd2v6wSJmy9JaM4/2fc68529fe5299c1fc514e3f28a8c998/Login_Screen_-_French.png) + + + ##### Point de contrôle + Vérifiez que: + - Vous pouvez afficher `user.name` ou toute autre propriété de l’utilisateur dans un composant correctement, après vous être connecté. + +
+ + ## Étapes suivantes + + Beau travail! Si vous en êtes arrivé là, vous devriez avoir la connexion, la déconnexion et les informations de profil utilisateur actives dans votre application. + + Cela conclut notre tutoriel de démarrage rapide, mais il y a tellement plus à explorer. Pour en savoir plus sur ce que vous pouvez faire avec Auth0, consultez : + + * [Auth0 Dashboard](https://manage.auth0.com/#) : apprenez à configurer et gérer votre locataire et vos applications Auth0 + * [Trousse SDK auth0-react](https://www.github.com/auth0/auth0-react/) : explorez en détail la trousse SDK utilisée dans ce tutoriel + * [Auth0 Marketplace](https://marketplace.auth0.com/) : découvrez des intégrations que vous pouvez activer pour étendre les fonctionnalités d’Auth0 +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
diff --git a/main/docs/fr-ca/quickstart/spa/vuejs/interactive.mdx b/main/docs/fr-ca/quickstart/spa/vuejs/interactive.mdx index f6f572839..cbd6794a6 100644 --- a/main/docs/fr-ca/quickstart/spa/vuejs/interactive.mdx +++ b/main/docs/fr-ca/quickstart/spa/vuejs/interactive.mdx @@ -1,212 +1,214 @@ ---- -title: "Ajouter une connexion à votre application Vue" -permalink: "interactive" -'description': "Ce guide explique comment intégrer Auth0, ajouter l’authentification et afficher les informations de profil utilisateur dans n’importe quelle application Vue à l’aide de la trousse SDK Vue Auth0." -'og:title': "Ajouter une connexion à votre application Vue" -'og:description': "Ce guide explique comment intégrer Auth0, ajouter l’authentification et afficher les informations de profil utilisateur dans n’importe quelle application Vue à l’aide de la trousse SDK Vue Auth0." -'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/vue.png" -'twitter:title': "Ajouter une connexion à votre application Vue" -'twitter:description': "Ce guide explique comment intégrer Auth0, ajouter l’authentification et afficher les informations de profil utilisateur dans n’importe quelle application Vue à l’aide de la trousse SDK Vue Auth0." -sidebarTitle: Vue ---- - -import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; -import { LoggedInForm } from "/snippets/Login.jsx"; -import Index from "/snippets/quickstart/spa/vuejs/index.mdx"; -import Login from "/snippets/quickstart/spa/vuejs/login.mdx"; -import Logout from "/snippets/quickstart/spa/vuejs/logout.mdx"; -import Profile from "/snippets/quickstart/spa/vuejs/profile.mdx"; - -export const sections = [ - { id: "configuration-d-auth0", title: "Configuration d’Auth0" }, - { id: "installer-la-trousse-sdk-auth0-vue", title: "Installer la trousse SDK Auth0 Vue" }, - { id: "ajouter-une-fonctionnalité-de-connexion-à-votre-application", title: "Ajouter une fonctionnalité de connexion à votre application" }, - { id: "ajouter-une-fonctionnalité-de-déconnexion-à-votre-application", title: "Ajouter une fonctionnalité de déconnexion à votre application" }, - { id: "afficher-les-informations-du-profil-utilisateur", title: "Afficher les informations du profil utilisateur" } -] - - - - Auth0 vous permet d’ajouter l’authentification à presque tous les types d’applications. Ce guide explique comment intégrer Auth0, ajouter l’authentification et afficher les informations de profil utilisateur dans n’importe quelle application Vue à l’aide de la trousse SDK Vue Auth0. - - - Ce guide rapide est conçu pour l’utilisation de [Vue Auth0](https://github.com/auth0/auth0-vue) avec des applications Vue 3. Si vous utilisez Vue 2, veuillez plutôt consulter le [tutoriel Vue 2 avec la trousse SDK Auth0 SPA](https://github.com/auth0/auth0-vue/blob/main/tutorial/vue2-login.md) ou le guide [Vue.js Authentication 2 By Example](https://developer.auth0.com/resources/guides/spa/vue/basic-authentication/v2-javascript). - - - Pour utiliser ce guide rapide, vous aurez besoin de : - - - Un compte Auth0 gratuit ou une connexion à Auth0. - - Un projet Vue fonctionnel avec lequel vous souhaitez vous intégrer OU vous pouvez télécharger un exemple d’application après vous être connecté. - -
- Pour utiliser les services Auth0, vous devez avoir une application installée dans Auth0 Dashboard. L’application Auth0 est l’endroit où vous allez configurer le fonctionnement de l’authentification pour le projet que vous développez. - - ### Configurer une application - - Utilisez le sélecteur interactif pour créer une nouvelle application Auth0 ou sélectionner une application existante qui représente le projet avec lequel vous souhaitez effectuer l’intégration. Dans Auth0, il est attribué à chaque application un identifiant client unique alphanumérique que votre code d’application utilisera pour appeler les API Auth0 via la trousse SDK. - - Tous les paramètres que vous configurez à l’aide de ce guide rapide seront automatiquement mis à jour pour votre application dans le [Dashboard](https://manage.auth0.com/dashboard/us/dev-1-2s2aq0/), qui est l’endroit où vous pourrez gérer vos applications à l’avenir. - - Si vous préférez explorer une configuration complète, consultez plutôt un exemple d’application. - - ### Configuration des URL de rappel - - Une URL de rappel est une URL intégrée dans votre application vers laquelle vous souhaitez qu’Auth0 redirige les utilisateurs après leur authentification. Si elle n’est pas définie, les utilisateurs ne seront pas redirigés vers votre application après s’être connectés. - - - Si vous suivez notre projet à titre d’exemple, définissez ceci sur `http://localhost:3000`. - - - ### Configuration des URL de déconnexion - - Une URL de déconnexion est une URL intégrée dans votre application vers laquelle vous souhaitez qu’Auth0 redirige les utilisateurs après leur déconnexion. Si elle n’est pas définie, les utilisateurs ne pourront pas se déconnecter de votre application et recevront un message d’erreur. - - - Si vous suivez notre projet à titre d’exemple, définissez ceci sur `http://localhost:3000`. - - - ### Configurer les origines Web autorisées - - Une origine Web autorisée est une URL que vous souhaitez autoriser à accéder à votre flux d’authentification. Elle doit contenir l’URL de votre projet. Si elle n’est pas configurée adéquatement, votre projet ne pourra pas actualiser silencieusement les jetons d’authentification, ce qui entraînera la déconnexion de vos utilisateurs lorsque prochainement ils visiteront votre application ou lors de l’actualisation d’une page. - - - Si vous suivez notre projet à titre d’exemple, définissez ceci sur `http://localhost:3000`. - -
- -
- Auth0 propose une [trousse SDK Vue](https://github.com/auth0/auth0-vue) pour simplifier le processus d’implémentation de l’authentification et de l’autorisation Auth0 dans les applications Vue 3. - - Installez la trousse SDK Auth0 Vue en exécutant les commandes suivantes dans votre terminal : - - ``` - cd - npm install @auth0/auth0-vue - ``` - - ### Enregistrer le plugiciel - - Pour que la trousse SDK fonctionne, vous devez enregistrer le plugiciel dans votre application Vue à l’aide des propriétés suivantes : - - - `domain` : Le domaine de votre locataire Auth0. Cette valeur se trouve dans Auth0 Dashboard dans les Settings (Paramètres) de votre application dans le champ Domain (Domaine). Si vous utilisez un [domaine personnalisé](https://auth0.com/docs/custom-domains), définissez-le plutôt sur la valeur de votre domaine personnalisé. - - `clientId` : L’identifiant de l’application Auth0 que vous avez configurée précédemment dans le démarrage rapide. Vous le trouverez dans Auth0 Dashboard sous les paramètres de votre application dans le champ Client ID (Identifiant client). - - `authorizationParams.redirect_uri` : L’URL dans votre application vers laquelle vous souhaitez qu’Auth0 redirige les utilisateurs après leur authentification. Cela correspond à l’URL de rappel que vous avez configurée précédemment dans ce démarrage rapide. Cette valeur se trouve dans Auth0 Dashboard, dans les Paramètres de votre application, dans le champ URL de rappel. Assurez-vous que ce que vous saisissez dans votre code correspond à ce que vous avez configuré précédemment, au cas contraire, vos utilisateurs verront une erreur. - - Le plugiciel enregistrera la trousse SDK en utilisant à la fois `provide` et `app.config.globalProperties`. Cela permet d’activer à la fois l’[API de composition](https://vuejs.org/guide/introduction.html#composition-api) et l’[API d’options](https://vuejs.org/guide/introduction.html#options-api). - - - ##### Point de contrôle - Le plugiciel est maintenant configuré. Exécutez votre application pour vérifier que: - la trousse SDK est correctement initialisée, - votre application ne génère aucune erreur liée à Auth0. - -
- -
- Vous allez ensuite configurer une connexion pour votre projet. Vous utiliserez la fonction `loginWithRedirect` de la trousse SDK exposée à la valeur de retour de `useAuth0`, à laquelle vous pouvez accéder dans la fonction de configuration de votre composant. Elle redirigera les utilisateurs vers la page de connexion universelle Auth0 et, après l’authentification de l’utilisateur, elle le redirigera vers l’URL de rappel que vous avez configurée plus tôt dans ce guide rapide. - - ### Utilisation d’Options API - - Si vous utilisez Options API, vous pouvez utiliser la même méthode `loginWithRedirect` à partir de la propriété globale `$auth0` via l’accesseur `this`. - - - ##### Point de contrôle - Vous devriez maintenant être en mesure de vous connecter en utilisant la connexion universelle Auth0. - - Appuyez sur le bouton de connexion et vérifiez que: - - Votre application Vue vous redirige vers la page de connexion universelle Auth0. - - Vous pouvez vous connecter ou vous inscrire. - - Auth0 vous redirige vers votre application en utilisant la valeur `authorizationParams.redirect\_uri` que vous avez utilisée pour configurer le plugiciel. - -
- -
- Les utilisateurs qui se connectent à votre projet auront également besoin d’un moyen de se déconnecter. Quand les utilisateurs se déconnectent, votre application les redirige vers votre point de terminaison [Déconnexion Auth0](https://auth0.com/docs/api/authentication?javascript#logout), qui les redirige ensuite vers le paramètre `logoutParams.returnTo` indiqué. - - Utilisez la fonction `logout` exposée sur la valeur de retour `useAuth0`, à laquelle vous pouvez accéder dans la fonction `setup` de votre composant, pour déconnecter l’utilisateur de votre application. - - ### Utilisation d’Options API - - Avec l’Options API, vous pouvez utiliser la même méthode `logout` à partir de la propriété globale `$auth0` via l’accesseur `this`. - - - ##### Point de contrôle - Exécutez votre application et cliquez sur le bouton de déconnexion, vérifiez que: - - votre application Vue vous redirige vers l’adresse `logoutParams.returnTo` , - - vous n’êtes plus connecté à votre application. - -
- -
- Vous allez ensuite configurer la manière de récupérer les [informations de profil](https://auth0.com/docs/users/concepts/overview-user-profile) associées aux utilisateurs authentifiés. Par exemple, vous voudrez peut-être pouvoir afficher le nom ou la photo de profil d’un utilisateur connecté dans votre projet. Une fois l’utilisateur authentifié, la trousse SDK extrait les informations du profil utilisateur et les stocke en mémoire. L’application peut accéder au profil utilisateur à l’aide de la propriété réactive `user`. Pour accéder à cette propriété, examinez la fonction `setup` de votre composant et trouvez la valeur de retour de `userAuth0`. - - La propriété `user` contient des informations sensibles relatives à l’identité de l’utilisateur. Elle n’est disponible qu’en fonction de l’état d’authentification de l’utilisateur. Pour éviter les erreurs de rendu, vous devez toujours : - - - utiliser la propriété `isAuthenticated` pour déterminer si Auth0 a authentifié l’utilisateur avant que Vue ne rende un composant qui consomme la propriété `user`. - - vous assurer que la trousse SDK a fini de se charger en vérifiant que `isLoading` est false avant d’accéder à la propriété `isAuthenticated`. - - ### Utilisation de l’API Options - - Pour l’API Options, utilisez les mêmes propriétés réactives `user`, `isLoading` et `isAuthenticated` de la propriété globale `$auth0` via l’accesseur `this`. - - - ##### Point de contrôle - Vérifiez que: - - vous pouvez afficher `user` ou l’une des propriétés de l’utilisateur correctement dans un composant, après vous être connecté. - -
- - ## Étapes suivantes - - Beau travail! Si vous en êtes arrivé là, vous devriez avoir la connexion, la déconnexion et les informations de profil utilisateur actives dans votre application. - - Cela conclut notre tutoriel de démarrage rapide, mais il y a tellement plus à explorer. Pour en savoir plus sur ce que vous pouvez faire avec Auth0, consultez : - - * [Auth0 Dashboard](https://manage.auth0.com/#) : apprenez à configurer et gérer votre locataire et vos applications Auth0 - * [Trousse SDK auth0-spa-js](https://github.com/auth0/auth0-spa-js) : explorez en détail la trousse SDK utilisée dans ce tutoriel - * [Auth0 Marketplace](https://marketplace.auth0.com/) : découvrez des intégrations que vous pouvez activer pour étendre les fonctionnalités d’Auth0 -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+--- +title: "Ajouter une connexion à votre application Vue" +permalink: "interactive" +'description': "Ce guide explique comment intégrer Auth0, ajouter l’authentification et afficher les informations de profil utilisateur dans n’importe quelle application Vue à l’aide de la trousse SDK Vue Auth0." +'og:title': "Ajouter une connexion à votre application Vue" +'og:description': "Ce guide explique comment intégrer Auth0, ajouter l’authentification et afficher les informations de profil utilisateur dans n’importe quelle application Vue à l’aide de la trousse SDK Vue Auth0." +'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/vue.png" +'twitter:title': "Ajouter une connexion à votre application Vue" +'twitter:description': "Ce guide explique comment intégrer Auth0, ajouter l’authentification et afficher les informations de profil utilisateur dans n’importe quelle application Vue à l’aide de la trousse SDK Vue Auth0." +sidebarTitle: Vue +--- + +import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; +import { LoggedInForm } from "/snippets/Login.jsx"; +import Index from "/snippets/quickstart/spa/vuejs/index.mdx"; +import Login from "/snippets/quickstart/spa/vuejs/login.mdx"; +import Logout from "/snippets/quickstart/spa/vuejs/logout.mdx"; +import Profile from "/snippets/quickstart/spa/vuejs/profile.mdx"; + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + +export const sections = [ + { id: "configuration-d-auth0", title: "Configuration d’Auth0" }, + { id: "installer-la-trousse-sdk-auth0-vue", title: "Installer la trousse SDK Auth0 Vue" }, + { id: "ajouter-une-fonctionnalité-de-connexion-à-votre-application", title: "Ajouter une fonctionnalité de connexion à votre application" }, + { id: "ajouter-une-fonctionnalité-de-déconnexion-à-votre-application", title: "Ajouter une fonctionnalité de déconnexion à votre application" }, + { id: "afficher-les-informations-du-profil-utilisateur", title: "Afficher les informations du profil utilisateur" } +] + + + + Auth0 vous permet d’ajouter l’authentification à presque tous les types d’applications. Ce guide explique comment intégrer Auth0, ajouter l’authentification et afficher les informations de profil utilisateur dans n’importe quelle application Vue à l’aide de la trousse SDK Vue Auth0. + + + Ce guide rapide est conçu pour l’utilisation de [Vue Auth0](https://github.com/auth0/auth0-vue) avec des applications Vue 3. Si vous utilisez Vue 2, veuillez plutôt consulter le [tutoriel Vue 2 avec la trousse SDK Auth0 SPA](https://github.com/auth0/auth0-vue/blob/main/tutorial/vue2-login.md) ou le guide [Vue.js Authentication 2 By Example](https://developer.auth0.com/resources/guides/spa/vue/basic-authentication/v2-javascript). + + + Pour utiliser ce guide rapide, vous aurez besoin de : + + - Un compte Auth0 gratuit ou une connexion à Auth0. + - Un projet Vue fonctionnel avec lequel vous souhaitez vous intégrer OU vous pouvez télécharger un exemple d’application après vous être connecté. + +
+ Pour utiliser les services Auth0, vous devez avoir une application installée dans Auth0 Dashboard. L’application Auth0 est l’endroit où vous allez configurer le fonctionnement de l’authentification pour le projet que vous développez. + + ### Configurer une application + + Utilisez le sélecteur interactif pour créer une nouvelle application Auth0 ou sélectionner une application existante qui représente le projet avec lequel vous souhaitez effectuer l’intégration. Dans Auth0, il est attribué à chaque application un identifiant client unique alphanumérique que votre code d’application utilisera pour appeler les API Auth0 via la trousse SDK. + + Tous les paramètres que vous configurez à l’aide de ce guide rapide seront automatiquement mis à jour pour votre application dans le [Dashboard](https://manage.auth0.com/dashboard/us/dev-1-2s2aq0/), qui est l’endroit où vous pourrez gérer vos applications à l’avenir. + + Si vous préférez explorer une configuration complète, consultez plutôt un exemple d’application. + + ### Configuration des URL de rappel + + Une URL de rappel est une URL intégrée dans votre application vers laquelle vous souhaitez qu’Auth0 redirige les utilisateurs après leur authentification. Si elle n’est pas définie, les utilisateurs ne seront pas redirigés vers votre application après s’être connectés. + + + Si vous suivez notre projet à titre d’exemple, définissez ceci sur `http://localhost:3000`. + + + ### Configuration des URL de déconnexion + + Une URL de déconnexion est une URL intégrée dans votre application vers laquelle vous souhaitez qu’Auth0 redirige les utilisateurs après leur déconnexion. Si elle n’est pas définie, les utilisateurs ne pourront pas se déconnecter de votre application et recevront un message d’erreur. + + + Si vous suivez notre projet à titre d’exemple, définissez ceci sur `http://localhost:3000`. + + + ### Configurer les origines Web autorisées + + Une origine Web autorisée est une URL que vous souhaitez autoriser à accéder à votre flux d’authentification. Elle doit contenir l’URL de votre projet. Si elle n’est pas configurée adéquatement, votre projet ne pourra pas actualiser silencieusement les jetons d’authentification, ce qui entraînera la déconnexion de vos utilisateurs lorsque prochainement ils visiteront votre application ou lors de l’actualisation d’une page. + + + Si vous suivez notre projet à titre d’exemple, définissez ceci sur `http://localhost:3000`. + +
+ +
+ Auth0 propose une [trousse SDK Vue](https://github.com/auth0/auth0-vue) pour simplifier le processus d’implémentation de l’authentification et de l’autorisation Auth0 dans les applications Vue 3. + + Installez la trousse SDK Auth0 Vue en exécutant les commandes suivantes dans votre terminal : + + ``` + cd + npm install @auth0/auth0-vue + ``` + + ### Enregistrer le plugiciel + + Pour que la trousse SDK fonctionne, vous devez enregistrer le plugiciel dans votre application Vue à l’aide des propriétés suivantes : + + - `domain` : Le domaine de votre locataire Auth0. Cette valeur se trouve dans Auth0 Dashboard dans les Settings (Paramètres) de votre application dans le champ Domain (Domaine). Si vous utilisez un [domaine personnalisé](https://auth0.com/docs/custom-domains), définissez-le plutôt sur la valeur de votre domaine personnalisé. + - `clientId` : L’identifiant de l’application Auth0 que vous avez configurée précédemment dans le démarrage rapide. Vous le trouverez dans Auth0 Dashboard sous les paramètres de votre application dans le champ Client ID (Identifiant client). + - `authorizationParams.redirect_uri` : L’URL dans votre application vers laquelle vous souhaitez qu’Auth0 redirige les utilisateurs après leur authentification. Cela correspond à l’URL de rappel que vous avez configurée précédemment dans ce démarrage rapide. Cette valeur se trouve dans Auth0 Dashboard, dans les Paramètres de votre application, dans le champ URL de rappel. Assurez-vous que ce que vous saisissez dans votre code correspond à ce que vous avez configuré précédemment, au cas contraire, vos utilisateurs verront une erreur. + + Le plugiciel enregistrera la trousse SDK en utilisant à la fois `provide` et `app.config.globalProperties`. Cela permet d’activer à la fois l’[API de composition](https://vuejs.org/guide/introduction.html#composition-api) et l’[API d’options](https://vuejs.org/guide/introduction.html#options-api). + + + ##### Point de contrôle + Le plugiciel est maintenant configuré. Exécutez votre application pour vérifier que: + la trousse SDK est correctement initialisée, + votre application ne génère aucune erreur liée à Auth0. + +
+ +
+ Vous allez ensuite configurer une connexion pour votre projet. Vous utiliserez la fonction `loginWithRedirect` de la trousse SDK exposée à la valeur de retour de `useAuth0`, à laquelle vous pouvez accéder dans la fonction de configuration de votre composant. Elle redirigera les utilisateurs vers la page de connexion universelle Auth0 et, après l’authentification de l’utilisateur, elle le redirigera vers l’URL de rappel que vous avez configurée plus tôt dans ce guide rapide. + + ### Utilisation d’Options API + + Si vous utilisez Options API, vous pouvez utiliser la même méthode `loginWithRedirect` à partir de la propriété globale `$auth0` via l’accesseur `this`. + + + ##### Point de contrôle + Vous devriez maintenant être en mesure de vous connecter en utilisant la connexion universelle Auth0. + + Appuyez sur le bouton de connexion et vérifiez que: + - Votre application Vue vous redirige vers la page de connexion universelle Auth0. + - Vous pouvez vous connecter ou vous inscrire. + - Auth0 vous redirige vers votre application en utilisant la valeur `authorizationParams.redirect\_uri` que vous avez utilisée pour configurer le plugiciel. + +
+ +
+ Les utilisateurs qui se connectent à votre projet auront également besoin d’un moyen de se déconnecter. Quand les utilisateurs se déconnectent, votre application les redirige vers votre point de terminaison [Déconnexion Auth0](https://auth0.com/docs/api/authentication?javascript#logout), qui les redirige ensuite vers le paramètre `logoutParams.returnTo` indiqué. + + Utilisez la fonction `logout` exposée sur la valeur de retour `useAuth0`, à laquelle vous pouvez accéder dans la fonction `setup` de votre composant, pour déconnecter l’utilisateur de votre application. + + ### Utilisation d’Options API + + Avec l’Options API, vous pouvez utiliser la même méthode `logout` à partir de la propriété globale `$auth0` via l’accesseur `this`. + + + ##### Point de contrôle + Exécutez votre application et cliquez sur le bouton de déconnexion, vérifiez que: + - votre application Vue vous redirige vers l’adresse `logoutParams.returnTo` , + - vous n’êtes plus connecté à votre application. + +
+ +
+ Vous allez ensuite configurer la manière de récupérer les [informations de profil](https://auth0.com/docs/users/concepts/overview-user-profile) associées aux utilisateurs authentifiés. Par exemple, vous voudrez peut-être pouvoir afficher le nom ou la photo de profil d’un utilisateur connecté dans votre projet. Une fois l’utilisateur authentifié, la trousse SDK extrait les informations du profil utilisateur et les stocke en mémoire. L’application peut accéder au profil utilisateur à l’aide de la propriété réactive `user`. Pour accéder à cette propriété, examinez la fonction `setup` de votre composant et trouvez la valeur de retour de `userAuth0`. + + La propriété `user` contient des informations sensibles relatives à l’identité de l’utilisateur. Elle n’est disponible qu’en fonction de l’état d’authentification de l’utilisateur. Pour éviter les erreurs de rendu, vous devez toujours : + + - utiliser la propriété `isAuthenticated` pour déterminer si Auth0 a authentifié l’utilisateur avant que Vue ne rende un composant qui consomme la propriété `user`. + - vous assurer que la trousse SDK a fini de se charger en vérifiant que `isLoading` est false avant d’accéder à la propriété `isAuthenticated`. + + ### Utilisation de l’API Options + + Pour l’API Options, utilisez les mêmes propriétés réactives `user`, `isLoading` et `isAuthenticated` de la propriété globale `$auth0` via l’accesseur `this`. + + + ##### Point de contrôle + Vérifiez que: + - vous pouvez afficher `user` ou l’une des propriétés de l’utilisateur correctement dans un composant, après vous être connecté. + +
+ + ## Étapes suivantes + + Beau travail! Si vous en êtes arrivé là, vous devriez avoir la connexion, la déconnexion et les informations de profil utilisateur actives dans votre application. + + Cela conclut notre tutoriel de démarrage rapide, mais il y a tellement plus à explorer. Pour en savoir plus sur ce que vous pouvez faire avec Auth0, consultez : + + * [Auth0 Dashboard](https://manage.auth0.com/#) : apprenez à configurer et gérer votre locataire et vos applications Auth0 + * [Trousse SDK auth0-spa-js](https://github.com/auth0/auth0-spa-js) : explorez en détail la trousse SDK utilisée dans ce tutoriel + * [Auth0 Marketplace](https://marketplace.auth0.com/) : découvrez des intégrations que vous pouvez activer pour étendre les fonctionnalités d’Auth0 +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
diff --git a/main/docs/fr-ca/quickstart/webapp/apache/interactive.mdx b/main/docs/fr-ca/quickstart/webapp/apache/interactive.mdx index e904a4364..48fa654f7 100644 --- a/main/docs/fr-ca/quickstart/webapp/apache/interactive.mdx +++ b/main/docs/fr-ca/quickstart/webapp/apache/interactive.mdx @@ -1,119 +1,122 @@ ---- -title: "Apache" -permalink: "interactive" -'description': "Ce tutoriel montre comment configurer Apache pour ajouter l’authentification et l’autorisation à votre application web." -'og:title': "Apache" -'og:description': "Ce tutoriel montre comment configurer Apache pour ajouter l’authentification et l’autorisation à votre application web." -'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/apache.jpg" -'twitter:title': "Apache" -'twitter:description': "Ce tutoriel montre comment configurer Apache pour ajouter l’authentification et l’autorisation à votre application web." ---- - -import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx" -import Code1 from "/snippets/quickstart/webapp/apache/code1.mdx" -import Code2 from "/snippets/quickstart/webapp/apache/code2.mdx" - -export const sections = [ - { id: "configuration-requise", title: "Configuration requise" }, - { id: "installer-et-activer-le-module-mod-auth-openidc", title: "Installer et activer le module mod_auth_openidc" }, - { id: "configurer-le-module-avec-les-informations-de-votre-compte-auth0", title: "Configurer le module avec les informations de votre compte Auth0" }, - { id: "configuration-d-auth0", title: "Configuration d’Auth0" }, - { id: "autorisation", title: "Autorisation" } -] - - - - Ce tutoriel montre comment configurer Apache pour ajouter l’authentification et l’autorisation à votre application web. Nous vous recommandons de vous connecter pour suivre ce démarrage rapide avec les exemples configurés pour votre compte. - -
- Ce tutoriel et le projet d’exemple ont été testés avec les éléments suivants : - - - Apache 2.4 -
- -
- Tout d’abord, installez le module `mod_auth_openidc` pour Apache. - - Vous pouvez obtenir les binaires sur [GitHub](https://github.com/zmartzone/mod_auth_openidc/releases) et les installer pour votre système d’exploitation. Si votre système d’exploitation n’est pas compatible avec les binaires, vous pouvez toujours le [build it from source (construire à partir de la source)](https://github.com/zmartzone/mod_auth_openidc/blob/master/INSTALL). - - Une fois le module installé, activez-le pour Apache avec la commande `a2enmod`. Pour en savoir plus, veuillez consulter la page [a2enmod on Ubuntu Manpage](https://manpages.ubuntu.com/manpages/focal/man8/a2enmod.8.html) : - - `a2enmod auth_openidc` - - - Pour Windows, vous pouvez utiliser [ce script Powershell](https://github.com/enderandpeter/win-a2enmod#installation) pour faire fonctionner `a2enmod` sur votre système. - -
- -
- Mettez à jour votre nouveau fichier de configuration (`auth_openidc.conf`), présent dans le dossier `/etc/apache2/mods-available`. - - - Pour Windows, vous devez utiliser le fichier `/apache/conf/httpd.conf`. - -
- -
- Dans Auth0 Dashboard : - - 1. Accédez à **Applications** > **Applications**, puis sélectionnez votre application dans la liste. - 2. Passez à l’affichage **Settings (Paramètres)**, puis localisez la section **Application URIs** (URI d’application). - 3. Ajoutez la valeur de `OIDCRedirectURI`à **URL de rappel autorisées**. - 4. Localisez **Advanced Settings (Paramètres avancés)** au bas de la page. - 5. Passez à l’affichage **OAuth**. - 6. Définissez **Algorithme de signature du jeton Web JSON (JWT)** sur `RS256`. -
- -
- Vous pouvez configurer Apache pour protéger un emplacement spécifique en fonction de la valeur d’une revendication dans le jeton d’ID de l’utilisateur en ajoutant un bloc `Location` à votre fichier `auth_openidc.conf`. - - Par exemple, vous pouvez créer une Action qui lit les rôles de l’utilisateur, puis ajoute une revendication qui accorde l’accès à un emplacement protégé : - - ```js - exports.onExecutePostLogin = async (event, api) => { - const roles = event.authorization.roles; // ['user', 'admin'] - if (roles.includes('admin')) { - api.idToken.setCustomClaim('folder', 'admin'); - - } - }; - ``` -
- - ## Étapes suivantes - - Beau travail! Si vous en êtes arrivé là, vous devriez avoir la connexion, la déconnexion et les informations de profil utilisateur actives dans votre application. - - Cela conclut notre tutoriel de démarrage rapide, mais il y a tellement plus à explorer. Pour en savoir plus sur ce que vous pouvez faire avec Auth0, consultez : - - * [Auth0 Dashboard](https://manage.auth0.com/#) : apprenez à configurer et gérer votre locataire et vos applications Auth0 - * [Auth0 Marketplace](https://marketplace.auth0.com/) : découvrez des intégrations que vous pouvez activer pour étendre les fonctionnalités d’Auth0 -
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
+--- +title: "Apache" +permalink: "interactive" +'description': "Ce tutoriel montre comment configurer Apache pour ajouter l’authentification et l’autorisation à votre application web." +'og:title': "Apache" +'og:description': "Ce tutoriel montre comment configurer Apache pour ajouter l’authentification et l’autorisation à votre application web." +'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/apache.jpg" +'twitter:title': "Apache" +'twitter:description': "Ce tutoriel montre comment configurer Apache pour ajouter l’authentification et l’autorisation à votre application web." +--- + + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + +import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx" +import Code1 from "/snippets/quickstart/webapp/apache/code1.mdx" +import Code2 from "/snippets/quickstart/webapp/apache/code2.mdx" + +export const sections = [ + { id: "configuration-requise", title: "Configuration requise" }, + { id: "installer-et-activer-le-module-mod-auth-openidc", title: "Installer et activer le module mod_auth_openidc" }, + { id: "configurer-le-module-avec-les-informations-de-votre-compte-auth0", title: "Configurer le module avec les informations de votre compte Auth0" }, + { id: "configuration-d-auth0", title: "Configuration d’Auth0" }, + { id: "autorisation", title: "Autorisation" } +] + + + + Ce tutoriel montre comment configurer Apache pour ajouter l’authentification et l’autorisation à votre application web. Nous vous recommandons de vous connecter pour suivre ce démarrage rapide avec les exemples configurés pour votre compte. + +
+ Ce tutoriel et le projet d’exemple ont été testés avec les éléments suivants : + + - Apache 2.4 +
+ +
+ Tout d’abord, installez le module `mod_auth_openidc` pour Apache. + + Vous pouvez obtenir les binaires sur [GitHub](https://github.com/zmartzone/mod_auth_openidc/releases) et les installer pour votre système d’exploitation. Si votre système d’exploitation n’est pas compatible avec les binaires, vous pouvez toujours le [build it from source (construire à partir de la source)](https://github.com/zmartzone/mod_auth_openidc/blob/master/INSTALL). + + Une fois le module installé, activez-le pour Apache avec la commande `a2enmod`. Pour en savoir plus, veuillez consulter la page [a2enmod on Ubuntu Manpage](https://manpages.ubuntu.com/manpages/focal/man8/a2enmod.8.html) : + + `a2enmod auth_openidc` + + + Pour Windows, vous pouvez utiliser [ce script Powershell](https://github.com/enderandpeter/win-a2enmod#installation) pour faire fonctionner `a2enmod` sur votre système. + +
+ +
+ Mettez à jour votre nouveau fichier de configuration (`auth_openidc.conf`), présent dans le dossier `/etc/apache2/mods-available`. + + + Pour Windows, vous devez utiliser le fichier `/apache/conf/httpd.conf`. + +
+ +
+ Dans Auth0 Dashboard : + + 1. Accédez à **Applications** > **Applications**, puis sélectionnez votre application dans la liste. + 2. Passez à l’affichage **Settings (Paramètres)**, puis localisez la section **Application URIs** (URI d’application). + 3. Ajoutez la valeur de `OIDCRedirectURI`à **URL de rappel autorisées**. + 4. Localisez **Advanced Settings (Paramètres avancés)** au bas de la page. + 5. Passez à l’affichage **OAuth**. + 6. Définissez **Algorithme de signature du jeton Web JSON (JWT)** sur `RS256`. +
+ +
+ Vous pouvez configurer Apache pour protéger un emplacement spécifique en fonction de la valeur d’une revendication dans le jeton d’ID de l’utilisateur en ajoutant un bloc `Location` à votre fichier `auth_openidc.conf`. + + Par exemple, vous pouvez créer une Action qui lit les rôles de l’utilisateur, puis ajoute une revendication qui accorde l’accès à un emplacement protégé : + + ```js + exports.onExecutePostLogin = async (event, api) => { + const roles = event.authorization.roles; // ['user', 'admin'] + if (roles.includes('admin')) { + api.idToken.setCustomClaim('folder', 'admin'); + + } + }; + ``` +
+ + ## Étapes suivantes + + Beau travail! Si vous en êtes arrivé là, vous devriez avoir la connexion, la déconnexion et les informations de profil utilisateur actives dans votre application. + + Cela conclut notre tutoriel de démarrage rapide, mais il y a tellement plus à explorer. Pour en savoir plus sur ce que vous pouvez faire avec Auth0, consultez : + + * [Auth0 Dashboard](https://manage.auth0.com/#) : apprenez à configurer et gérer votre locataire et vos applications Auth0 + * [Auth0 Marketplace](https://marketplace.auth0.com/) : découvrez des intégrations que vous pouvez activer pour étendre les fonctionnalités d’Auth0 +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
diff --git a/main/docs/fr-ca/quickstart/webapp/aspnet-core-blazor-server/interactive.mdx b/main/docs/fr-ca/quickstart/webapp/aspnet-core-blazor-server/interactive.mdx index 5a43f9f6f..e754a4c4e 100644 --- a/main/docs/fr-ca/quickstart/webapp/aspnet-core-blazor-server/interactive.mdx +++ b/main/docs/fr-ca/quickstart/webapp/aspnet-core-blazor-server/interactive.mdx @@ -1,153 +1,156 @@ ---- -title: "Ajouter une fonctionnalité de connexion à votre application Blazor Server" -permalink: "interactive" -'description': "Ce guide explique comment intégrer Auth0 à n’importe quelle application Blazor Server, nouvelle ou existante, à l’aide de la trousse SDK Auth0.AspNetCore.Authentication." -'og:title': "Ajouter une fonctionnalité de connexion à votre application Blazor Server" -'og:description': "Ce guide explique comment intégrer Auth0 à n’importe quelle application Blazor Server, nouvelle ou existante, à l’aide de la trousse SDK Auth0.AspNetCore.Authentication." -'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/asp.png" -'twitter:title': "Ajouter une fonctionnalité de connexion à votre application Blazor Server" -'twitter:description': "Ce guide explique comment intégrer Auth0 à n’importe quelle application Blazor Server, nouvelle ou existante, à l’aide de la trousse SDK Auth0.AspNetCore.Authentication." -sidebarTitle: ASP.NET Core Blazor Server ---- - -import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx" -import Login from "/snippets/quickstart/webapp/aspnet-core-blazor-server/Login.cshtml.cs.mdx" -import Logout from "/snippets/quickstart/webapp/aspnet-core-blazor-server/Logout.cshtml.cs.mdx" - -export const sections = [ - { id: "configuration-d-auth0", title: "Configuration d’Auth0" }, - { id: "installer-et-configurer-la-trousse-sdk", title: "Installer et configurer la trousse SDK" }, - { id: "connexion", title: "Connexion" }, - { id: "afficher-le-profil-utilisateur", title: "Afficher le profil utilisateur" }, - { id: "déconnexion", title: "Déconnexion" } -] - - - - Auth0 vous permet d’ajouter rapidement l’authentification et de pouvoir accéder aux informations relatives au profil utilisateur dans votre application. Ce guide explique comment intégrer Auth0 à n’importe quelle application Blazor Server, nouvelle ou existante, à l’aide de la trousse SDK **Auth0.AspNetCore.Authentication**. - -
- Pour utiliser les services Auth0, vous devez avoir une application installée dans Auth0 Dashboard. L’application Auth0 est l’endroit où vous allez configurer le fonctionnement de l’authentification pour le projet que vous développez. - - ### Configurer une application - - Utilisez le sélecteur interactif pour créer une nouvelle application Auth0 ou sélectionner une application existante qui représente le projet avec lequel vous souhaitez effectuer l’intégration. Dans Auth0, il est attribué à chaque application un identifiant client unique alphanumérique que votre code d’application utilisera pour appeler les API Auth0 via la trousse SDK. - - Tous les paramètres que vous configurez à l’aide de ce démarrage rapide seront automatiquement mis à jour pour votre application dans le [Dashboard](https://manage.auth0.com/dashboard/us/auth0-dsepaid/), qui est l’endroit où vous pourrez gérer vos Applications à l’avenir. - - Si vous préférez explorer une configuration complète, consultez plutôt un exemple d’application. - - ### Configuration des URL de rappel - - Une URL de rappel est une URL intégrée dans votre application vers laquelle vous souhaitez qu’Auth0 redirige les utilisateurs après leur authentification. Si elle n’est pas définie, les utilisateurs ne seront pas redirigés vers votre application après s’être connectés. - - - Si vous suivez notre exemple de projet, définissez cette URL comme suit : `http://localhost:3000``/callback`. - - - ### Configuration des URL de déconnexion - - Une URL de déconnexion est une URL intégrée dans votre application vers laquelle vous souhaitez qu’Auth0 redirige les utilisateurs après leur déconnexion. Si elle n’est pas définie, les utilisateurs ne pourront pas se déconnecter de votre application et recevront un message d’erreur. - - - Si vous suivez notre exemple de projet, définissez cette URL comme suit : `http://localhost:3000`. - -
- -
- ### Installer à partir de Nuget - - Pour intégrer Auth0 à Blazor Server vous pouvez utiliser notre trousse SDK en installant le [package Nuget](https://www.nuget.org/packages/Auth0.AspNetCore.Authentication/)`Auth0.AspNetCore.Authentication`dans votre application. - - ### Configurer le logiciel médiateur - - Pour activer l’authentification dans votre application Blazor Server, utilisez le logiciel médiateur fourni par la trousse SDK. Allez dans le fichier `Program.cs` et appelez `builder.Services.AddAuth0WebAppAuthentication()` pour enregistrer le logiciel médiateur de la trousse SDK. - - Assurez-vous de configurer `Domain` et `ClientId`, car ce sont des champs requis pour garantir que la trousse SDK sache quel locataire Auth0 et quelle application utiliser. - - Assurez-vous d’avoir activé l’authentification et l’autorisation dans votre fichier `Program.cs`. -
- -
- Pour permettre aux utilisateurs de se connecter à votre application Blazor Server, ajoutez un `LoginModel` à votre répertoire `Pages`. - - Dans le cadre de la méthode `OnGet` de `LoginModel`, appelez `HTTPContext.ChallengeAsync()` et passez `Auth0Constants.AuthenticationScheme` comme schéma d’authentification. Cela fera appel au gestionnaire d’authentification OIDC que notre trousse SDK enregistre en interne. Assurez-vous également d’indiquer les `authenticationProperties` correspondantes, que vous pouvez construire en utilisant `LoginAuthenticationPropertiesBuilder`. - - Après avoir appelé avec succès `HttpContext.ChallengeAsync()`, l’utilisateur est redirigé vers Auth0 et est connecté à la fois au logiciel médiateur OIDC et au logiciel médiateur de témoin après avoir été redirigé vers votre application. Cela permettra aux utilisateurs d’être authentifiés lors des requêtes suivantes. - - - ##### Point de contrôle - Maintenant que vous avez configuré la fonction de connexion, lancez votre application pour vérifier que: - naviguer vers votre page `Login` vous redirigera vers Auth0, - saisir vos identifiants vous redirigera vers votre application. - -
- -
- Une fois que le logiciel médiateur a réussi à récupérer les jetons auprès d’Auth0, il extrait les informations et les demandes de l’utilisateur du jeton d’ID et les met à disposition via `AuthenticationState`, que vous pouvez ajouter en tant que `CascadingParameter`. - - Vous pouvez créer une page de profil utilisateur personnalisée pour afficher le nom de l’utilisateur, ainsi que des demandes supplémentaires (comme le courriel et la photo), en récupérant les informations correspondantes à partir de la propriété `User` de `AuthenticationState` et en les visualisant à partir du code Blazor. - - - ##### Point de contrôle - Maintenant que vous avez effectué la configuration pour afficher le profil utilisateur, lancez votre application pour vérifier que: - la navigation vers le point de terminaison contenant le profil après une connexion réussie permet d’afficher le profil utilisateur. - -
- -
- Déconnecter l’utilisateur de votre propre application peut se faire en appelant `HttpContext.SignOutAsync` avec le schéma d’authentification `CookieAuthenticationDefaults.AuthenticationScheme` à partir de la méthode `OnGet`de `LogoutModel`. - - En outre, si vous souhaitez également déconnecter l’utilisateur d’Auth0 (cette action peut également le déconnecter d’autres applications qui utilisent l’authentification unique), appelez `HttpContext.SignOutAsync` avec le schéma d’authentification `Auth0Constants.AuthenticationScheme` ainsi que l’`authenticationProperties` approprié qui peut être construit en utilisant `LogoutAuthenticationPropertiesBuilder`. - - - ##### Point de contrôle - Maintenant que vous avez configuré la fonction de déconnexion, exécutez votre application pour vérifier que: - Naviguer vers votre page `Logout` garantira que l’utilisateur est déconnecté. - Lorsque vous vous déconnectez également d’Auth0, vous devriez être redirigé vers Auth0, puis immédiatement renvoyé vers votre propre application. - -
- - ## Étapes suivantes - - Beau travail! Si vous en êtes arrivé là, vous devriez avoir la connexion, la déconnexion et les informations de profil utilisateur actives dans votre application. - - Cela conclut notre tutoriel de démarrage rapide, mais il y a tellement plus à explorer. Pour en savoir plus sur ce que vous pouvez faire avec Auth0, consultez : - - * [Auth0 Dashboard](https://manage.auth0.com/#) : apprenez à configurer et gérer votre locataire et vos applications Auth0 - * [Trousse SDK auth0-aspnetcore-authentication](https://github.com/auth0/auth0-aspnetcore-authentication) : explorez en détail la trousse SDK utilisée dans ce tutoriel - * [Auth0 Marketplace](https://marketplace.auth0.com/) : découvrez des intégrations que vous pouvez activer pour étendre les fonctionnalités d’Auth0 -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+--- +title: "Ajouter une fonctionnalité de connexion à votre application Blazor Server" +permalink: "interactive" +'description': "Ce guide explique comment intégrer Auth0 à n’importe quelle application Blazor Server, nouvelle ou existante, à l’aide de la trousse SDK Auth0.AspNetCore.Authentication." +'og:title': "Ajouter une fonctionnalité de connexion à votre application Blazor Server" +'og:description': "Ce guide explique comment intégrer Auth0 à n’importe quelle application Blazor Server, nouvelle ou existante, à l’aide de la trousse SDK Auth0.AspNetCore.Authentication." +'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/asp.png" +'twitter:title': "Ajouter une fonctionnalité de connexion à votre application Blazor Server" +'twitter:description': "Ce guide explique comment intégrer Auth0 à n’importe quelle application Blazor Server, nouvelle ou existante, à l’aide de la trousse SDK Auth0.AspNetCore.Authentication." +sidebarTitle: ASP.NET Core Blazor Server +--- + + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + +import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx" +import Login from "/snippets/quickstart/webapp/aspnet-core-blazor-server/Login.cshtml.cs.mdx" +import Logout from "/snippets/quickstart/webapp/aspnet-core-blazor-server/Logout.cshtml.cs.mdx" + +export const sections = [ + { id: "configuration-d-auth0", title: "Configuration d’Auth0" }, + { id: "installer-et-configurer-la-trousse-sdk", title: "Installer et configurer la trousse SDK" }, + { id: "connexion", title: "Connexion" }, + { id: "afficher-le-profil-utilisateur", title: "Afficher le profil utilisateur" }, + { id: "déconnexion", title: "Déconnexion" } +] + + + + Auth0 vous permet d’ajouter rapidement l’authentification et de pouvoir accéder aux informations relatives au profil utilisateur dans votre application. Ce guide explique comment intégrer Auth0 à n’importe quelle application Blazor Server, nouvelle ou existante, à l’aide de la trousse SDK **Auth0.AspNetCore.Authentication**. + +
+ Pour utiliser les services Auth0, vous devez avoir une application installée dans Auth0 Dashboard. L’application Auth0 est l’endroit où vous allez configurer le fonctionnement de l’authentification pour le projet que vous développez. + + ### Configurer une application + + Utilisez le sélecteur interactif pour créer une nouvelle application Auth0 ou sélectionner une application existante qui représente le projet avec lequel vous souhaitez effectuer l’intégration. Dans Auth0, il est attribué à chaque application un identifiant client unique alphanumérique que votre code d’application utilisera pour appeler les API Auth0 via la trousse SDK. + + Tous les paramètres que vous configurez à l’aide de ce démarrage rapide seront automatiquement mis à jour pour votre application dans le [Dashboard](https://manage.auth0.com/dashboard/us/auth0-dsepaid/), qui est l’endroit où vous pourrez gérer vos Applications à l’avenir. + + Si vous préférez explorer une configuration complète, consultez plutôt un exemple d’application. + + ### Configuration des URL de rappel + + Une URL de rappel est une URL intégrée dans votre application vers laquelle vous souhaitez qu’Auth0 redirige les utilisateurs après leur authentification. Si elle n’est pas définie, les utilisateurs ne seront pas redirigés vers votre application après s’être connectés. + + + Si vous suivez notre exemple de projet, définissez cette URL comme suit : `http://localhost:3000``/callback`. + + + ### Configuration des URL de déconnexion + + Une URL de déconnexion est une URL intégrée dans votre application vers laquelle vous souhaitez qu’Auth0 redirige les utilisateurs après leur déconnexion. Si elle n’est pas définie, les utilisateurs ne pourront pas se déconnecter de votre application et recevront un message d’erreur. + + + Si vous suivez notre exemple de projet, définissez cette URL comme suit : `http://localhost:3000`. + +
+ +
+ ### Installer à partir de Nuget + + Pour intégrer Auth0 à Blazor Server vous pouvez utiliser notre trousse SDK en installant le [package Nuget](https://www.nuget.org/packages/Auth0.AspNetCore.Authentication/)`Auth0.AspNetCore.Authentication`dans votre application. + + ### Configurer le logiciel médiateur + + Pour activer l’authentification dans votre application Blazor Server, utilisez le logiciel médiateur fourni par la trousse SDK. Allez dans le fichier `Program.cs` et appelez `builder.Services.AddAuth0WebAppAuthentication()` pour enregistrer le logiciel médiateur de la trousse SDK. + + Assurez-vous de configurer `Domain` et `ClientId`, car ce sont des champs requis pour garantir que la trousse SDK sache quel locataire Auth0 et quelle application utiliser. + + Assurez-vous d’avoir activé l’authentification et l’autorisation dans votre fichier `Program.cs`. +
+ +
+ Pour permettre aux utilisateurs de se connecter à votre application Blazor Server, ajoutez un `LoginModel` à votre répertoire `Pages`. + + Dans le cadre de la méthode `OnGet` de `LoginModel`, appelez `HTTPContext.ChallengeAsync()` et passez `Auth0Constants.AuthenticationScheme` comme schéma d’authentification. Cela fera appel au gestionnaire d’authentification OIDC que notre trousse SDK enregistre en interne. Assurez-vous également d’indiquer les `authenticationProperties` correspondantes, que vous pouvez construire en utilisant `LoginAuthenticationPropertiesBuilder`. + + Après avoir appelé avec succès `HttpContext.ChallengeAsync()`, l’utilisateur est redirigé vers Auth0 et est connecté à la fois au logiciel médiateur OIDC et au logiciel médiateur de témoin après avoir été redirigé vers votre application. Cela permettra aux utilisateurs d’être authentifiés lors des requêtes suivantes. + + + ##### Point de contrôle + Maintenant que vous avez configuré la fonction de connexion, lancez votre application pour vérifier que: + naviguer vers votre page `Login` vous redirigera vers Auth0, + saisir vos identifiants vous redirigera vers votre application. + +
+ +
+ Une fois que le logiciel médiateur a réussi à récupérer les jetons auprès d’Auth0, il extrait les informations et les demandes de l’utilisateur du jeton d’ID et les met à disposition via `AuthenticationState`, que vous pouvez ajouter en tant que `CascadingParameter`. + + Vous pouvez créer une page de profil utilisateur personnalisée pour afficher le nom de l’utilisateur, ainsi que des demandes supplémentaires (comme le courriel et la photo), en récupérant les informations correspondantes à partir de la propriété `User` de `AuthenticationState` et en les visualisant à partir du code Blazor. + + + ##### Point de contrôle + Maintenant que vous avez effectué la configuration pour afficher le profil utilisateur, lancez votre application pour vérifier que: + la navigation vers le point de terminaison contenant le profil après une connexion réussie permet d’afficher le profil utilisateur. + +
+ +
+ Déconnecter l’utilisateur de votre propre application peut se faire en appelant `HttpContext.SignOutAsync` avec le schéma d’authentification `CookieAuthenticationDefaults.AuthenticationScheme` à partir de la méthode `OnGet`de `LogoutModel`. + + En outre, si vous souhaitez également déconnecter l’utilisateur d’Auth0 (cette action peut également le déconnecter d’autres applications qui utilisent l’authentification unique), appelez `HttpContext.SignOutAsync` avec le schéma d’authentification `Auth0Constants.AuthenticationScheme` ainsi que l’`authenticationProperties` approprié qui peut être construit en utilisant `LogoutAuthenticationPropertiesBuilder`. + + + ##### Point de contrôle + Maintenant que vous avez configuré la fonction de déconnexion, exécutez votre application pour vérifier que: + Naviguer vers votre page `Logout` garantira que l’utilisateur est déconnecté. + Lorsque vous vous déconnectez également d’Auth0, vous devriez être redirigé vers Auth0, puis immédiatement renvoyé vers votre propre application. + +
+ + ## Étapes suivantes + + Beau travail! Si vous en êtes arrivé là, vous devriez avoir la connexion, la déconnexion et les informations de profil utilisateur actives dans votre application. + + Cela conclut notre tutoriel de démarrage rapide, mais il y a tellement plus à explorer. Pour en savoir plus sur ce que vous pouvez faire avec Auth0, consultez : + + * [Auth0 Dashboard](https://manage.auth0.com/#) : apprenez à configurer et gérer votre locataire et vos applications Auth0 + * [Trousse SDK auth0-aspnetcore-authentication](https://github.com/auth0/auth0-aspnetcore-authentication) : explorez en détail la trousse SDK utilisée dans ce tutoriel + * [Auth0 Marketplace](https://marketplace.auth0.com/) : découvrez des intégrations que vous pouvez activer pour étendre les fonctionnalités d’Auth0 +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
diff --git a/main/docs/fr-ca/quickstart/webapp/aspnet-core/interactive.mdx b/main/docs/fr-ca/quickstart/webapp/aspnet-core/interactive.mdx index 8885a03a1..2529b2b1e 100644 --- a/main/docs/fr-ca/quickstart/webapp/aspnet-core/interactive.mdx +++ b/main/docs/fr-ca/quickstart/webapp/aspnet-core/interactive.mdx @@ -1,151 +1,153 @@ ---- -title: "Ajouter une fonctionnalité de connexion à votre application ASP.NET MVC" -permalink: "interactive" -'description': "Ce guide explique comment intégrer Auth0 à n’importe quelle application ASP.NET MVC, nouvelle ou existante, à l’aide de la trousse SDK Auth0.AspNetCore.Authentication." -'og:title': "Ajouter une fonctionnalité de connexion à votre application ASP.NET MVC" -'og:description': "Ce guide explique comment intégrer Auth0 à n’importe quelle application ASP.NET MVC, nouvelle ou existante, à l’aide de la trousse SDK Auth0.AspNetCore.Authentication." -'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/asp.png" -'twitter:title': "Ajouter une fonctionnalité de connexion à votre application ASP.NET MVC" -'twitter:description': "Ce guide explique comment intégrer Auth0 à n’importe quelle application ASP.NET MVC, nouvelle ou existante, à l’aide de la trousse SDK Auth0.AspNetCore.Authentication." -sidebarTitle: ASP.NET Core MVC ---- - -import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; -import { LoggedInForm } from "/snippets/Login.jsx"; -import AppSettingsJSON from "/snippets/quickstart/webapp/aspnet-core/appsettings.json.mdx"; -import AccountController from "/snippets/quickstart/webapp/aspnet-core/AccountController.cs.mdx"; - -export const sections = [ - { id: "configuration-d-auth0", title: "Configuration d’Auth0" }, - { id: "installer-et-configurer-la-trousse-sdk", title: "Installer et configurer la trousse SDK" }, - { id: "connexion", title: "Connexion" }, - { id: "afficher-le-profil-utilisateur", title: "Afficher le profil utilisateur" }, - { id: "déconnexion", title: "Déconnexion" } -] - - - - Auth0 vous permet d’ajouter rapidement l’authentification et de pouvoir accéder aux informations relatives au profil utilisateur dans votre application. Ce guide explique comment intégrer Auth0 à n’importe quelle application ASP.NET MVC, nouvelle ou existante, à l’aide de la trousse SDK **Auth0.AspNetCore.Authentication**. - -
- Pour utiliser les services Auth0, vous devez avoir une application installée dans Auth0 Dashboard. L’application Auth0 est l’endroit où vous allez configurer le fonctionnement de l’authentification pour le projet que vous développez. - - ### Configurer une application - - Utilisez le sélecteur interactif pour créer une nouvelle application Auth0 ou sélectionner une application existante qui représente le projet avec lequel vous souhaitez effectuer l’intégration. Dans Auth0, chaque application se voit attribuer un identifiant client unique alphanumérique que votre code d’application utilisera pour appeler les API Auth0 via la trousse SDK. - - Tous les paramètres que vous configurez à l’aide de ce guide rapide seront automatiquement mis à jour pour votre application dans le [Tableau de bord](https://manage.auth0.com/#/), qui est l’endroit où vous pourrez gérer vos applications à l’avenir. - - Si vous préférez explorer une configuration complète, consultez plutôt un exemple d’application. - - ### Configuration des URL de rappel - - Une URL de rappel est une URL intégrée dans votre application vers laquelle vous souhaitez qu’Auth0 redirige les utilisateurs après leur authentification. Si elle n’est pas définie, les utilisateurs ne seront pas redirigés vers votre application après s’être connectés. - - - Si vous suivez notre projet à titre d’exemple, définissez ceci sur `http://localhost:3000/callback`. - - - ### Configuration des URL de déconnexion - - Une URL de déconnexion est une URL intégrée dans votre application vers laquelle vous souhaitez qu’Auth0 redirige les utilisateurs après leur déconnexion. Si elle n’est pas définie, les utilisateurs ne pourront pas se déconnecter de votre application et recevront un message d’erreur. - - - Si vous suivez notre projet à titre d’exemple, définissez ceci sur `http://localhost:3000`. - -
- -
- ### Installer à partir de Nuget - - Pour intégrer Auth0 à ASP.NET Core, vous pouvez utiliser notre trousse SDK en installant le [package Nuget](https://www.nuget.org/packages/Auth0.AspNetCore.Authentication/)`Auth0.AspNetCore.Authentication`dans votre application. - - ### Configurer le logiciel médiateur - - Pour activer l’authentification dans votre application ASP.NET Core, utilisez le logiciel médiateur fourni par la trousse SDK. Allez dans le fichier `Program.cs` et appelez `builder.Services.AddAuth0WebAppAuthentication()` pour enregistrer le logiciel médiateur de la trousse SDK. - - Assurez-vous de configurer `Domain` et `ClientId`, car ce sont des champs requis pour garantir que la trousse SDK sache quel locataire Auth0 et quelle application utiliser. - - Assurez-vous d’avoir activé l’authentification et l’autorisation dans votre fichier `Program.cs`. -
- -
- Pour permettre aux utilisateurs de se connecter à votre application ASP.NET MVC, ajoutez une action `Login` à votre contrôleur. - - Appelez `HTTPContext.ChallengeAsync()` et transmettez `Auth0Constants.AuthenticationScheme` comme schéma d’authentification. Cela fera appel au gestionnaire d’authentification OIDC que notre trousse SDK enregistre en interne. Assurez-vous également d’indiquer les `authenticationProperties` correspondantes, que vous pouvez construire en utilisant `LoginAuthenticationPropertiesBuilder`. - - Après avoir appelé avec succès `HTTPContext.ChallengeAsync()`, l’utilisateur est redirigé vers Auth0 et est connecté à la fois au logiciel médiateur OIDC et au logiciel médiateur de témoin après avoir été redirigé vers votre application. Cela permettra aux utilisateurs d’être authentifiés lors des requêtes suivantes. - - - ##### Point de contrôle - Maintenant que vous avez configuré la fonction de connexion, lancez votre application pour vérifier que: - naviguer vers votre action `Login` vous redirigera vers Auth0, - saisir vos identifiants vous redirigera vers votre application. - -
- -
- Une fois que l’intergiciel a réussi à récupérer les jetons auprès d’Auth0, il extrait les informations et les demandes de l’utilisateur du jeton d’ID et les met à disposition en tant que propriété `User.Claims` sur le contrôleur. - - Vous pouvez créer une page de profil utilisateur personnalisée pour afficher le nom, l’adresse courriel et l’image de profil d’un utilisateur, en récupérant les informations correspondantes de `User` et en les visualisant à partir de votre contrôleur. - - - ##### Point de contrôle - Maintenant que vous avez configuré votre action pour afficher le profil de l’utilisateur, lancez votre application pour vérifier que: - naviguer vers votre action `Profile` après vous être connecté avec succès affiche le profil de l’utilisateur. - -
- -
- Déconnecter l’utilisateur de votre propre application peut se faire en appelant `HttpContext.SignOutAsync` avec le schéma d’authentification `CookieAuthenticationDefaults.AuthenticationScheme` à partir de l’action de votre contrôleur. - - En outre, si vous souhaitez également déconnecter l’utilisateur d’Auth0 (cette action peut également le déconnecter d’autres applications qui utilisent l’authentification unique), appelez `HttpContext.SignOutAsync` avec le schéma d’authentification `Auth0Constants.AuthenticationScheme` ainsi que les `authenticationProperties` appropriées qui peuvent être développées en utilisant `LogoutAuthenticationPropertiesBuilder`. - - - ##### Point de contrôle - Maintenant que vous avez configuré la fonction de déconnexion, exécutez votre application pour vérifier que: - Naviguer vers votre action `Logout` garantit que l’utilisateur est déconnecté. - Lorsque vous vous déconnectez également d’Auth0, vous devriez être redirigé vers Auth0, puis immédiatement renvoyé vers votre propre application. - -
- - ## Étapes suivantes - - Beau travail! Si vous en êtes arrivé là, vous devriez avoir la connexion, la déconnexion et les informations de profil utilisateur actives dans votre application. - - Cela conclut notre tutoriel de démarrage rapide, mais il y a tellement plus à explorer. Pour en savoir plus sur ce que vous pouvez faire avec Auth0, consultez : - - * [Auth0 Dashboard](https://manage.auth0.com/#) : apprenez à configurer et gérer votre locataire et vos applications Auth0 - * [Trousse SDK auth0-aspnetcore-authentication](https://github.com/auth0/auth0-aspnetcore-authentication) : explorez en détail la trousse SDK utilisée dans ce tutoriel - * [Auth0 Marketplace](https://marketplace.auth0.com/) : découvrez des intégrations que vous pouvez activer pour étendre les fonctionnalités d’Auth0 -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+--- +title: "Ajouter une fonctionnalité de connexion à votre application ASP.NET MVC" +permalink: "interactive" +'description': "Ce guide explique comment intégrer Auth0 à n’importe quelle application ASP.NET MVC, nouvelle ou existante, à l’aide de la trousse SDK Auth0.AspNetCore.Authentication." +'og:title': "Ajouter une fonctionnalité de connexion à votre application ASP.NET MVC" +'og:description': "Ce guide explique comment intégrer Auth0 à n’importe quelle application ASP.NET MVC, nouvelle ou existante, à l’aide de la trousse SDK Auth0.AspNetCore.Authentication." +'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/asp.png" +'twitter:title': "Ajouter une fonctionnalité de connexion à votre application ASP.NET MVC" +'twitter:description': "Ce guide explique comment intégrer Auth0 à n’importe quelle application ASP.NET MVC, nouvelle ou existante, à l’aide de la trousse SDK Auth0.AspNetCore.Authentication." +sidebarTitle: ASP.NET Core MVC +--- + +import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; +import { LoggedInForm } from "/snippets/Login.jsx"; +import AppSettingsJSON from "/snippets/quickstart/webapp/aspnet-core/appsettings.json.mdx"; +import AccountController from "/snippets/quickstart/webapp/aspnet-core/AccountController.cs.mdx"; + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + +export const sections = [ + { id: "configuration-d-auth0", title: "Configuration d’Auth0" }, + { id: "installer-et-configurer-la-trousse-sdk", title: "Installer et configurer la trousse SDK" }, + { id: "connexion", title: "Connexion" }, + { id: "afficher-le-profil-utilisateur", title: "Afficher le profil utilisateur" }, + { id: "déconnexion", title: "Déconnexion" } +] + + + + Auth0 vous permet d’ajouter rapidement l’authentification et de pouvoir accéder aux informations relatives au profil utilisateur dans votre application. Ce guide explique comment intégrer Auth0 à n’importe quelle application ASP.NET MVC, nouvelle ou existante, à l’aide de la trousse SDK **Auth0.AspNetCore.Authentication**. + +
+ Pour utiliser les services Auth0, vous devez avoir une application installée dans Auth0 Dashboard. L’application Auth0 est l’endroit où vous allez configurer le fonctionnement de l’authentification pour le projet que vous développez. + + ### Configurer une application + + Utilisez le sélecteur interactif pour créer une nouvelle application Auth0 ou sélectionner une application existante qui représente le projet avec lequel vous souhaitez effectuer l’intégration. Dans Auth0, chaque application se voit attribuer un identifiant client unique alphanumérique que votre code d’application utilisera pour appeler les API Auth0 via la trousse SDK. + + Tous les paramètres que vous configurez à l’aide de ce guide rapide seront automatiquement mis à jour pour votre application dans le [Tableau de bord](https://manage.auth0.com/#/), qui est l’endroit où vous pourrez gérer vos applications à l’avenir. + + Si vous préférez explorer une configuration complète, consultez plutôt un exemple d’application. + + ### Configuration des URL de rappel + + Une URL de rappel est une URL intégrée dans votre application vers laquelle vous souhaitez qu’Auth0 redirige les utilisateurs après leur authentification. Si elle n’est pas définie, les utilisateurs ne seront pas redirigés vers votre application après s’être connectés. + + + Si vous suivez notre projet à titre d’exemple, définissez ceci sur `http://localhost:3000/callback`. + + + ### Configuration des URL de déconnexion + + Une URL de déconnexion est une URL intégrée dans votre application vers laquelle vous souhaitez qu’Auth0 redirige les utilisateurs après leur déconnexion. Si elle n’est pas définie, les utilisateurs ne pourront pas se déconnecter de votre application et recevront un message d’erreur. + + + Si vous suivez notre projet à titre d’exemple, définissez ceci sur `http://localhost:3000`. + +
+ +
+ ### Installer à partir de Nuget + + Pour intégrer Auth0 à ASP.NET Core, vous pouvez utiliser notre trousse SDK en installant le [package Nuget](https://www.nuget.org/packages/Auth0.AspNetCore.Authentication/)`Auth0.AspNetCore.Authentication`dans votre application. + + ### Configurer le logiciel médiateur + + Pour activer l’authentification dans votre application ASP.NET Core, utilisez le logiciel médiateur fourni par la trousse SDK. Allez dans le fichier `Program.cs` et appelez `builder.Services.AddAuth0WebAppAuthentication()` pour enregistrer le logiciel médiateur de la trousse SDK. + + Assurez-vous de configurer `Domain` et `ClientId`, car ce sont des champs requis pour garantir que la trousse SDK sache quel locataire Auth0 et quelle application utiliser. + + Assurez-vous d’avoir activé l’authentification et l’autorisation dans votre fichier `Program.cs`. +
+ +
+ Pour permettre aux utilisateurs de se connecter à votre application ASP.NET MVC, ajoutez une action `Login` à votre contrôleur. + + Appelez `HTTPContext.ChallengeAsync()` et transmettez `Auth0Constants.AuthenticationScheme` comme schéma d’authentification. Cela fera appel au gestionnaire d’authentification OIDC que notre trousse SDK enregistre en interne. Assurez-vous également d’indiquer les `authenticationProperties` correspondantes, que vous pouvez construire en utilisant `LoginAuthenticationPropertiesBuilder`. + + Après avoir appelé avec succès `HTTPContext.ChallengeAsync()`, l’utilisateur est redirigé vers Auth0 et est connecté à la fois au logiciel médiateur OIDC et au logiciel médiateur de témoin après avoir été redirigé vers votre application. Cela permettra aux utilisateurs d’être authentifiés lors des requêtes suivantes. + + + ##### Point de contrôle + Maintenant que vous avez configuré la fonction de connexion, lancez votre application pour vérifier que: + naviguer vers votre action `Login` vous redirigera vers Auth0, + saisir vos identifiants vous redirigera vers votre application. + +
+ +
+ Une fois que l’intergiciel a réussi à récupérer les jetons auprès d’Auth0, il extrait les informations et les demandes de l’utilisateur du jeton d’ID et les met à disposition en tant que propriété `User.Claims` sur le contrôleur. + + Vous pouvez créer une page de profil utilisateur personnalisée pour afficher le nom, l’adresse courriel et l’image de profil d’un utilisateur, en récupérant les informations correspondantes de `User` et en les visualisant à partir de votre contrôleur. + + + ##### Point de contrôle + Maintenant que vous avez configuré votre action pour afficher le profil de l’utilisateur, lancez votre application pour vérifier que: + naviguer vers votre action `Profile` après vous être connecté avec succès affiche le profil de l’utilisateur. + +
+ +
+ Déconnecter l’utilisateur de votre propre application peut se faire en appelant `HttpContext.SignOutAsync` avec le schéma d’authentification `CookieAuthenticationDefaults.AuthenticationScheme` à partir de l’action de votre contrôleur. + + En outre, si vous souhaitez également déconnecter l’utilisateur d’Auth0 (cette action peut également le déconnecter d’autres applications qui utilisent l’authentification unique), appelez `HttpContext.SignOutAsync` avec le schéma d’authentification `Auth0Constants.AuthenticationScheme` ainsi que les `authenticationProperties` appropriées qui peuvent être développées en utilisant `LogoutAuthenticationPropertiesBuilder`. + + + ##### Point de contrôle + Maintenant que vous avez configuré la fonction de déconnexion, exécutez votre application pour vérifier que: + Naviguer vers votre action `Logout` garantit que l’utilisateur est déconnecté. + Lorsque vous vous déconnectez également d’Auth0, vous devriez être redirigé vers Auth0, puis immédiatement renvoyé vers votre propre application. + +
+ + ## Étapes suivantes + + Beau travail! Si vous en êtes arrivé là, vous devriez avoir la connexion, la déconnexion et les informations de profil utilisateur actives dans votre application. + + Cela conclut notre tutoriel de démarrage rapide, mais il y a tellement plus à explorer. Pour en savoir plus sur ce que vous pouvez faire avec Auth0, consultez : + + * [Auth0 Dashboard](https://manage.auth0.com/#) : apprenez à configurer et gérer votre locataire et vos applications Auth0 + * [Trousse SDK auth0-aspnetcore-authentication](https://github.com/auth0/auth0-aspnetcore-authentication) : explorez en détail la trousse SDK utilisée dans ce tutoriel + * [Auth0 Marketplace](https://marketplace.auth0.com/) : découvrez des intégrations que vous pouvez activer pour étendre les fonctionnalités d’Auth0 +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
diff --git a/main/docs/fr-ca/quickstart/webapp/aspnet-owin/interactive.mdx b/main/docs/fr-ca/quickstart/webapp/aspnet-owin/interactive.mdx index 06e3a18bd..635a0c63e 100644 --- a/main/docs/fr-ca/quickstart/webapp/aspnet-owin/interactive.mdx +++ b/main/docs/fr-ca/quickstart/webapp/aspnet-owin/interactive.mdx @@ -1,181 +1,184 @@ ---- -title: "Ajouter une fonctionnalité de connexion à votre application ASP.NET OWIN" -permalink: "interactive" -'description': "Ce guide explique comment intégrer Auth0 à n’importe quelle application ASP.NET OWIN, nouvelle ou ancienne, à l’aide du package NuGet Microsoft.Owin.Security.OpenIdConnect." -'og:title': "Ajouter une fonctionnalité de connexion à votre application ASP.NET OWIN" -'og:description': "Ce guide explique comment intégrer Auth0 à n’importe quelle application ASP.NET OWIN, nouvelle ou ancienne, à l’aide du package NuGet Microsoft.Owin.Security.OpenIdConnect." -'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/asp.png" -'twitter:title': "Ajouter une fonctionnalité de connexion à votre application ASP.NET OWIN" -'twitter:description': "Ce guide explique comment intégrer Auth0 à n’importe quelle application ASP.NET OWIN, nouvelle ou ancienne, à l’aide du package NuGet Microsoft.Owin.Security.OpenIdConnect." -sidebarTitle: ASP.NET OWIN ---- - -import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx" -import WebConfig from "/snippets/quickstart/webapp/aspnet-owin/web-config.mdx" -import AccountController1 from "/snippets/quickstart/webapp/aspnet-owin/AccountController1.mdx" -import AccountController2 from "/snippets/quickstart/webapp/aspnet-owin/AccountController2.mdx" -import AccountController3 from "/snippets/quickstart/webapp/aspnet-owin/AccountController3.mdx" - -export const sections = [ - { id: "configuration-d-auth0", title: "Configuration d’Auth0" }, - { id: "configurer-le-projet", title: "Configurer le projet" }, - { id: "configurer-le-logiciel-médiateur", title: "Configurer le logiciel médiateur" }, - { id: "ajouter-une-fonctionnalité-de-connexion-à-votre-application", title: "Ajouter une fonctionnalité de connexion à votre application" }, - { id: "ajouter-une-fonctionnalité-de-déconnexion-à-votre-application", title: "Ajouter une fonctionnalité de déconnexion à votre application" }, - { id: "afficher-les-informations-du-profil-utilisateur", title: "Afficher les informations du profil utilisateur" } -] - - - - Auth0 vous permet d’ajouter rapidement l’authentification et de pouvoir accéder aux informations relatives au profil utilisateur dans votre application. Ce guide explique comment intégrer Auth0 à n’importe quelle application ASP.NET OWIN, nouvelle ou ancienne, en utilisant le package Nuget `Microsoft.Owin.Security.OpenIdConnect`. - -
- Pour utiliser les services Auth0, vous devez avoir une application installée dans Auth0 Dashboard. L’application Auth0 est l’endroit où vous allez configurer le fonctionnement de l’authentification pour le projet que vous développez. - - ### Configurer une application - - Utilisez le sélecteur interactif pour créer une nouvelle application Auth0 ou sélectionner une application existante qui représente le projet avec lequel vous souhaitez effectuer l’intégration. Dans Auth0, il est attribué à chaque application un identifiant client unique alphanumérique que votre code d’application utilisera pour appeler les API Auth0 via la trousse SDK. - - Tous les paramètres que vous configurez à l’aide de ce démarrage rapide seront automatiquement mis à jour pour votre application dans le [Dashboard](https://manage.auth0.com/#/), qui est l’endroit où vous pourrez gérer vos Applications à l’avenir. - - Si vous préférez explorer une configuration complète, consultez plutôt un exemple d’application. - - ### Configuration des URL de rappel - - Une URL de rappel est une URL intégrée dans votre application vers laquelle vous souhaitez qu’Auth0 redirige les utilisateurs après leur authentification. Si elle n’est pas définie, les utilisateurs ne seront pas redirigés vers votre application après s’être connectés. - - - Si vous suivez notre exemple de projet, définissez cette URL comme suit : `http://localhost:3000``/callback`. - - - ### Configuration des URL de déconnexion - - Une URL de déconnexion est une URL intégrée dans votre application vers laquelle vous souhaitez qu’Auth0 redirige les utilisateurs après leur déconnexion. Si elle n’est pas définie, les utilisateurs ne pourront pas se déconnecter de votre application et recevront un message d’erreur. - - - Si vous suivez notre exemple de projet, définissez cette URL comme suit : `http://localhost:3000`. - -
- -
- ### Installer à partir de Nuget - - Pour intégrer Auth0 avec ASP.NET OWIN, vous pouvez utiliser les packages Nuget `Microsoft.Owin.Security.OpenIdConnect` et `Microsoft.Owin.Security.Cookies`. - - ``` - Install-Package Microsoft.Owin.Security.OpenIdConnect - Install-Package Microsoft.Owin.Security.Cookies - ``` - - - Des problèmes surviennent lorsque vous configurez l’intergiciel de témoin OWIN et les témoins System.Web en même temps. Pour en savoir plus, consultez [la documentation sur les problèmes d’intégration des témoins System.Web](https://github.com/aspnet/AspNetKatana/wiki/System.Web-response-cookie-integration-issues) afin d’atténuer ces problèmes. - - - ### Configurer les identifiants - - Pour que la trousse SDK fonctionne correctement, définissez les propriétés suivantes dans `Web.config` : - - - `auth0:Domain` : Le domaine de votre locataire Auth0. Celui-ci figure dans Auth0 Dashboard, dans les **Settings (Paramètres)** de votre application dans le champ Domaine. Si vous utilisez un [domaine personnalisé](https://auth0.com/docs/custom-domains), définissez ceci plutôt sur la valeur de votre domaine personnalisé. - - `auth0:ClientId` : L’identifiant de l’application Auth0 que vous avez créée dans Auth0 Dashboard. Celui-ci figure dans Auth0 Dashboard, dans les **Settings (Paramètres)** de votre application dans le champ Identifiant client. -
- -
- Pour activer l’authentification dans votre application ASP.NET OWIN, reportez-vous à la méthode de configuration de votre classe de démarrage et configurez le témoin, ainsi que le logiciel médiateur OIDC. - - Il est essentiel d’enregistrer à la fois le logiciel médiateur de témoin et le logiciel médiateur OpenID Connect, car les deux sont nécessaires (dans cet ordre) pour que l’authentification fonctionne. le logiciel médiateur OpenID Connect gère l’authentification avec Auth0. Une fois que les utilisateurs se sont authentifiés, leur identité est sauvegardée dans le logiciel médiateur de témoin. - - Dans l’extrait de code, AuthenticationType est défini sur **Auth0**. Utilisez AuthenticationType dans la section suivante pour lancer un défi au logiciel médiateur OpenID Connect et commencer le flux d’authentification. L’événement de notification RedirectToIdentityProvider génère la bonne Logout URL (URL de déconnexion). -
- -
- Pour permettre aux utilisateurs de se connecter à votre application ASP.NET OWIN, ajoutez une action `Login`à votre contrôleur. - - Appelez `HttpContext.GetOwinContext().Authentication.Challenge` et passez `Auth0` comme schéma d’authentification. Cette action fait appel au gestionnaire d’authentification OIDC qui a été enregistré plus tôt. Veillez à préciser les `AuthenticationProperties`, y compris un `RedirectUri`i. - - Après avoir appelé avec succès `HttpContext.GetOwinContext().Authentication.Challenge`, l’utilisateur est redirigé vers Auth0 et est connecté à la fois au logiciel médiateur OIDC et au logiciel médiateur de témoin après avoir été redirigé vers votre application. Cela permettra aux utilisateurs d’être authentifiés lors des requêtes suivantes. - - - ##### Point de contrôle - Maintenant que vous avez configuré la fonction de connexion, lancez votre application pour vérifier que: - naviguer vers votre action `Login` vous redirigera vers Auth0, - saisir vos identifiants vous redirigera vers votre application. - -
- -
- À partir de l’action de votre contrôleur, appelez `HttpContext.GetOwinContext().Authentication.SignOut` avec le schéma d’authentification `CookieAuthenticationDefaults.AuthenticationType` pour déconnecter l’utilisateur de votre application. - - De plus, si vous souhaitez déconnecter l’utilisateur d’Auth0 (cette action pourrait également le déconnecter d’autres applications qui dépendent de l’authentification unique), appelez `HttpContext.GetOwinContext().Authentication.SignOut` avec le schéma d’authentification `"Auth0"`. - - - ##### Point de contrôle - Maintenant que vous avez configuré la fonction de déconnexion, exécutez votre application pour vérifier que: - Naviguer vers votre action `Logout` garantit que l’utilisateur est déconnecté. - Lors de la déconnexion, vous êtes redirigé vers Auth0 puis immédiatement renvoyé vers votre application pendant la déconnexion. - -
- -
- Après que l’intergiciel a réussi à récupérer les jetons d’Auth0, il extraira les informations et les demandes de l’utilisateur à partir du jeton d’ID et les met à disposition en tant que `ClaimsIdentity`. Accédez aux informations extraites en utilisant la propriété `User` dans le contrôleur. - - Pour créer un profil utilisateur, récupérez le nom, l’adresse courriel et l’image de profil de l’utilisateur à partir de `User` et visualisez-les à partir de votre contrôleur. - - - ##### Point de contrôle - Maintenant que vous avez configuré votre action pour afficher le profil de l’utilisateur, lancez votre application pour vérifier que: - naviguer vers votre action `Profile` après vous être connecté avec succès affiche le profil de l’utilisateur. - -
- - ## Étapes suivantes - - Beau travail! Si vous en êtes arrivé là, vous devriez avoir la connexion, la déconnexion et les informations de profil utilisateur actives dans votre application. - - Cela conclut notre tutoriel de démarrage rapide, mais il y a tellement plus à explorer. Pour en savoir plus sur ce que vous pouvez faire avec Auth0, consultez : - - * [Auth0 Dashboard](https://manage.auth0.com/#) : apprenez à configurer et gérer votre locataire et vos applications Auth0 - * [Auth0 Marketplace](https://marketplace.auth0.com/) : découvrez des intégrations que vous pouvez activer pour étendre les fonctionnalités d’Auth0 -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+--- +title: "Ajouter une fonctionnalité de connexion à votre application ASP.NET OWIN" +permalink: "interactive" +'description': "Ce guide explique comment intégrer Auth0 à n’importe quelle application ASP.NET OWIN, nouvelle ou ancienne, à l’aide du package NuGet Microsoft.Owin.Security.OpenIdConnect." +'og:title': "Ajouter une fonctionnalité de connexion à votre application ASP.NET OWIN" +'og:description': "Ce guide explique comment intégrer Auth0 à n’importe quelle application ASP.NET OWIN, nouvelle ou ancienne, à l’aide du package NuGet Microsoft.Owin.Security.OpenIdConnect." +'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/asp.png" +'twitter:title': "Ajouter une fonctionnalité de connexion à votre application ASP.NET OWIN" +'twitter:description': "Ce guide explique comment intégrer Auth0 à n’importe quelle application ASP.NET OWIN, nouvelle ou ancienne, à l’aide du package NuGet Microsoft.Owin.Security.OpenIdConnect." +sidebarTitle: ASP.NET OWIN +--- + + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + +import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx" +import WebConfig from "/snippets/quickstart/webapp/aspnet-owin/web-config.mdx" +import AccountController1 from "/snippets/quickstart/webapp/aspnet-owin/AccountController1.mdx" +import AccountController2 from "/snippets/quickstart/webapp/aspnet-owin/AccountController2.mdx" +import AccountController3 from "/snippets/quickstart/webapp/aspnet-owin/AccountController3.mdx" + +export const sections = [ + { id: "configuration-d-auth0", title: "Configuration d’Auth0" }, + { id: "configurer-le-projet", title: "Configurer le projet" }, + { id: "configurer-le-logiciel-médiateur", title: "Configurer le logiciel médiateur" }, + { id: "ajouter-une-fonctionnalité-de-connexion-à-votre-application", title: "Ajouter une fonctionnalité de connexion à votre application" }, + { id: "ajouter-une-fonctionnalité-de-déconnexion-à-votre-application", title: "Ajouter une fonctionnalité de déconnexion à votre application" }, + { id: "afficher-les-informations-du-profil-utilisateur", title: "Afficher les informations du profil utilisateur" } +] + + + + Auth0 vous permet d’ajouter rapidement l’authentification et de pouvoir accéder aux informations relatives au profil utilisateur dans votre application. Ce guide explique comment intégrer Auth0 à n’importe quelle application ASP.NET OWIN, nouvelle ou ancienne, en utilisant le package Nuget `Microsoft.Owin.Security.OpenIdConnect`. + +
+ Pour utiliser les services Auth0, vous devez avoir une application installée dans Auth0 Dashboard. L’application Auth0 est l’endroit où vous allez configurer le fonctionnement de l’authentification pour le projet que vous développez. + + ### Configurer une application + + Utilisez le sélecteur interactif pour créer une nouvelle application Auth0 ou sélectionner une application existante qui représente le projet avec lequel vous souhaitez effectuer l’intégration. Dans Auth0, il est attribué à chaque application un identifiant client unique alphanumérique que votre code d’application utilisera pour appeler les API Auth0 via la trousse SDK. + + Tous les paramètres que vous configurez à l’aide de ce démarrage rapide seront automatiquement mis à jour pour votre application dans le [Dashboard](https://manage.auth0.com/#/), qui est l’endroit où vous pourrez gérer vos Applications à l’avenir. + + Si vous préférez explorer une configuration complète, consultez plutôt un exemple d’application. + + ### Configuration des URL de rappel + + Une URL de rappel est une URL intégrée dans votre application vers laquelle vous souhaitez qu’Auth0 redirige les utilisateurs après leur authentification. Si elle n’est pas définie, les utilisateurs ne seront pas redirigés vers votre application après s’être connectés. + + + Si vous suivez notre exemple de projet, définissez cette URL comme suit : `http://localhost:3000``/callback`. + + + ### Configuration des URL de déconnexion + + Une URL de déconnexion est une URL intégrée dans votre application vers laquelle vous souhaitez qu’Auth0 redirige les utilisateurs après leur déconnexion. Si elle n’est pas définie, les utilisateurs ne pourront pas se déconnecter de votre application et recevront un message d’erreur. + + + Si vous suivez notre exemple de projet, définissez cette URL comme suit : `http://localhost:3000`. + +
+ +
+ ### Installer à partir de Nuget + + Pour intégrer Auth0 avec ASP.NET OWIN, vous pouvez utiliser les packages Nuget `Microsoft.Owin.Security.OpenIdConnect` et `Microsoft.Owin.Security.Cookies`. + + ``` + Install-Package Microsoft.Owin.Security.OpenIdConnect + Install-Package Microsoft.Owin.Security.Cookies + ``` + + + Des problèmes surviennent lorsque vous configurez l’intergiciel de témoin OWIN et les témoins System.Web en même temps. Pour en savoir plus, consultez [la documentation sur les problèmes d’intégration des témoins System.Web](https://github.com/aspnet/AspNetKatana/wiki/System.Web-response-cookie-integration-issues) afin d’atténuer ces problèmes. + + + ### Configurer les identifiants + + Pour que la trousse SDK fonctionne correctement, définissez les propriétés suivantes dans `Web.config` : + + - `auth0:Domain` : Le domaine de votre locataire Auth0. Celui-ci figure dans Auth0 Dashboard, dans les **Settings (Paramètres)** de votre application dans le champ Domaine. Si vous utilisez un [domaine personnalisé](https://auth0.com/docs/custom-domains), définissez ceci plutôt sur la valeur de votre domaine personnalisé. + - `auth0:ClientId` : L’identifiant de l’application Auth0 que vous avez créée dans Auth0 Dashboard. Celui-ci figure dans Auth0 Dashboard, dans les **Settings (Paramètres)** de votre application dans le champ Identifiant client. +
+ +
+ Pour activer l’authentification dans votre application ASP.NET OWIN, reportez-vous à la méthode de configuration de votre classe de démarrage et configurez le témoin, ainsi que le logiciel médiateur OIDC. + + Il est essentiel d’enregistrer à la fois le logiciel médiateur de témoin et le logiciel médiateur OpenID Connect, car les deux sont nécessaires (dans cet ordre) pour que l’authentification fonctionne. le logiciel médiateur OpenID Connect gère l’authentification avec Auth0. Une fois que les utilisateurs se sont authentifiés, leur identité est sauvegardée dans le logiciel médiateur de témoin. + + Dans l’extrait de code, AuthenticationType est défini sur **Auth0**. Utilisez AuthenticationType dans la section suivante pour lancer un défi au logiciel médiateur OpenID Connect et commencer le flux d’authentification. L’événement de notification RedirectToIdentityProvider génère la bonne Logout URL (URL de déconnexion). +
+ +
+ Pour permettre aux utilisateurs de se connecter à votre application ASP.NET OWIN, ajoutez une action `Login`à votre contrôleur. + + Appelez `HttpContext.GetOwinContext().Authentication.Challenge` et passez `Auth0` comme schéma d’authentification. Cette action fait appel au gestionnaire d’authentification OIDC qui a été enregistré plus tôt. Veillez à préciser les `AuthenticationProperties`, y compris un `RedirectUri`i. + + Après avoir appelé avec succès `HttpContext.GetOwinContext().Authentication.Challenge`, l’utilisateur est redirigé vers Auth0 et est connecté à la fois au logiciel médiateur OIDC et au logiciel médiateur de témoin après avoir été redirigé vers votre application. Cela permettra aux utilisateurs d’être authentifiés lors des requêtes suivantes. + + + ##### Point de contrôle + Maintenant que vous avez configuré la fonction de connexion, lancez votre application pour vérifier que: + naviguer vers votre action `Login` vous redirigera vers Auth0, + saisir vos identifiants vous redirigera vers votre application. + +
+ +
+ À partir de l’action de votre contrôleur, appelez `HttpContext.GetOwinContext().Authentication.SignOut` avec le schéma d’authentification `CookieAuthenticationDefaults.AuthenticationType` pour déconnecter l’utilisateur de votre application. + + De plus, si vous souhaitez déconnecter l’utilisateur d’Auth0 (cette action pourrait également le déconnecter d’autres applications qui dépendent de l’authentification unique), appelez `HttpContext.GetOwinContext().Authentication.SignOut` avec le schéma d’authentification `"Auth0"`. + + + ##### Point de contrôle + Maintenant que vous avez configuré la fonction de déconnexion, exécutez votre application pour vérifier que: + Naviguer vers votre action `Logout` garantit que l’utilisateur est déconnecté. + Lors de la déconnexion, vous êtes redirigé vers Auth0 puis immédiatement renvoyé vers votre application pendant la déconnexion. + +
+ +
+ Après que l’intergiciel a réussi à récupérer les jetons d’Auth0, il extraira les informations et les demandes de l’utilisateur à partir du jeton d’ID et les met à disposition en tant que `ClaimsIdentity`. Accédez aux informations extraites en utilisant la propriété `User` dans le contrôleur. + + Pour créer un profil utilisateur, récupérez le nom, l’adresse courriel et l’image de profil de l’utilisateur à partir de `User` et visualisez-les à partir de votre contrôleur. + + + ##### Point de contrôle + Maintenant que vous avez configuré votre action pour afficher le profil de l’utilisateur, lancez votre application pour vérifier que: + naviguer vers votre action `Profile` après vous être connecté avec succès affiche le profil de l’utilisateur. + +
+ + ## Étapes suivantes + + Beau travail! Si vous en êtes arrivé là, vous devriez avoir la connexion, la déconnexion et les informations de profil utilisateur actives dans votre application. + + Cela conclut notre tutoriel de démarrage rapide, mais il y a tellement plus à explorer. Pour en savoir plus sur ce que vous pouvez faire avec Auth0, consultez : + + * [Auth0 Dashboard](https://manage.auth0.com/#) : apprenez à configurer et gérer votre locataire et vos applications Auth0 + * [Auth0 Marketplace](https://marketplace.auth0.com/) : découvrez des intégrations que vous pouvez activer pour étendre les fonctionnalités d’Auth0 +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
diff --git a/main/docs/fr-ca/quickstart/webapp/django/interactive.mdx b/main/docs/fr-ca/quickstart/webapp/django/interactive.mdx index 14bb19fd4..920e0e8c1 100644 --- a/main/docs/fr-ca/quickstart/webapp/django/interactive.mdx +++ b/main/docs/fr-ca/quickstart/webapp/django/interactive.mdx @@ -1,239 +1,241 @@ ---- -title: "Ajouter une fonctionnalité de connexion à votre application Django" -permalink: "interactive" -'description': "Ce guide explique comment intégrer Auth0 à une application Python Django, à l’aide de la trousse SDK Authlib." -'og:title': "Ajouter une fonctionnalité de connexion à votre application Django" -'og:description': "Ce guide explique comment intégrer Auth0 à une application Python Django, à l’aide de la trousse SDK Authlib." -'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/python.png" -'twitter:title': "Ajouter une fonctionnalité de connexion à votre application Django" -'twitter:description': "Ce guide explique comment intégrer Auth0 à une application Python Django, à l’aide de la trousse SDK Authlib." -sidebarTitle: Django ---- - -import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; -import { LoggedInForm } from "/snippets/Login.jsx"; -import HTML from "/snippets/quickstart/webapp/django/templates-index.html.mdx"; -import Settings from "/snippets/quickstart/webapp/django/settings.py.mdx"; -import Urls from "/snippets/quickstart/webapp/django/urls.py.mdx"; -import Views from "/snippets/quickstart/webapp/django/views.py.mdx"; -import Views2 from "/snippets/quickstart/webapp/django/views.py2.mdx"; - -export const sections = [ - { id: "configuration-d-auth0", title: "Configuration d’Auth0" }, - { id: "installer-les-dépendances", title: "Installer les dépendances" }, - { id: "configurez-votre-fichier-env-", title: "Configurez votre fichier .env." }, - { id: "création-d-une-application", title: "Création d’une application" }, - { id: "mettre-à-jour-settings-py", title: "Mettre à jour settings.py" }, - { id: "configurez-votre-application", title: "Configurez votre application" }, - { id: "configurer-vos-gestionnaires-de-route", title: "Configurer vos gestionnaires de route" }, - { id: "enregistrer-vos-routes", title: "Enregistrer vos routes" }, - { id: "ajouter-des-modèles", title: "Ajouter des modèles" }, - { id: "exécuter-votre-application", title: "Exécuter votre application" } -] - - - - Auth0 vous permet d’ajouter l’authentification et de pouvoir accéder aux informations relatives au profil de l’utilisateur dans votre application. Ce guide explique comment intégrer Auth0 à une application Python [Django](https://www.djangoproject.com/), à l’aide de la trousse SDK [Authlib](https://authlib.org/). - -
- Pour utiliser les services Auth0, vous devez avoir une application installée dans Auth0 Dashboard. L’application Auth0 est l’endroit où vous allez configurer le fonctionnement de l’authentification pour le projet que vous développez. - - ### Configurer une application - - Utilisez le sélecteur interactif pour créer une nouvelle application Auth0 ou sélectionner une application existante qui représente le projet avec lequel vous souhaitez effectuer l’intégration. Dans Auth0, chaque application se voit attribuer un identifiant client unique alphanumérique que votre code d’application utilisera pour appeler les API Auth0 via la trousse SDK. - - Tous les paramètres que vous configurez à l’aide de ce guide de démarrage rapide seront automatiquement mis à jour pour votre application dans le [Tableau de bord](https://manage.auth0.com/dashboard/us/auth0-dsepaid/), qui est l’endroit où vous pourrez gérer vos applications à l’avenir. - - Si vous préférez explorer une configuration complète, consultez plutôt un exemple d’application. - - ### Configurer les URL de rappel - - Une URL de rappel est une URL intégrée dans votre application vers laquelle vous souhaitez qu’Auth0 redirige les utilisateurs après leur authentification. Si elle n’est pas définie, les utilisateurs ne seront pas redirigés vers votre application après s’être connectés. - - - Si vous suivez notre exemple de projet, définissez cette URL comme suit : `http://localhost:3000``/callback`. - - - ### Configuration des URL de déconnexion - - Une URL de déconnexion est une URL intégrée dans votre application vers laquelle vous souhaitez qu’Auth0 redirige les utilisateurs après leur déconnexion. Si elle n’est pas définie, les utilisateurs ne pourront pas se déconnecter de votre application et recevront un message d’erreur. - - - Si vous suivez notre exemple de projet, définissez cette URL comme suit : `http://localhost:3000`. - -
- -
- Pour cette intégration, vous ajouterez plusieurs dépendances de bibliothèque, telles qu’Authlib. Créez un fichier `requirements.txt` dans votre répertoire de projet et incluez ce qui suit : - - ``` - authlib ~= 1.0 - django ~= 4.0 - python-dotenv ~= 0.19 - requests ~= 2.27 - ``` - - Exécutez la commande suivante depuis votre interface système pour accéder à ces dépendances : - - `pip install -r requirements.txt` -
- -
- Ensuite, créez un fichier `.env` dans votre répertoire de projet. Ce fichier contiendra les clés de vos clients et d’autres détails de configuration. - - ``` - AUTH0_CLIENT_ID={yourClientId} - AUTH0_CLIENT_SECRET={yourClientSecret} - AUTH0_DOMAIN={yourDomain} - ``` -
- -
- Si vous avez déjà une application Django installée, passez à l’étape suivante. Pour un nouveau projet d’application, exécutez la commande suivante : - - `django-admin startproject webappexample` - - Placez-vous dans le nouveau dossier du projet : - - `cd webappexample` -
- -
- Ouvrez le fichier `webappexample/settings.py` pour examiner les valeurs `.env`. - - En haut du fichier, ajoutez les importations `os` et `dotenv`. - - Ensuite, sous la définition `BASE_DIR`, ajoutez la variable `TEMPLATE_DIR`. - - Ensuite, trouvez la variable `TEMPLATES` et mettez à jour la valeur `DIRS` pour y ajouter notre chaîne `TEMPLATE_DIR`. Cette action détermine le chemin des fichiers modèles, que vous créerez à une étape future. Ne modifiez aucun autre élément de ce tableau. - - À la fin de ce fichier, ajoutez le code pour charger la configuration d’Auth0. -
- -
- Pour commencer à créer votre application, ouvrez le fichier `webappexample/views.py` dans votre IDE. - - Importez toutes les bibliothèques nécessaires à votre application. - - Vous pouvez maintenant configurer Authlib pour gérer l’authentification de votre application avec Auth0. - - Découvrez les options de configuration possibles pour la méthode Authlib’s OAuth `register()` à partir de [leur documentation.](https://docs.authlib.org/en/latest/client/frameworks.html#using-oauth-2-0-to-log-in) -
- -
- Dans cet exemple, vous allez ajouter quatre routes pour votre application : connexion, callback, déconnexion et index. - - - `login` – Lorsque les visiteurs de votre application se rendent sur la route `/login` ils seront redirigés vers Auth0 pour commencer le processus d’authentification. - - `callback` – Après la connexion de vos utilisateurs à Auth0, ceux-ci reviendront à votre application à la route `/callback`. Cette route enregistre la session de l’utilisateur et permet de ne plus avoir à se reconnecter lorsqu’il revient. - - `logout` – La route `/logout` permet aux utilisateurs de se déconnecter de votre application. Cette route efface la session de l’utilisateur dans votre application et redirige vers le point de terminaison de déconnexion d’Auth0 pour s’assurer que la session n’est plus enregistrée. Ensuite, l’application redirige l’utilisateur vers votre route d’accueil. - - `index` – La route d’accueil affichera les détails de l’utilisateur authentifié ou permettra aux visiteurs de se connecter. -
- -
- Remplacez le contenu de votre fichier `webappexample/urls.py` par le code à droite pour vous connecter à ces nouvelles routes. - - Cela dirigera les routes `/login`, `/callback`, `/logout` et `/` vers les gestionnaires appropriés. -
- -
- Vous allez ensuite créer un fichier modèle utilisé dans la route de la page d’accueil. - - Créez un nouveau sous-répertoire dans le dossier `webappexample` nommé `templates`, et créez un fichier `index.html`. - - Le fichier `index.html` contiendra un code modèle pour afficher les informations de l’utilisateur s’il est connecté, ou pour lui présenter un bouton de connexion s’il ne l’est pas. -
- -
- Vous êtes prêts à exécuter votre application! À partir de votre Directory de projet, ouvrez un interface et utilisez : - - ``` - python3 manage.py migrate - python3 manage.py runserver 3000 - ``` - - Votre application devrait maintenant être prête à s’ouvrir à partir de votre navigateur à l’adresse `http://localhost:3000`. - - - ##### Point de contrôle - Visitez [http://localhost:3000](http://localhost:3000/) pour des raisons de vérification. Un bouton de connexion devrait vous permettre de vous connecter à Auth0, puis de revenir à votre application pour consulter les informations relatives à votre profil. - -
- - ## Étapes suivantes - - Beau travail! Si vous en êtes arrivé là, vous devriez avoir la connexion, la déconnexion et les informations de profil utilisateur actives dans votre application. - - Cela conclut notre tutoriel de démarrage rapide, mais il y a tellement plus à explorer. Pour en savoir plus sur ce que vous pouvez faire avec Auth0, consultez : - - * [Auth0 Dashboard](https://manage.auth0.com/#) : apprenez à configurer et gérer votre locataire et vos applications Auth0 - * [Auth0 Marketplace](https://marketplace.auth0.com/) : découvrez des intégrations que vous pouvez activer pour étendre les fonctionnalités d’Auth0 -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+--- +title: "Ajouter une fonctionnalité de connexion à votre application Django" +permalink: "interactive" +'description': "Ce guide explique comment intégrer Auth0 à une application Python Django, à l’aide de la trousse SDK Authlib." +'og:title': "Ajouter une fonctionnalité de connexion à votre application Django" +'og:description': "Ce guide explique comment intégrer Auth0 à une application Python Django, à l’aide de la trousse SDK Authlib." +'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/python.png" +'twitter:title': "Ajouter une fonctionnalité de connexion à votre application Django" +'twitter:description': "Ce guide explique comment intégrer Auth0 à une application Python Django, à l’aide de la trousse SDK Authlib." +sidebarTitle: Django +--- + +import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; +import { LoggedInForm } from "/snippets/Login.jsx"; +import HTML from "/snippets/quickstart/webapp/django/templates-index.html.mdx"; +import Settings from "/snippets/quickstart/webapp/django/settings.py.mdx"; +import Urls from "/snippets/quickstart/webapp/django/urls.py.mdx"; +import Views from "/snippets/quickstart/webapp/django/views.py.mdx"; +import Views2 from "/snippets/quickstart/webapp/django/views.py2.mdx"; + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + +export const sections = [ + { id: "configuration-d-auth0", title: "Configuration d’Auth0" }, + { id: "installer-les-dépendances", title: "Installer les dépendances" }, + { id: "configurez-votre-fichier-env-", title: "Configurez votre fichier .env." }, + { id: "création-d-une-application", title: "Création d’une application" }, + { id: "mettre-à-jour-settings-py", title: "Mettre à jour settings.py" }, + { id: "configurez-votre-application", title: "Configurez votre application" }, + { id: "configurer-vos-gestionnaires-de-route", title: "Configurer vos gestionnaires de route" }, + { id: "enregistrer-vos-routes", title: "Enregistrer vos routes" }, + { id: "ajouter-des-modèles", title: "Ajouter des modèles" }, + { id: "exécuter-votre-application", title: "Exécuter votre application" } +] + + + + Auth0 vous permet d’ajouter l’authentification et de pouvoir accéder aux informations relatives au profil de l’utilisateur dans votre application. Ce guide explique comment intégrer Auth0 à une application Python [Django](https://www.djangoproject.com/), à l’aide de la trousse SDK [Authlib](https://authlib.org/). + +
+ Pour utiliser les services Auth0, vous devez avoir une application installée dans Auth0 Dashboard. L’application Auth0 est l’endroit où vous allez configurer le fonctionnement de l’authentification pour le projet que vous développez. + + ### Configurer une application + + Utilisez le sélecteur interactif pour créer une nouvelle application Auth0 ou sélectionner une application existante qui représente le projet avec lequel vous souhaitez effectuer l’intégration. Dans Auth0, chaque application se voit attribuer un identifiant client unique alphanumérique que votre code d’application utilisera pour appeler les API Auth0 via la trousse SDK. + + Tous les paramètres que vous configurez à l’aide de ce guide de démarrage rapide seront automatiquement mis à jour pour votre application dans le [Tableau de bord](https://manage.auth0.com/dashboard/us/auth0-dsepaid/), qui est l’endroit où vous pourrez gérer vos applications à l’avenir. + + Si vous préférez explorer une configuration complète, consultez plutôt un exemple d’application. + + ### Configurer les URL de rappel + + Une URL de rappel est une URL intégrée dans votre application vers laquelle vous souhaitez qu’Auth0 redirige les utilisateurs après leur authentification. Si elle n’est pas définie, les utilisateurs ne seront pas redirigés vers votre application après s’être connectés. + + + Si vous suivez notre exemple de projet, définissez cette URL comme suit : `http://localhost:3000``/callback`. + + + ### Configuration des URL de déconnexion + + Une URL de déconnexion est une URL intégrée dans votre application vers laquelle vous souhaitez qu’Auth0 redirige les utilisateurs après leur déconnexion. Si elle n’est pas définie, les utilisateurs ne pourront pas se déconnecter de votre application et recevront un message d’erreur. + + + Si vous suivez notre exemple de projet, définissez cette URL comme suit : `http://localhost:3000`. + +
+ +
+ Pour cette intégration, vous ajouterez plusieurs dépendances de bibliothèque, telles qu’Authlib. Créez un fichier `requirements.txt` dans votre répertoire de projet et incluez ce qui suit : + + ``` + authlib ~= 1.0 + django ~= 4.0 + python-dotenv ~= 0.19 + requests ~= 2.27 + ``` + + Exécutez la commande suivante depuis votre interface système pour accéder à ces dépendances : + + `pip install -r requirements.txt` +
+ +
+ Ensuite, créez un fichier `.env` dans votre répertoire de projet. Ce fichier contiendra les clés de vos clients et d’autres détails de configuration. + + ``` + AUTH0_CLIENT_ID={yourClientId} + AUTH0_CLIENT_SECRET={yourClientSecret} + AUTH0_DOMAIN={yourDomain} + ``` +
+ +
+ Si vous avez déjà une application Django installée, passez à l’étape suivante. Pour un nouveau projet d’application, exécutez la commande suivante : + + `django-admin startproject webappexample` + + Placez-vous dans le nouveau dossier du projet : + + `cd webappexample` +
+ +
+ Ouvrez le fichier `webappexample/settings.py` pour examiner les valeurs `.env`. + + En haut du fichier, ajoutez les importations `os` et `dotenv`. + + Ensuite, sous la définition `BASE_DIR`, ajoutez la variable `TEMPLATE_DIR`. + + Ensuite, trouvez la variable `TEMPLATES` et mettez à jour la valeur `DIRS` pour y ajouter notre chaîne `TEMPLATE_DIR`. Cette action détermine le chemin des fichiers modèles, que vous créerez à une étape future. Ne modifiez aucun autre élément de ce tableau. + + À la fin de ce fichier, ajoutez le code pour charger la configuration d’Auth0. +
+ +
+ Pour commencer à créer votre application, ouvrez le fichier `webappexample/views.py` dans votre IDE. + + Importez toutes les bibliothèques nécessaires à votre application. + + Vous pouvez maintenant configurer Authlib pour gérer l’authentification de votre application avec Auth0. + + Découvrez les options de configuration possibles pour la méthode Authlib’s OAuth `register()` à partir de [leur documentation.](https://docs.authlib.org/en/latest/client/frameworks.html#using-oauth-2-0-to-log-in) +
+ +
+ Dans cet exemple, vous allez ajouter quatre routes pour votre application : connexion, callback, déconnexion et index. + + - `login` – Lorsque les visiteurs de votre application se rendent sur la route `/login` ils seront redirigés vers Auth0 pour commencer le processus d’authentification. + - `callback` – Après la connexion de vos utilisateurs à Auth0, ceux-ci reviendront à votre application à la route `/callback`. Cette route enregistre la session de l’utilisateur et permet de ne plus avoir à se reconnecter lorsqu’il revient. + - `logout` – La route `/logout` permet aux utilisateurs de se déconnecter de votre application. Cette route efface la session de l’utilisateur dans votre application et redirige vers le point de terminaison de déconnexion d’Auth0 pour s’assurer que la session n’est plus enregistrée. Ensuite, l’application redirige l’utilisateur vers votre route d’accueil. + - `index` – La route d’accueil affichera les détails de l’utilisateur authentifié ou permettra aux visiteurs de se connecter. +
+ +
+ Remplacez le contenu de votre fichier `webappexample/urls.py` par le code à droite pour vous connecter à ces nouvelles routes. + + Cela dirigera les routes `/login`, `/callback`, `/logout` et `/` vers les gestionnaires appropriés. +
+ +
+ Vous allez ensuite créer un fichier modèle utilisé dans la route de la page d’accueil. + + Créez un nouveau sous-répertoire dans le dossier `webappexample` nommé `templates`, et créez un fichier `index.html`. + + Le fichier `index.html` contiendra un code modèle pour afficher les informations de l’utilisateur s’il est connecté, ou pour lui présenter un bouton de connexion s’il ne l’est pas. +
+ +
+ Vous êtes prêts à exécuter votre application! À partir de votre Directory de projet, ouvrez un interface et utilisez : + + ``` + python3 manage.py migrate + python3 manage.py runserver 3000 + ``` + + Votre application devrait maintenant être prête à s’ouvrir à partir de votre navigateur à l’adresse `http://localhost:3000`. + + + ##### Point de contrôle + Visitez [http://localhost:3000](http://localhost:3000/) pour des raisons de vérification. Un bouton de connexion devrait vous permettre de vous connecter à Auth0, puis de revenir à votre application pour consulter les informations relatives à votre profil. + +
+ + ## Étapes suivantes + + Beau travail! Si vous en êtes arrivé là, vous devriez avoir la connexion, la déconnexion et les informations de profil utilisateur actives dans votre application. + + Cela conclut notre tutoriel de démarrage rapide, mais il y a tellement plus à explorer. Pour en savoir plus sur ce que vous pouvez faire avec Auth0, consultez : + + * [Auth0 Dashboard](https://manage.auth0.com/#) : apprenez à configurer et gérer votre locataire et vos applications Auth0 + * [Auth0 Marketplace](https://marketplace.auth0.com/) : découvrez des intégrations que vous pouvez activer pour étendre les fonctionnalités d’Auth0 +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
diff --git a/main/docs/fr-ca/quickstart/webapp/golang/interactive.mdx b/main/docs/fr-ca/quickstart/webapp/golang/interactive.mdx index b31e6e4bf..647234ebf 100644 --- a/main/docs/fr-ca/quickstart/webapp/golang/interactive.mdx +++ b/main/docs/fr-ca/quickstart/webapp/golang/interactive.mdx @@ -1,331 +1,333 @@ ---- -title: "Ajouter une fonctionnalité de connexion à votre application Go" -permalink: "interactive" -'description': "Ce guide explique comment intégrer Auth0 à n’importe quelle application Web Go, nouvelle ou existante." -'og:title': "Ajouter une fonctionnalité de connexion à votre application Go" -'og:description': "Ce guide explique comment intégrer Auth0 à n’importe quelle application Web Go, nouvelle ou existante." -'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/golang.png" -'twitter:title': "Ajouter une fonctionnalité de connexion à votre application Go" -'twitter:description': "Ce guide explique comment intégrer Auth0 à n’importe quelle application Web Go, nouvelle ou existante." -sidebarTitle: Go ---- - -import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; -import { LoggedInForm } from "/snippets/Login.jsx"; -import Auth from "/snippets/quickstart/webapp/golang/auth.go.mdx"; -import Callback from "/snippets/quickstart/webapp/golang/callback.go.mdx"; -import Env from "/snippets/quickstart/webapp/golang/.env.mdx"; -import Go from "/snippets/quickstart/webapp/golang/go.mod.mdx"; -import Isauthenticated from "/snippets/quickstart/webapp/golang/isAuthenticated.go.mdx"; -import Login from "/snippets/quickstart/webapp/golang/login.go.mdx"; -import Logout from "/snippets/quickstart/webapp/golang/logout.go.mdx"; -import Main from "/snippets/quickstart/webapp/golang/main.go.mdx"; -import Router from "/snippets/quickstart/webapp/golang/router.go.mdx"; -import User from "/snippets/quickstart/webapp/golang/user.go.mdx"; - -export const sections = [ - { id: "configuration-d-auth0", title: "Configuration d’Auth0" }, - { id: "installer-les-dépendances", title: "Installer les dépendances" }, - { id: "configurer-les-variables-d-environnement", title: "Configurer les variables d’environnement" }, - { id: "configurez-les-packages-oauth2-et-openid-connect", title: "Configurez les packages OAuth2 et OpenID Connect" }, - { id: "configurer-vos-routes-d-application", title: "Configurer vos routes d’application" }, - { id: "ajouter-une-fonctionnalité-de-connexion-à-votre-application", title: "Ajouter une fonctionnalité de connexion à votre application" }, - { id: "gérer-le-rappel-d-authentification", title: "Gérer le rappel d’authentification" }, - { id: "afficher-les-informations-du-profil-utilisateur", title: "Afficher les informations du profil utilisateur" }, - { id: "ajouter-une-fonctionnalité-de-déconnexion-à-votre-application", title: "Ajouter une fonctionnalité de déconnexion à votre application" }, - { id: "protéger-les-routes", title: "Protéger les routes" }, - { id: "lancer-votre-application", title: "Lancer votre application" } -] - - - - Auth0 vous permet d’ajouter l’authentification et de pouvoir accéder aux informations relatives au profil de l’utilisateur dans votre application. Ce guide explique comment intégrer Auth0 à n’importe quelle application Web Go, nouvelle ou existante. - -
- Pour utiliser les services Auth0, vous devez avoir une application installée dans Auth0 Dashboard. L’application Auth0 est l’endroit où vous allez configurer le fonctionnement de l’authentification pour le projet que vous développez. - - ### Configurer une application - - Utilisez le sélecteur interactif pour créer une nouvelle application Auth0 ou sélectionner une application existante qui représente le projet avec lequel vous souhaitez effectuer l’intégration. Dans Auth0, chaque application se voit attribuer un identifiant client unique alphanumérique que votre code d’application utilisera pour appeler les API Auth0 via la trousse SDK. - - Tous les paramètres que vous configurez à l’aide de ce guide de démarrage rapide seront automatiquement mis à jour pour votre application dans le [Tableau de bord](https://manage.auth0.com/dashboard/us/auth0-dsepaid/), qui est l’endroit où vous pourrez gérer vos applications à l’avenir. - - Si vous préférez explorer une configuration complète, consultez plutôt un exemple d’application. - - ### Configuration des URL de rappel - - Une URL de rappel est une URL intégrée dans votre application vers laquelle vous souhaitez qu’Auth0 redirige les utilisateurs après leur authentification. Si elle n’est pas définie, les utilisateurs ne seront pas redirigés vers votre application après s’être connectés. - - - Si vous suivez notre exemple de projet, définissez cette URL comme suit : `http://localhost:3000``/callback`. - - - ### Configuration des URL de déconnexion - - Une URL de déconnexion est une URL intégrée dans votre application vers laquelle vous souhaitez qu’Auth0 redirige les utilisateurs après leur déconnexion. Si elle n’est pas définie, les utilisateurs ne pourront pas se déconnecter de votre application et recevront un message d’erreur. - - - Si vous suivez notre exemple de projet, définissez cette URL comme suit : `http://localhost:3000`. - -
- -
- Créez un fichier `go.mod` pour lister toutes les dépendances de votre application. - - Pour intégrer Auth0 dans une application Go, ajoutez les packages `coreos/go-oidc/v3` et `x/oauth2`. - - En plus des packages OIDC et OAuth2, ajoutez `joho/godotenv`, `gin-gonic/gin`, et `gin-contrib/sessions`. - - - Cet exemple utilise `gin` pour le routage, mais vous pouvez utiliser le routeur de votre choix. - - - Enregistrez le fichier `go.mod` avec les dépendances nécessaires et installez-les en utilisant la commande suivante dans votre terminal : - - `go mod download` -
- -
- Vous devez définir les variables d’environnement suivantes dans `.env` à la racine de votre répertoire de projet : - - - **AUTH0\_DOMAIN** : Le domaine de votre locataire Auth0. Trouvez votre domaine Auth0 dans Auth0 Dashboard sous les paramètres de votre application dans le champ Domain (Domaine). Pour les domaines personnalisés, définissez-le plutôt sur la valeur de votre domaine personnalisé. - - **AUTH0\_CLIENT\_ID** : L’identificateur de l’application Auth0 que vous avez configurée précédemment dans ce guide rapide. Vous le trouverez dans Auth0 Dashboard sous les paramètres de votre application dans le champ Client ID (Identificateur client). - - **AUTH0\_CLIENT\_SECRET** : Le secret de l’application Auth0 que vous avez configurée précédemment dans ce guide rapide. Vous le trouverez dans Auth0 Dashboard, sous les paramètres de votre application dans le champ Client Secret (Secret client). - - **AUTH0\_CALLBACK\_URL** : L’URL utilisée par Auth0 pour rediriger l’utilisateur après une authentification réussie. -
- -
- Ensuite, configurez les packages OAuth2 et OpenID Connect - - Créez un fichier nommé `auth.go` dans le dossier `platform/authenticator`. Dans ce package, créez une méthode pour configurer et renvoyer les clients [OAuth2](https://godoc.org/golang.org/x/oauth2) et [OIDC](https://godoc.org/github.com/coreos/go-oidc), et une autre pour vérifier un jeton d’ID. -
- -
- Créez un fichier nommé `router.go` dans le dossier `platform/router`. Dans ce package, créez une méthode pour configurer et renvoyer nos routes en utilisant [github.com/gin-gonic/gin](https://github.com/gin-gonic/gin). Vous passerez une instance de `Authenticator` à la méthode pour l’utiliser avec les gestionnaires `login (connexion)` et `callback (rappel)`. -
- -
- Pour que l’utilisateur s’authentifie, nous devons créer une fonction gestionnaire pour traiter la route`/login`. - - Créez un fichier nommé `login.go` dans le dossier `web/app/login` et ajoutez une fonction `Handler`. Lors de l’exécution du gestionnaire, l’utilisateur sera redirigé vers Auth0 où il pourra saisir ses identifiants. - - Pour appeler la route `/login` ajoutez un lien vers `/login` dans le modèle `home.html` situé dans le directory `web/template`. -
- -
- Une fois que les utilisateurs se sont authentifiés en utilisant la page de connexion universelle d’Auth0, ils reviendront à l’application à la route `/callback`. - - Créez un fichier nommé `callback.go` dans le dossier `web/app/callback` et ajoutez une fonction `Handler`. - - Ce gestionnaire prendra la chaîne de requête `code` fournie par Auth0 et l’échangera contre un jeton d’ID et un jeton d’accès. - - Si le jeton d’ID est valide, il stockera les informations de profil et le jeton d’accès dans la session. Les informations de profil sont basées sur les demandes contenues dans le jeton d’ID. Le stockage de session permet à l’application d’accéder à ces informations selon les besoins. -
- -
- Maintenant que vos utilisateurs peuvent se connecter, vous voulez probablement pouvoir récupérer et utiliser les informations de profil associées aux utilisateurs authentifiés. - - Vous pouvez accéder à ces informations de profil, telles que leur pseudonyme ou leur photo de profil, à partir du `profile` qui a été sauvegardé dans la session précédemment. - - Créez un gestionnaire pour le point de terminaison `/user` dans `web/app/user/user.go` et renvoyez le fichier HTML correspondant. Comme le `profile` passe à `ctx.HTML()`, vous pouvez accéder aux informations de profil, telles que `picture` et `nickname` à l’intérieur de ce même fichier HTML. - - Un exemple de fichier HTML de ce type pourrait ressembler à l’exemple ci-dessous, mais vous pouvez récupérer n’importe quelle information de profil, y compris des demandes personnalisées. -
- -
- Pour déconnecter l’utilisateur, effacez les données de la session et redirigez l’utilisateur vers le point de terminaison de déconnexion Auth0. Vous trouverez plus d’informations à ce sujet dans la [documentation sur la déconnexion](https://auth0.com/docs/logout). - - Créez un fichier nommé `logout.go` dans le dossier `web/app/logout`, et ajoutez la fonction `Handler` pour rediriger l’utilisateur vers le point de terminaison de déconnexion Auth0. - - L’URL `returnTo` doit figurer dans la liste des URL de déconnexion autorisées de la section des paramètres de l’application. Pour plus d’informations, consultez [Rediriger les utilisateurs après la déconnexion](https://auth0.com/docs/logout/guides/redirect-users-after-logout). - - Créez un fichier nommé `user.js` dans le dossier `web/static/js`, et ajoutez le code pour supprimer le témoin d’un utilisateur connecté. -
- -
- La pratique recommandée veut que certaines routes ne soient accessibles qu’aux utilisateurs authentifiés. Lorsque des utilisateurs non authentifiés essaient d’accéder à des routes protégées, votre application devrait les rediriger. - - Dans ce cas, vous devez mettre en œuvre un intergiciel pour accéder à la requête HTTP. La fonction d’intergiciel détermine si la requête doit être dirigée vers le gestionnaire de point de terminaison ou si elle doit être bloquée. - - Créez un fichier nommé `isAuthenticated.go` dans `platform/middleware` et ajoutez une fonction qui vérifie si l’utilisateur est authentifié ou non, en fonction de la clé de session de `profile`. Si l’utilisateur n’est pas authentifié, l’intergiciel le redirigera vers la racine de l’application. - - L’intergiciel créé, nous pouvons le configurer pour toute route nécessitant une authentification en l’ajoutant au routeur. -
- -
- L’authentificateur et le routeur configurés, nous pouvons connecter les éléments à l’aide du point d’entrée de notre application. Dans `main.go`, créez une instance de l’authentificateur et du routeur, qui reçoit l’instance de l’authentificateur. - - Si vous utilisez un fichier `.env` , vous devez appeler `godotenv.Load()` au tout début de la fonction `main()`. - - Lancez votre application en utilisant la commande suivante dans votre terminal : - - `go run main.go` -
- - ## Étapes suivantes - - Beau travail! Si vous en êtes arrivé là, vous devriez avoir la connexion, la déconnexion et les informations de profil utilisateur actives dans votre application. - - Cela conclut notre tutoriel de démarrage rapide, mais il y a tellement plus à explorer. Pour en savoir plus sur ce que vous pouvez faire avec Auth0, consultez : - - * [Auth0 Dashboard](https://manage.auth0.com/#) : apprenez à configurer et gérer votre locataire et vos applications Auth0 - * [Auth0 Marketplace](https://marketplace.auth0.com/) : découvrez des intégrations que vous pouvez activer pour étendre les fonctionnalités d’Auth0 -
- - - - - - - - - - - - - - - - -
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - -
- - - - - - - - - - - - - - - -
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - -
- - - - - - - - - - - - - - - -
- - - - - - - - - - - - - -
- - - - - - - - - - - - - - -
- - - - - - - -
- - - - - - - - - - - - - - +--- +title: "Ajouter une fonctionnalité de connexion à votre application Go" +permalink: "interactive" +'description': "Ce guide explique comment intégrer Auth0 à n’importe quelle application Web Go, nouvelle ou existante." +'og:title': "Ajouter une fonctionnalité de connexion à votre application Go" +'og:description': "Ce guide explique comment intégrer Auth0 à n’importe quelle application Web Go, nouvelle ou existante." +'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/golang.png" +'twitter:title': "Ajouter une fonctionnalité de connexion à votre application Go" +'twitter:description': "Ce guide explique comment intégrer Auth0 à n’importe quelle application Web Go, nouvelle ou existante." +sidebarTitle: Go +--- + +import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; +import { LoggedInForm } from "/snippets/Login.jsx"; +import Auth from "/snippets/quickstart/webapp/golang/auth.go.mdx"; +import Callback from "/snippets/quickstart/webapp/golang/callback.go.mdx"; +import Env from "/snippets/quickstart/webapp/golang/.env.mdx"; +import Go from "/snippets/quickstart/webapp/golang/go.mod.mdx"; +import Isauthenticated from "/snippets/quickstart/webapp/golang/isAuthenticated.go.mdx"; +import Login from "/snippets/quickstart/webapp/golang/login.go.mdx"; +import Logout from "/snippets/quickstart/webapp/golang/logout.go.mdx"; +import Main from "/snippets/quickstart/webapp/golang/main.go.mdx"; +import Router from "/snippets/quickstart/webapp/golang/router.go.mdx"; +import User from "/snippets/quickstart/webapp/golang/user.go.mdx"; + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + +export const sections = [ + { id: "configuration-d-auth0", title: "Configuration d’Auth0" }, + { id: "installer-les-dépendances", title: "Installer les dépendances" }, + { id: "configurer-les-variables-d-environnement", title: "Configurer les variables d’environnement" }, + { id: "configurez-les-packages-oauth2-et-openid-connect", title: "Configurez les packages OAuth2 et OpenID Connect" }, + { id: "configurer-vos-routes-d-application", title: "Configurer vos routes d’application" }, + { id: "ajouter-une-fonctionnalité-de-connexion-à-votre-application", title: "Ajouter une fonctionnalité de connexion à votre application" }, + { id: "gérer-le-rappel-d-authentification", title: "Gérer le rappel d’authentification" }, + { id: "afficher-les-informations-du-profil-utilisateur", title: "Afficher les informations du profil utilisateur" }, + { id: "ajouter-une-fonctionnalité-de-déconnexion-à-votre-application", title: "Ajouter une fonctionnalité de déconnexion à votre application" }, + { id: "protéger-les-routes", title: "Protéger les routes" }, + { id: "lancer-votre-application", title: "Lancer votre application" } +] + + + + Auth0 vous permet d’ajouter l’authentification et de pouvoir accéder aux informations relatives au profil de l’utilisateur dans votre application. Ce guide explique comment intégrer Auth0 à n’importe quelle application Web Go, nouvelle ou existante. + +
+ Pour utiliser les services Auth0, vous devez avoir une application installée dans Auth0 Dashboard. L’application Auth0 est l’endroit où vous allez configurer le fonctionnement de l’authentification pour le projet que vous développez. + + ### Configurer une application + + Utilisez le sélecteur interactif pour créer une nouvelle application Auth0 ou sélectionner une application existante qui représente le projet avec lequel vous souhaitez effectuer l’intégration. Dans Auth0, chaque application se voit attribuer un identifiant client unique alphanumérique que votre code d’application utilisera pour appeler les API Auth0 via la trousse SDK. + + Tous les paramètres que vous configurez à l’aide de ce guide de démarrage rapide seront automatiquement mis à jour pour votre application dans le [Tableau de bord](https://manage.auth0.com/dashboard/us/auth0-dsepaid/), qui est l’endroit où vous pourrez gérer vos applications à l’avenir. + + Si vous préférez explorer une configuration complète, consultez plutôt un exemple d’application. + + ### Configuration des URL de rappel + + Une URL de rappel est une URL intégrée dans votre application vers laquelle vous souhaitez qu’Auth0 redirige les utilisateurs après leur authentification. Si elle n’est pas définie, les utilisateurs ne seront pas redirigés vers votre application après s’être connectés. + + + Si vous suivez notre exemple de projet, définissez cette URL comme suit : `http://localhost:3000``/callback`. + + + ### Configuration des URL de déconnexion + + Une URL de déconnexion est une URL intégrée dans votre application vers laquelle vous souhaitez qu’Auth0 redirige les utilisateurs après leur déconnexion. Si elle n’est pas définie, les utilisateurs ne pourront pas se déconnecter de votre application et recevront un message d’erreur. + + + Si vous suivez notre exemple de projet, définissez cette URL comme suit : `http://localhost:3000`. + +
+ +
+ Créez un fichier `go.mod` pour lister toutes les dépendances de votre application. + + Pour intégrer Auth0 dans une application Go, ajoutez les packages `coreos/go-oidc/v3` et `x/oauth2`. + + En plus des packages OIDC et OAuth2, ajoutez `joho/godotenv`, `gin-gonic/gin`, et `gin-contrib/sessions`. + + + Cet exemple utilise `gin` pour le routage, mais vous pouvez utiliser le routeur de votre choix. + + + Enregistrez le fichier `go.mod` avec les dépendances nécessaires et installez-les en utilisant la commande suivante dans votre terminal : + + `go mod download` +
+ +
+ Vous devez définir les variables d’environnement suivantes dans `.env` à la racine de votre répertoire de projet : + + - **AUTH0\_DOMAIN** : Le domaine de votre locataire Auth0. Trouvez votre domaine Auth0 dans Auth0 Dashboard sous les paramètres de votre application dans le champ Domain (Domaine). Pour les domaines personnalisés, définissez-le plutôt sur la valeur de votre domaine personnalisé. + - **AUTH0\_CLIENT\_ID** : L’identificateur de l’application Auth0 que vous avez configurée précédemment dans ce guide rapide. Vous le trouverez dans Auth0 Dashboard sous les paramètres de votre application dans le champ Client ID (Identificateur client). + - **AUTH0\_CLIENT\_SECRET** : Le secret de l’application Auth0 que vous avez configurée précédemment dans ce guide rapide. Vous le trouverez dans Auth0 Dashboard, sous les paramètres de votre application dans le champ Client Secret (Secret client). + - **AUTH0\_CALLBACK\_URL** : L’URL utilisée par Auth0 pour rediriger l’utilisateur après une authentification réussie. +
+ +
+ Ensuite, configurez les packages OAuth2 et OpenID Connect + + Créez un fichier nommé `auth.go` dans le dossier `platform/authenticator`. Dans ce package, créez une méthode pour configurer et renvoyer les clients [OAuth2](https://godoc.org/golang.org/x/oauth2) et [OIDC](https://godoc.org/github.com/coreos/go-oidc), et une autre pour vérifier un jeton d’ID. +
+ +
+ Créez un fichier nommé `router.go` dans le dossier `platform/router`. Dans ce package, créez une méthode pour configurer et renvoyer nos routes en utilisant [github.com/gin-gonic/gin](https://github.com/gin-gonic/gin). Vous passerez une instance de `Authenticator` à la méthode pour l’utiliser avec les gestionnaires `login (connexion)` et `callback (rappel)`. +
+ +
+ Pour que l’utilisateur s’authentifie, nous devons créer une fonction gestionnaire pour traiter la route`/login`. + + Créez un fichier nommé `login.go` dans le dossier `web/app/login` et ajoutez une fonction `Handler`. Lors de l’exécution du gestionnaire, l’utilisateur sera redirigé vers Auth0 où il pourra saisir ses identifiants. + + Pour appeler la route `/login` ajoutez un lien vers `/login` dans le modèle `home.html` situé dans le directory `web/template`. +
+ +
+ Une fois que les utilisateurs se sont authentifiés en utilisant la page de connexion universelle d’Auth0, ils reviendront à l’application à la route `/callback`. + + Créez un fichier nommé `callback.go` dans le dossier `web/app/callback` et ajoutez une fonction `Handler`. + + Ce gestionnaire prendra la chaîne de requête `code` fournie par Auth0 et l’échangera contre un jeton d’ID et un jeton d’accès. + + Si le jeton d’ID est valide, il stockera les informations de profil et le jeton d’accès dans la session. Les informations de profil sont basées sur les demandes contenues dans le jeton d’ID. Le stockage de session permet à l’application d’accéder à ces informations selon les besoins. +
+ +
+ Maintenant que vos utilisateurs peuvent se connecter, vous voulez probablement pouvoir récupérer et utiliser les informations de profil associées aux utilisateurs authentifiés. + + Vous pouvez accéder à ces informations de profil, telles que leur pseudonyme ou leur photo de profil, à partir du `profile` qui a été sauvegardé dans la session précédemment. + + Créez un gestionnaire pour le point de terminaison `/user` dans `web/app/user/user.go` et renvoyez le fichier HTML correspondant. Comme le `profile` passe à `ctx.HTML()`, vous pouvez accéder aux informations de profil, telles que `picture` et `nickname` à l’intérieur de ce même fichier HTML. + + Un exemple de fichier HTML de ce type pourrait ressembler à l’exemple ci-dessous, mais vous pouvez récupérer n’importe quelle information de profil, y compris des demandes personnalisées. +
+ +
+ Pour déconnecter l’utilisateur, effacez les données de la session et redirigez l’utilisateur vers le point de terminaison de déconnexion Auth0. Vous trouverez plus d’informations à ce sujet dans la [documentation sur la déconnexion](https://auth0.com/docs/logout). + + Créez un fichier nommé `logout.go` dans le dossier `web/app/logout`, et ajoutez la fonction `Handler` pour rediriger l’utilisateur vers le point de terminaison de déconnexion Auth0. + + L’URL `returnTo` doit figurer dans la liste des URL de déconnexion autorisées de la section des paramètres de l’application. Pour plus d’informations, consultez [Rediriger les utilisateurs après la déconnexion](https://auth0.com/docs/logout/guides/redirect-users-after-logout). + + Créez un fichier nommé `user.js` dans le dossier `web/static/js`, et ajoutez le code pour supprimer le témoin d’un utilisateur connecté. +
+ +
+ La pratique recommandée veut que certaines routes ne soient accessibles qu’aux utilisateurs authentifiés. Lorsque des utilisateurs non authentifiés essaient d’accéder à des routes protégées, votre application devrait les rediriger. + + Dans ce cas, vous devez mettre en œuvre un intergiciel pour accéder à la requête HTTP. La fonction d’intergiciel détermine si la requête doit être dirigée vers le gestionnaire de point de terminaison ou si elle doit être bloquée. + + Créez un fichier nommé `isAuthenticated.go` dans `platform/middleware` et ajoutez une fonction qui vérifie si l’utilisateur est authentifié ou non, en fonction de la clé de session de `profile`. Si l’utilisateur n’est pas authentifié, l’intergiciel le redirigera vers la racine de l’application. + + L’intergiciel créé, nous pouvons le configurer pour toute route nécessitant une authentification en l’ajoutant au routeur. +
+ +
+ L’authentificateur et le routeur configurés, nous pouvons connecter les éléments à l’aide du point d’entrée de notre application. Dans `main.go`, créez une instance de l’authentificateur et du routeur, qui reçoit l’instance de l’authentificateur. + + Si vous utilisez un fichier `.env` , vous devez appeler `godotenv.Load()` au tout début de la fonction `main()`. + + Lancez votre application en utilisant la commande suivante dans votre terminal : + + `go run main.go` +
+ + ## Étapes suivantes + + Beau travail! Si vous en êtes arrivé là, vous devriez avoir la connexion, la déconnexion et les informations de profil utilisateur actives dans votre application. + + Cela conclut notre tutoriel de démarrage rapide, mais il y a tellement plus à explorer. Pour en savoir plus sur ce que vous pouvez faire avec Auth0, consultez : + + * [Auth0 Dashboard](https://manage.auth0.com/#) : apprenez à configurer et gérer votre locataire et vos applications Auth0 + * [Auth0 Marketplace](https://marketplace.auth0.com/) : découvrez des intégrations que vous pouvez activer pour étendre les fonctionnalités d’Auth0 +
+ + + + + + + + + + + + + + + + +
+ + + + + + + + + + + + + +
+ + + + + + + + + + + + + + +
+ + + + + + + + + + + + + + + +
+ + + + + + + + + + + + + +
+ + + + + + + + + + + + + + +
+ + + + + + + + + + + + + + + +
+ + + + + + + + + + + + + +
+ + + + + + + + + + + + + + +
+ + + + + + + +
+ + + + + + + + + + + + + + diff --git a/main/docs/fr-ca/quickstart/webapp/java-ee/interactive.mdx b/main/docs/fr-ca/quickstart/webapp/java-ee/interactive.mdx index bbefbf1d9..760100fae 100644 --- a/main/docs/fr-ca/quickstart/webapp/java-ee/interactive.mdx +++ b/main/docs/fr-ca/quickstart/webapp/java-ee/interactive.mdx @@ -1,494 +1,496 @@ ---- -title: "Ajouter une connexion à votre application web Java EE" -permalink: "interactive" -'description': "Ce tutoriel montre comment ajouter une connexion utilisateur à une application web Java EE." -'og:title': "Ajouter une connexion à votre application web Java EE" -'og:description': "Ce tutoriel montre comment ajouter une connexion utilisateur à une application web Java EE." -'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/java.png" -'twitter:title': "Ajouter une connexion à votre application web Java EE" -'twitter:description': "Ce tutoriel montre comment ajouter une connexion utilisateur à une application web Java EE." -sidebarTitle: Java EE ---- - -import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; -import { LoggedInForm } from "/snippets/Login.jsx"; -import Web from "/snippets/quickstart/webapp/java-ee/web.xml.mdx"; -import Auth0authenticationconfig from "/snippets/quickstart/webapp/java-ee/Auth0AuthenticationConfig.java.mdx"; -import Loginservlet from "/snippets/quickstart/webapp/java-ee/LoginServlet.java.mdx"; -import Homeservlet from "/snippets/quickstart/webapp/java-ee/HomeServlet.java.mdx"; -import Logoutservlet from "/snippets/quickstart/webapp/java-ee/LogoutServlet.java.mdx"; - -export const sections = [ - { id: "configuration-requise", title: "Configuration requise" }, - { id: "configuration-d-auth0", title: "Configuration d’Auth0" }, - { id: "configurer-java-ee-pour-utiliser-auth0", title: "Configurer Java EE pour utiliser Auth0" }, - { id: "configurer-la-sécurité-java-ee", title: "Configurer la sécurité Java EE" }, - { id: "déclencher-l-authentification", title: "Déclencher l’authentification" }, - { id: "afficher-les-informations-de-l-utilisateur", title: "Afficher les informations de l’utilisateur" }, - { id: "gérer-la-déconnexion", title: "Gérer la déconnexion" }, - { id: "exécuter-l-exemple", title: "Exécuter l’exemple" } -] - - - - Ce tutoriel montre comment ajouter une connexion utilisateur à une application web Java EE. Nous vous recommandons de vous connecter pour suivre ce démarrage rapide avec les exemples configurés pour votre compte. - -
- Ce tutoriel et le projet d’exemple ont été testés avec les éléments suivants : - - - Java 11 -
- -
- ### Obtenez vos clés d’application - - Après votre inscription à Auth0, une nouvelle application a été créée pour vous, ou vous avez pu en créer une. Vous aurez besoin de quelques informations sur cette application pour communiquer avec Auth0. Vous pouvez obtenir ces détails dans la section [Paramètres de l’application](https://manage.auth0.com/#/applications) d’Auth0 Dashboard. - - ![](/docs/images/fr-ca/cdy7uua7fh8z/1NtemqhRTHLFgWkGyAVSC6/ae66506a56ffab891e8a36e1344e6376/uwp.png) - - Les informations suivantes sont nécessaires : - - - **Domain (Domaine)** - - **Client ID (Identifiant client)** - - **Client Secret (Secret client)** - - - En téléchargeant l’exemple en haut de cette page, les détails vous seront automatiquement fournis. - - - ### Configurer les URL de rappel - - Une URL de rappel est une URL dans votre application où Auth0 redirige l’utilisateur après qu’il se soit authentifié. La callbackc URL de votre application doit être ajoutée au champ **URL de rappel autorisées** dansples [Paramètres de l’application](https://manage.auth0.com/#/applications). Si ce champ n’est pas défini, les utilisateurs ne pourront pas se connecter à l’application et obtiendront un message d’erreur. - - - Si vous suivez l’exemple de projet que vous avez téléchargé à partir du haut de cette page, l’URL de rappel que vous devez ajouter au champ **URL de rappel autorisées** est `http://localhost:3000/callback`. - - - ### Configuration des URL de déconnexion - - Une URL de déconnexion est une URL de votre application à laquelle Auth0 peut retourner après la déconnexion de l’utilisateur du serveur d’autorisation. Elle est indiquée dans le paramètre de requête `returnTo`. L’URL de déconnexion de votre application doit être ajoutée au champ **URL de déconnexion autorisées** dans les [paramètres de l’application](https://manage.auth0.com/#/applications). Si ce champ n’est pas défini, les utilisateurs ne pourront pas se déconnecter de l’application et obtiendront un message d’erreur. - - - Si vous suivez l’exemple de projet que vous avez téléchargé à partir du haut de cette page, l’URL de déconnexion que vous devez ajouter au champ **URL de déconnexion autorisées** est `http://localhost:3000/`. - -
- -
- ### Configurez les dépendances - - Pour intégrer votre application Java EE avec Auth0, ajoutez les dépendances suivantes : - - - **javax.javaee-api** : L’API Java EE 8 est nécessaire pour écrire des applications à l’aide de Java EE 8. L’implémentation réelle est fournie par le conteneur d’application : elle n’a donc pas besoin d’être incluse dans le fichier WAR. - - **javax.security.entreprise** : L’API de sécurité Java EE 8 permet de gérer les problèmes de sécurité dans une application EE. Comme la dépendance `javax.javaee-api`, l’implémentation est fournie par le conteneur d’application : elle n’est donc pas incluse dans le fichier WAR. - - **auth0-java-mvc-commons** : Le [Kit de développement logiciel (SDK) Java MVC Auth0](https://github.com/auth0/auth0-java-mvc-common) vous permet d’utiliser Auth0 avec Java pour les applications Web MVC côté serveur. Il génère l’URL d’autorisation que votre application doit appeler pour authentifier un utilisateur à l’aide d’Auth0. - - Si vous utilisez Maven, ajoutez les dépendances à votre `pom.xml` : - - ```html - - - com.auth0 - mvc-auth-commons - [1.0, 2.0) - - - javax - javaee-api - 8.0.1 - provided - - - javax.security.enterprise - javax.security.enterprise-api - 1.0 - provided - - ``` - - Si vous utilisez Gradle, ajoutez-les à votre `build.gradle` : - - ``` - // build.gradle - providedCompile 'javax:javaee-api:8.0.1' - providedCompile 'javax.security.enterprise:javax.security.enterprise-api:1.0' - implementation 'com.auth0:mvc-auth-commons:1. ' - ``` - - ### Configurez votre application Java EE - - - L’exemple qui accompagne ce tutoriel est écrit en JSP et testé avec le serveur d’application [WildFly](https://wildfly.org/). Il se peut que vous deviez adapter certaines des étapes si vous travaillez avec un conteneur d’application ou des technologies différents. - - - Votre application Java EE a besoin de certaines informations pour authentifier les utilisateurs avec votre application Auth0. Le fichier descripteur de déploiement `web.xml` peut être utilisé pour stocker ces informations, bien que vous puissiez les stocker dans un autre emplacement sécurisé. - - Ces informations seront utilisées pour configurer la bibliothèque **auth0-java-mvc-commons** afin de permettre aux utilisateurs de se connecter à votre application. Pour en savoir plus sur la bibliothèque, y compris ses différentes options de configuration, consultez le fichier [README](https://github.com/auth0/auth0-java-mvc-common/blob/master/README.md) de la bibliothèque. - - | **Vérifier les attributs remplis** | - | --- | - | Si vous avez téléchargé cet exemple en utilisant le bouton **Download Sample**, les attributs `domain`, `clientId` et `clientSecret` seront remplis pour vous. Vous devez vérifier que les valeurs sont correctes, surtout si vous avez plusieurs applications Auth0 dans votre compte. | -
- -
- L’API de Java EE 8 Security a introduit l’interface `HttpAuthenticationMechanism` pour permettre aux applications d’obtenir les identifiants d’un utilisateur. Des implémentations par défaut existent pour l’authentification de base et l’authentification basée sur le formulaire, et il est facile de configurer une stratégie d’authentification personnalisée. - - Pour s’authentifier avec Auth0, il faut fournir des implémentations personnalisées des interfaces suivantes : - - - HttpAuthenticationMechanism : responsable de la gestion du flux d’authentification pour les utilisateurs qui reviennent d’Auth0. ([JavaDoc](https://javaee.github.io/javaee-spec/javadocs/javax/security/enterprise/authentication/mechanism/http/HttpAuthenticationMechanism.html)). - - IdentityStore : responsable de la validation des identifiants de l’utilisateur ([JavaDoc](https://javaee.github.io/javaee-spec/javadocs/javax/security/enterprise/identitystore/IdentityStore.html)). - - CallerPrincipal : représente le principal de l’appelant de la requête HTTP en cours ([JavaDoc](https://javaee.github.io/javaee-spec/javadocs/javax/security/enterprise/CallerPrincipal.html)). - - Credential : représente l’identifiant que l’appelant utilisera pour s’authentifier ([JavaDoc](https://javaee.github.io/javaee-spec/javadocs/javax/security/enterprise/credential/Credential.html)). - - Tout d’abord, mettez vos paramètres Auth0 à la disposition de l’application en créant un bean @ApplicationScoped pour récupérer les valeurs du contexte Web et les rendre disponibles via des getters (accesseurs). - - Ensuite, créez un `CallerPrincipal` personnalisé qui représente l’appelant de la requête en cours : - - ``` - // src/main/java/com/auth0/example/security/Auth0JwtPrincipal.java - public class Auth0JwtPrincipal extends CallerPrincipal { - private final DecodedJWT idToken; - - Auth0JwtPrincipal(DecodedJWT idToken) { - - super(idToken.getClaim("name").asString()); - - this.idToken = idToken; - - } - - public DecodedJWT getIdToken() { - - return this.idToken; - - } - - } - ``` - - Vous pouvez maintenant mettre en œuvre un `Credential` personnalisé qui sera utilisé pour représenter les identifiants de l’utilisateur. Il contiendra des informations sur le principal : - - ``` - // src/main/java/com/auth0/example/security/Auth0JwtCredential.java - class Auth0JwtCredential implements Credential { - private Auth0JwtPrincipal auth0JwtPrincipal; - - Auth0JwtCredential(String token) { - - DecodedJWT decodedJWT = JWT.decode(token); - - this.auth0JwtPrincipal = new Auth0JwtPrincipal(decodedJWT); - - } - - Auth0JwtPrincipal getAuth0JwtPrincipal() { - - return auth0JwtPrincipal; - - } - - } - ``` - - Vous avez maintenant défini les classes qui représentent le principal et l’identifiant d’un appelant. Ensuite, créez une implémentation personnalisée de `IdentityStore`. Cette classe sera chargée de valider les identifiants de l’utilisateur : - - ``` - // src/main/java/com/auth0/example/security/Auth0JwtIdentityStore.java - @ApplicationScoped - public class Auth0JwtIdentityStore implements IdentityStore { - @Override - - public CredentialValidationResult validate(final Credential credential) { - - CredentialValidationResult result = CredentialValidationResult.NOT_VALIDATED_RESULT; - - if (credential instanceof Auth0JwtCredential) { - - Auth0JwtCredential auth0JwtCredential = (Auth0JwtCredential) credential; - - result = new CredentialValidationResult(auth0JwtCredential.getAuth0JwtPrincipal()); - - } - - return result; - - } - - } - ``` - - Si le `credential` est un `Auth0Credential`, l’utilisateur appelant est authentifié et valide, et un `CredentialValidationResult` créé avec le credential est renvoyé pour indiquer le succès. S’il ne s’agit pas d’un `Auth0Credential`, un `CredentialValidationResult.NOT_VALIDATED_RESULT` est renvoyé. - - Avant d’implémenter l’interface `HttpAuthenticationMechanism` qui utilisera tous ces collaborateurs, créez un bean qui fournira une instance configurée du `AuthenticationController` de la trousse SDK Auth0 Java MVC. Le `AuthenticationController` est utilisé pour construire l’URL d’autorisation où les utilisateurs se connecteront, et gérer l’échange de jetons pour authentifier les utilisateurs. - - - Si votre application Auth0 est configurée pour utiliser l’algorithme de signature **RS256** (par défaut lors de la création d’une nouvelle application Auth0), vous devez configurer un `JwkProvider` pour récupérer la clé publique utilisée pour vérifier la signature du jeton. Voir le référentiel [jwks-rsa-java](https://github.com/auth0/jwks-rsa-java) pour connaître les options de configuration supplémentaires. - - Si votre application Auth0 est configurée pour utiliser l’algorithme de signature **HS256**, il n’est pas nécessaire de configurer le `JwkProvider`. - - - Pour en savoir plus sur les algorithmes de signature disponibles, consultez la [documentation](https://auth0.com/docs/tokens/concepts/signing-algorithms). - - - L’exemple ci-dessous montre comment configurer le `AuthenticationController` pour l’utiliser avec l’algorithme de signature **RS256** : - - ``` - // src/main/java/com/auth0/example/security/Auth0AuthenticationProvider.java - @ApplicationScoped - public class Auth0AuthenticationProvider { - @Produces - - public AuthenticationController authenticationController(Auth0AuthenticationConfig config) { - - JwkProvider jwkProvider = new JwkProviderBuilder(config.getDomain()).build(); - - return AuthenticationController.newBuilder(config.getDomain(), config.getClientId(), config.getClientSecret()) - - .withJwkProvider(jwkProvider) - - .build(); - - } - - } - ``` - - Enfin, mettez en œuvre un `HttpAuthenticationMechanism` personnalisé - - ``` - // src/main/java/com/auth0/example/security/Auth0AuthenticationMechanism.java - @ApplicationScoped - @AutoApplySession - public class Auth0AuthenticationMechanism implements HttpAuthenticationMechanism { - private final AuthenticationController authenticationController; - - private final IdentityStoreHandler identityStoreHandler; - - @Inject - - Auth0AuthenticationMechanism(AuthenticationController authenticationController, IdentityStoreHandler identityStoreHandler) { - - this.authenticationController = authenticationController; - - this.identityStoreHandler = identityStoreHandler; - - } - - @Override - - public AuthenticationStatus validateRequest(HttpServletRequest httpServletRequest, - - HttpServletResponse httpServletResponse, - - HttpMessageContext httpMessageContext) throws AuthenticationException { - - // Exchange the code for the ID token, and notify container of result. - - if (isCallbackRequest(httpServletRequest)) { - - try { - - Tokens tokens = authenticationController.handle(httpServletRequest, httpServletResponse); - - Auth0JwtCredential auth0JwtCredential = new Auth0JwtCredential(tokens.getIdToken()); - - CredentialValidationResult result = identityStoreHandler.validate(auth0JwtCredential); - - return httpMessageContext.notifyContainerAboutLogin(result); - - } catch (IdentityVerificationException e) { - - return httpMessageContext.responseUnauthorized(); - - } - - } - - return httpMessageContext.doNothing(); - - } - - private boolean isCallbackRequest(HttpServletRequest request) { - - return request.getRequestURI().equals("/callback") && request.getParameter("code") != null; - - } - - } - ``` - - La classe a priorité sur la méthode `validateRequest`, qui est appelée à chaque demande adressée à notre application et qui est chargée de notifier au conteneur l’état de l’authentification. - - Cet exemple utilise le [flux de code d’autorisation](https://auth0.com/docs/flows/concepts/auth-code) pour échanger un code d’autorisation contre un jeton au cours du processus d’authentification. Si cette requête est adressée au point de terminaison `/callback` et contient le paramètre de requête `code`, elle effectue quelques opérations importantes : - - - Elle appelle la méthode `handle` du `AuthenticationController` pour échanger le code d’autorisation contre un jeton d’ID et un jeton d’accès. - - Elle utilise le jeton d’ID pour créer un nouveau `Auth0Credential`. - - Elle appelle la méthode `validate` de l’implémentation personnalisée `IdentityStore` pour obtenir le résultat de la validation. - - Elle informe le conteneur de l’application de l’état de la connexion. - - Si la ressource demandée n’est pas `/callback`, elle renvoie `httpMessageContext.doNothing()` pour permettre la poursuite du traitement de la demande. Vous verrez bientôt comment utiliser les informations d’authentification lors du déclenchement de l’authentification et de l’affichage des vues Web. - - Enfin, notez que l’annotation `@AutoApplySession` a été ajoutée pour permettre au conteneur de créer une session pour l’utilisateur authentifié. -
- -
- Pour permettre à un utilisateur de se connecter, créez un Servlet qui traitera les requêtes au chemin `/login`. - - Le `LoginController` est responsable de rediriger la requête vers l’URL d’autorisation appropriée, où l’utilisateur peut s’authentifier avec Auth0. Il utilise le `AuthenticationController` du SDK Auth0 Java MVC pour construire le bon URL d’autorisation, en utilisant les valeurs de configuration injectées via `Auth0AuthenticationConfig`. Par défaut, cet exemple demande les permissions `"openid profile email"` pour permettre à l’application de récupérer les informations de profil de base auprès de l’utilisateur authentifié. Vous pouvez en savoir plus sur ces permissions dans la documentation [OpenID Connect Scopes](https://auth0.com/docs/scopes/current/oidc-scopes). - - Une fois que l’utilisateur a entré ses identifiants et autorisé les permissions demandées, Auth0 enverra une requête au `callbackUrl`, incluant un paramètre de requête `code` qui peut être échangé contre un jeton d’ID et un jeton d’accès. Rappelons que le `Auth0HttpAuthenticationMechanism` créé ci-dessus gère cet échange afin qu’il puisse notifier le conteneur d’applications du statut d’authentification. Cela permet au Servlet qui gère les requêtes vers le chemin `/callback` de simplement transférer la requête à la ressource initialement demandée avant de se connecter, ou simplement de rediriger vers la page d’accueil : - - ``` - // src/main/com/auth0/example/web/CallbackServlet.java - @WebServlet(urlPatterns = {"/callback"}) - public class CallbackServlet extends HttpServlet { - @Override - - public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { - - String referer = (String) request.getSession().getAttribute("Referer"); - - String redirectTo = referer != null ? referer : "/"; - - response.sendRedirect(redirectTo); - - } - - } - ``` -
- -
- Vous pouvez utiliser `Auth0JwtPrincipal` pour obtenir des informations sur le profil de l’utilisateur authentifié. L’exemple de code `HomeServlet.java` montre comment utiliser les demandes sur le [Jeton d’ID](https://auth0.com/docs/tokens/id-token) pour définir les données de profil comme attribut de requête. - - Vous pouvez ensuite utiliser ces informations de profil dans votre vue pour afficher des informations sur l’utilisateur : - - ```html - - - -
  • -
    - - -
  • -
    - -
  • - - - Profile picture - -
    - -
    "{profile.get('name').asString()}"
    - Profile - Log out -
    -
  • -
    -
    - ``` -
    - -
    - Pour déconnecter un utilisateur, vous devez effacer la session d’application et déconnecter l’utilisateur d’Auth0. Cette opération est gérée dans le `LogoutServlet`. - - Commencez par effacer la session en appelant `request.getSession().invalidate()`. Créez ensuite l’URL de déconnexion, en veillant à inclure le paramètre de requête `returnTo`, vers lequel l’utilisateur sera redirigé après la déconnexion. Enfin, redirigez la réponse vers l’URL de déconnexion de l’application. -
    - -
    - Pour construire et exécuter l’exemple, exécutez l’objectif Maven wildfly:run pour démarrer un serveur d’application WildFly intégré avec cette application déployée. Voir la documentation [Plugiciel WildFly Maven](https://docs.jboss.org/wildfly/plugins/maven/latest/) pour plus d’informations. - - Si vous utilisez Linux ou MacOS : - - ``` - ./mvnw clean wildfly:run - ``` - - Windows : - - ``` - mvnw.cmd clean wildfly:run - ``` - - Pointez votre navigateur sur `http:``//localhost:3000.` Suivez le lien **Log In (Connexion)** pour vous connecter ou vous inscrire à votre locataire Auth0. - - ![null](/docs/images/fr-ca/cdy7uua7fh8z/5Lp4Zahxd2v6wSJmy9JaM4/2fc68529fe5299c1fc514e3f28a8c998/Login_Screen_-_French.png) - - Une fois la connexion réussie, vous verrez l’image du profil de l’utilisateur et un menu déroulant à l’endroit où se trouvait le lien Log In (Connexion). Vous pouvez alors consulter la page de profil de l’utilisateur en cliquant sur le lien **Profile (Profil)**. Vous pouvez vous déconnecter en cliquant sur le lien **Logout (Déconnexion)** dans le menu déroulant. -
    - - ## Étapes suivantes - - Beau travail! Si vous en êtes arrivé là, vous devriez avoir la connexion, la déconnexion et les informations de profil utilisateur actives dans votre application. - - Cela conclut notre tutoriel de démarrage rapide, mais il y a tellement plus à explorer. Pour en savoir plus sur ce que vous pouvez faire avec Auth0, consultez : - - * [Auth0 Dashboard](https://manage.auth0.com/#) : apprenez à configurer et gérer votre locataire et vos applications Auth0 - * [Trousse SDK auth0-java-mvc-common](https://github.com/auth0/auth0-java-mvc-common) : explorez en détail la trousse SDK utilisée dans ce tutoriel - * [Auth0 Marketplace](https://marketplace.auth0.com/) : découvrez des intégrations que vous pouvez activer pour étendre les fonctionnalités d’Auth0 -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    +--- +title: "Ajouter une connexion à votre application web Java EE" +permalink: "interactive" +'description': "Ce tutoriel montre comment ajouter une connexion utilisateur à une application web Java EE." +'og:title': "Ajouter une connexion à votre application web Java EE" +'og:description': "Ce tutoriel montre comment ajouter une connexion utilisateur à une application web Java EE." +'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/java.png" +'twitter:title': "Ajouter une connexion à votre application web Java EE" +'twitter:description': "Ce tutoriel montre comment ajouter une connexion utilisateur à une application web Java EE." +sidebarTitle: Java EE +--- + +import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; +import { LoggedInForm } from "/snippets/Login.jsx"; +import Web from "/snippets/quickstart/webapp/java-ee/web.xml.mdx"; +import Auth0authenticationconfig from "/snippets/quickstart/webapp/java-ee/Auth0AuthenticationConfig.java.mdx"; +import Loginservlet from "/snippets/quickstart/webapp/java-ee/LoginServlet.java.mdx"; +import Homeservlet from "/snippets/quickstart/webapp/java-ee/HomeServlet.java.mdx"; +import Logoutservlet from "/snippets/quickstart/webapp/java-ee/LogoutServlet.java.mdx"; + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + +export const sections = [ + { id: "configuration-requise", title: "Configuration requise" }, + { id: "configuration-d-auth0", title: "Configuration d’Auth0" }, + { id: "configurer-java-ee-pour-utiliser-auth0", title: "Configurer Java EE pour utiliser Auth0" }, + { id: "configurer-la-sécurité-java-ee", title: "Configurer la sécurité Java EE" }, + { id: "déclencher-l-authentification", title: "Déclencher l’authentification" }, + { id: "afficher-les-informations-de-l-utilisateur", title: "Afficher les informations de l’utilisateur" }, + { id: "gérer-la-déconnexion", title: "Gérer la déconnexion" }, + { id: "exécuter-l-exemple", title: "Exécuter l’exemple" } +] + + + + Ce tutoriel montre comment ajouter une connexion utilisateur à une application web Java EE. Nous vous recommandons de vous connecter pour suivre ce démarrage rapide avec les exemples configurés pour votre compte. + +
    + Ce tutoriel et le projet d’exemple ont été testés avec les éléments suivants : + + - Java 11 +
    + +
    + ### Obtenez vos clés d’application + + Après votre inscription à Auth0, une nouvelle application a été créée pour vous, ou vous avez pu en créer une. Vous aurez besoin de quelques informations sur cette application pour communiquer avec Auth0. Vous pouvez obtenir ces détails dans la section [Paramètres de l’application](https://manage.auth0.com/#/applications) d’Auth0 Dashboard. + + ![](/docs/images/fr-ca/cdy7uua7fh8z/1NtemqhRTHLFgWkGyAVSC6/ae66506a56ffab891e8a36e1344e6376/uwp.png) + + Les informations suivantes sont nécessaires : + + - **Domain (Domaine)** + - **Client ID (Identifiant client)** + - **Client Secret (Secret client)** + + + En téléchargeant l’exemple en haut de cette page, les détails vous seront automatiquement fournis. + + + ### Configurer les URL de rappel + + Une URL de rappel est une URL dans votre application où Auth0 redirige l’utilisateur après qu’il se soit authentifié. La callbackc URL de votre application doit être ajoutée au champ **URL de rappel autorisées** dansples [Paramètres de l’application](https://manage.auth0.com/#/applications). Si ce champ n’est pas défini, les utilisateurs ne pourront pas se connecter à l’application et obtiendront un message d’erreur. + + + Si vous suivez l’exemple de projet que vous avez téléchargé à partir du haut de cette page, l’URL de rappel que vous devez ajouter au champ **URL de rappel autorisées** est `http://localhost:3000/callback`. + + + ### Configuration des URL de déconnexion + + Une URL de déconnexion est une URL de votre application à laquelle Auth0 peut retourner après la déconnexion de l’utilisateur du serveur d’autorisation. Elle est indiquée dans le paramètre de requête `returnTo`. L’URL de déconnexion de votre application doit être ajoutée au champ **URL de déconnexion autorisées** dans les [paramètres de l’application](https://manage.auth0.com/#/applications). Si ce champ n’est pas défini, les utilisateurs ne pourront pas se déconnecter de l’application et obtiendront un message d’erreur. + + + Si vous suivez l’exemple de projet que vous avez téléchargé à partir du haut de cette page, l’URL de déconnexion que vous devez ajouter au champ **URL de déconnexion autorisées** est `http://localhost:3000/`. + +
    + +
    + ### Configurez les dépendances + + Pour intégrer votre application Java EE avec Auth0, ajoutez les dépendances suivantes : + + - **javax.javaee-api** : L’API Java EE 8 est nécessaire pour écrire des applications à l’aide de Java EE 8. L’implémentation réelle est fournie par le conteneur d’application : elle n’a donc pas besoin d’être incluse dans le fichier WAR. + - **javax.security.entreprise** : L’API de sécurité Java EE 8 permet de gérer les problèmes de sécurité dans une application EE. Comme la dépendance `javax.javaee-api`, l’implémentation est fournie par le conteneur d’application : elle n’est donc pas incluse dans le fichier WAR. + - **auth0-java-mvc-commons** : Le [Kit de développement logiciel (SDK) Java MVC Auth0](https://github.com/auth0/auth0-java-mvc-common) vous permet d’utiliser Auth0 avec Java pour les applications Web MVC côté serveur. Il génère l’URL d’autorisation que votre application doit appeler pour authentifier un utilisateur à l’aide d’Auth0. + + Si vous utilisez Maven, ajoutez les dépendances à votre `pom.xml` : + + ```html + + + com.auth0 + mvc-auth-commons + [1.0, 2.0) + + + javax + javaee-api + 8.0.1 + provided + + + javax.security.enterprise + javax.security.enterprise-api + 1.0 + provided + + ``` + + Si vous utilisez Gradle, ajoutez-les à votre `build.gradle` : + + ``` + // build.gradle + providedCompile 'javax:javaee-api:8.0.1' + providedCompile 'javax.security.enterprise:javax.security.enterprise-api:1.0' + implementation 'com.auth0:mvc-auth-commons:1. ' + ``` + + ### Configurez votre application Java EE + + + L’exemple qui accompagne ce tutoriel est écrit en JSP et testé avec le serveur d’application [WildFly](https://wildfly.org/). Il se peut que vous deviez adapter certaines des étapes si vous travaillez avec un conteneur d’application ou des technologies différents. + + + Votre application Java EE a besoin de certaines informations pour authentifier les utilisateurs avec votre application Auth0. Le fichier descripteur de déploiement `web.xml` peut être utilisé pour stocker ces informations, bien que vous puissiez les stocker dans un autre emplacement sécurisé. + + Ces informations seront utilisées pour configurer la bibliothèque **auth0-java-mvc-commons** afin de permettre aux utilisateurs de se connecter à votre application. Pour en savoir plus sur la bibliothèque, y compris ses différentes options de configuration, consultez le fichier [README](https://github.com/auth0/auth0-java-mvc-common/blob/master/README.md) de la bibliothèque. + + | **Vérifier les attributs remplis** | + | --- | + | Si vous avez téléchargé cet exemple en utilisant le bouton **Download Sample**, les attributs `domain`, `clientId` et `clientSecret` seront remplis pour vous. Vous devez vérifier que les valeurs sont correctes, surtout si vous avez plusieurs applications Auth0 dans votre compte. | +
    + +
    + L’API de Java EE 8 Security a introduit l’interface `HttpAuthenticationMechanism` pour permettre aux applications d’obtenir les identifiants d’un utilisateur. Des implémentations par défaut existent pour l’authentification de base et l’authentification basée sur le formulaire, et il est facile de configurer une stratégie d’authentification personnalisée. + + Pour s’authentifier avec Auth0, il faut fournir des implémentations personnalisées des interfaces suivantes : + + - HttpAuthenticationMechanism : responsable de la gestion du flux d’authentification pour les utilisateurs qui reviennent d’Auth0. ([JavaDoc](https://javaee.github.io/javaee-spec/javadocs/javax/security/enterprise/authentication/mechanism/http/HttpAuthenticationMechanism.html)). + - IdentityStore : responsable de la validation des identifiants de l’utilisateur ([JavaDoc](https://javaee.github.io/javaee-spec/javadocs/javax/security/enterprise/identitystore/IdentityStore.html)). + - CallerPrincipal : représente le principal de l’appelant de la requête HTTP en cours ([JavaDoc](https://javaee.github.io/javaee-spec/javadocs/javax/security/enterprise/CallerPrincipal.html)). + - Credential : représente l’identifiant que l’appelant utilisera pour s’authentifier ([JavaDoc](https://javaee.github.io/javaee-spec/javadocs/javax/security/enterprise/credential/Credential.html)). + + Tout d’abord, mettez vos paramètres Auth0 à la disposition de l’application en créant un bean @ApplicationScoped pour récupérer les valeurs du contexte Web et les rendre disponibles via des getters (accesseurs). + + Ensuite, créez un `CallerPrincipal` personnalisé qui représente l’appelant de la requête en cours : + + ``` + // src/main/java/com/auth0/example/security/Auth0JwtPrincipal.java + public class Auth0JwtPrincipal extends CallerPrincipal { + private final DecodedJWT idToken; + + Auth0JwtPrincipal(DecodedJWT idToken) { + + super(idToken.getClaim("name").asString()); + + this.idToken = idToken; + + } + + public DecodedJWT getIdToken() { + + return this.idToken; + + } + + } + ``` + + Vous pouvez maintenant mettre en œuvre un `Credential` personnalisé qui sera utilisé pour représenter les identifiants de l’utilisateur. Il contiendra des informations sur le principal : + + ``` + // src/main/java/com/auth0/example/security/Auth0JwtCredential.java + class Auth0JwtCredential implements Credential { + private Auth0JwtPrincipal auth0JwtPrincipal; + + Auth0JwtCredential(String token) { + + DecodedJWT decodedJWT = JWT.decode(token); + + this.auth0JwtPrincipal = new Auth0JwtPrincipal(decodedJWT); + + } + + Auth0JwtPrincipal getAuth0JwtPrincipal() { + + return auth0JwtPrincipal; + + } + + } + ``` + + Vous avez maintenant défini les classes qui représentent le principal et l’identifiant d’un appelant. Ensuite, créez une implémentation personnalisée de `IdentityStore`. Cette classe sera chargée de valider les identifiants de l’utilisateur : + + ``` + // src/main/java/com/auth0/example/security/Auth0JwtIdentityStore.java + @ApplicationScoped + public class Auth0JwtIdentityStore implements IdentityStore { + @Override + + public CredentialValidationResult validate(final Credential credential) { + + CredentialValidationResult result = CredentialValidationResult.NOT_VALIDATED_RESULT; + + if (credential instanceof Auth0JwtCredential) { + + Auth0JwtCredential auth0JwtCredential = (Auth0JwtCredential) credential; + + result = new CredentialValidationResult(auth0JwtCredential.getAuth0JwtPrincipal()); + + } + + return result; + + } + + } + ``` + + Si le `credential` est un `Auth0Credential`, l’utilisateur appelant est authentifié et valide, et un `CredentialValidationResult` créé avec le credential est renvoyé pour indiquer le succès. S’il ne s’agit pas d’un `Auth0Credential`, un `CredentialValidationResult.NOT_VALIDATED_RESULT` est renvoyé. + + Avant d’implémenter l’interface `HttpAuthenticationMechanism` qui utilisera tous ces collaborateurs, créez un bean qui fournira une instance configurée du `AuthenticationController` de la trousse SDK Auth0 Java MVC. Le `AuthenticationController` est utilisé pour construire l’URL d’autorisation où les utilisateurs se connecteront, et gérer l’échange de jetons pour authentifier les utilisateurs. + + - Si votre application Auth0 est configurée pour utiliser l’algorithme de signature **RS256** (par défaut lors de la création d’une nouvelle application Auth0), vous devez configurer un `JwkProvider` pour récupérer la clé publique utilisée pour vérifier la signature du jeton. Voir le référentiel [jwks-rsa-java](https://github.com/auth0/jwks-rsa-java) pour connaître les options de configuration supplémentaires. + - Si votre application Auth0 est configurée pour utiliser l’algorithme de signature **HS256**, il n’est pas nécessaire de configurer le `JwkProvider`. + + + Pour en savoir plus sur les algorithmes de signature disponibles, consultez la [documentation](https://auth0.com/docs/tokens/concepts/signing-algorithms). + + + L’exemple ci-dessous montre comment configurer le `AuthenticationController` pour l’utiliser avec l’algorithme de signature **RS256** : + + ``` + // src/main/java/com/auth0/example/security/Auth0AuthenticationProvider.java + @ApplicationScoped + public class Auth0AuthenticationProvider { + @Produces + + public AuthenticationController authenticationController(Auth0AuthenticationConfig config) { + + JwkProvider jwkProvider = new JwkProviderBuilder(config.getDomain()).build(); + + return AuthenticationController.newBuilder(config.getDomain(), config.getClientId(), config.getClientSecret()) + + .withJwkProvider(jwkProvider) + + .build(); + + } + + } + ``` + + Enfin, mettez en œuvre un `HttpAuthenticationMechanism` personnalisé + + ``` + // src/main/java/com/auth0/example/security/Auth0AuthenticationMechanism.java + @ApplicationScoped + @AutoApplySession + public class Auth0AuthenticationMechanism implements HttpAuthenticationMechanism { + private final AuthenticationController authenticationController; + + private final IdentityStoreHandler identityStoreHandler; + + @Inject + + Auth0AuthenticationMechanism(AuthenticationController authenticationController, IdentityStoreHandler identityStoreHandler) { + + this.authenticationController = authenticationController; + + this.identityStoreHandler = identityStoreHandler; + + } + + @Override + + public AuthenticationStatus validateRequest(HttpServletRequest httpServletRequest, + + HttpServletResponse httpServletResponse, + + HttpMessageContext httpMessageContext) throws AuthenticationException { + + // Exchange the code for the ID token, and notify container of result. + + if (isCallbackRequest(httpServletRequest)) { + + try { + + Tokens tokens = authenticationController.handle(httpServletRequest, httpServletResponse); + + Auth0JwtCredential auth0JwtCredential = new Auth0JwtCredential(tokens.getIdToken()); + + CredentialValidationResult result = identityStoreHandler.validate(auth0JwtCredential); + + return httpMessageContext.notifyContainerAboutLogin(result); + + } catch (IdentityVerificationException e) { + + return httpMessageContext.responseUnauthorized(); + + } + + } + + return httpMessageContext.doNothing(); + + } + + private boolean isCallbackRequest(HttpServletRequest request) { + + return request.getRequestURI().equals("/callback") && request.getParameter("code") != null; + + } + + } + ``` + + La classe a priorité sur la méthode `validateRequest`, qui est appelée à chaque demande adressée à notre application et qui est chargée de notifier au conteneur l’état de l’authentification. + + Cet exemple utilise le [flux de code d’autorisation](https://auth0.com/docs/flows/concepts/auth-code) pour échanger un code d’autorisation contre un jeton au cours du processus d’authentification. Si cette requête est adressée au point de terminaison `/callback` et contient le paramètre de requête `code`, elle effectue quelques opérations importantes : + + - Elle appelle la méthode `handle` du `AuthenticationController` pour échanger le code d’autorisation contre un jeton d’ID et un jeton d’accès. + - Elle utilise le jeton d’ID pour créer un nouveau `Auth0Credential`. + - Elle appelle la méthode `validate` de l’implémentation personnalisée `IdentityStore` pour obtenir le résultat de la validation. + - Elle informe le conteneur de l’application de l’état de la connexion. + + Si la ressource demandée n’est pas `/callback`, elle renvoie `httpMessageContext.doNothing()` pour permettre la poursuite du traitement de la demande. Vous verrez bientôt comment utiliser les informations d’authentification lors du déclenchement de l’authentification et de l’affichage des vues Web. + + Enfin, notez que l’annotation `@AutoApplySession` a été ajoutée pour permettre au conteneur de créer une session pour l’utilisateur authentifié. +
    + +
    + Pour permettre à un utilisateur de se connecter, créez un Servlet qui traitera les requêtes au chemin `/login`. + + Le `LoginController` est responsable de rediriger la requête vers l’URL d’autorisation appropriée, où l’utilisateur peut s’authentifier avec Auth0. Il utilise le `AuthenticationController` du SDK Auth0 Java MVC pour construire le bon URL d’autorisation, en utilisant les valeurs de configuration injectées via `Auth0AuthenticationConfig`. Par défaut, cet exemple demande les permissions `"openid profile email"` pour permettre à l’application de récupérer les informations de profil de base auprès de l’utilisateur authentifié. Vous pouvez en savoir plus sur ces permissions dans la documentation [OpenID Connect Scopes](https://auth0.com/docs/scopes/current/oidc-scopes). + + Une fois que l’utilisateur a entré ses identifiants et autorisé les permissions demandées, Auth0 enverra une requête au `callbackUrl`, incluant un paramètre de requête `code` qui peut être échangé contre un jeton d’ID et un jeton d’accès. Rappelons que le `Auth0HttpAuthenticationMechanism` créé ci-dessus gère cet échange afin qu’il puisse notifier le conteneur d’applications du statut d’authentification. Cela permet au Servlet qui gère les requêtes vers le chemin `/callback` de simplement transférer la requête à la ressource initialement demandée avant de se connecter, ou simplement de rediriger vers la page d’accueil : + + ``` + // src/main/com/auth0/example/web/CallbackServlet.java + @WebServlet(urlPatterns = {"/callback"}) + public class CallbackServlet extends HttpServlet { + @Override + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { + + String referer = (String) request.getSession().getAttribute("Referer"); + + String redirectTo = referer != null ? referer : "/"; + + response.sendRedirect(redirectTo); + + } + + } + ``` +
    + +
    + Vous pouvez utiliser `Auth0JwtPrincipal` pour obtenir des informations sur le profil de l’utilisateur authentifié. L’exemple de code `HomeServlet.java` montre comment utiliser les demandes sur le [Jeton d’ID](https://auth0.com/docs/tokens/id-token) pour définir les données de profil comme attribut de requête. + + Vous pouvez ensuite utiliser ces informations de profil dans votre vue pour afficher des informations sur l’utilisateur : + + ```html + + + +
  • +
    + + +
  • +
    + +
  • + + + Profile picture + +
    + +
    "{profile.get('name').asString()}"
    + Profile + Log out +
    +
  • +
    +
    + ``` +
    + +
    + Pour déconnecter un utilisateur, vous devez effacer la session d’application et déconnecter l’utilisateur d’Auth0. Cette opération est gérée dans le `LogoutServlet`. + + Commencez par effacer la session en appelant `request.getSession().invalidate()`. Créez ensuite l’URL de déconnexion, en veillant à inclure le paramètre de requête `returnTo`, vers lequel l’utilisateur sera redirigé après la déconnexion. Enfin, redirigez la réponse vers l’URL de déconnexion de l’application. +
    + +
    + Pour construire et exécuter l’exemple, exécutez l’objectif Maven wildfly:run pour démarrer un serveur d’application WildFly intégré avec cette application déployée. Voir la documentation [Plugiciel WildFly Maven](https://docs.jboss.org/wildfly/plugins/maven/latest/) pour plus d’informations. + + Si vous utilisez Linux ou MacOS : + + ``` + ./mvnw clean wildfly:run + ``` + + Windows : + + ``` + mvnw.cmd clean wildfly:run + ``` + + Pointez votre navigateur sur `http:``//localhost:3000.` Suivez le lien **Log In (Connexion)** pour vous connecter ou vous inscrire à votre locataire Auth0. + + ![null](/docs/images/fr-ca/cdy7uua7fh8z/5Lp4Zahxd2v6wSJmy9JaM4/2fc68529fe5299c1fc514e3f28a8c998/Login_Screen_-_French.png) + + Une fois la connexion réussie, vous verrez l’image du profil de l’utilisateur et un menu déroulant à l’endroit où se trouvait le lien Log In (Connexion). Vous pouvez alors consulter la page de profil de l’utilisateur en cliquant sur le lien **Profile (Profil)**. Vous pouvez vous déconnecter en cliquant sur le lien **Logout (Déconnexion)** dans le menu déroulant. +
    + + ## Étapes suivantes + + Beau travail! Si vous en êtes arrivé là, vous devriez avoir la connexion, la déconnexion et les informations de profil utilisateur actives dans votre application. + + Cela conclut notre tutoriel de démarrage rapide, mais il y a tellement plus à explorer. Pour en savoir plus sur ce que vous pouvez faire avec Auth0, consultez : + + * [Auth0 Dashboard](https://manage.auth0.com/#) : apprenez à configurer et gérer votre locataire et vos applications Auth0 + * [Trousse SDK auth0-java-mvc-common](https://github.com/auth0/auth0-java-mvc-common) : explorez en détail la trousse SDK utilisée dans ce tutoriel + * [Auth0 Marketplace](https://marketplace.auth0.com/) : découvrez des intégrations que vous pouvez activer pour étendre les fonctionnalités d’Auth0 +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    diff --git a/main/docs/fr-ca/quickstart/webapp/java-spring-boot/interactive.mdx b/main/docs/fr-ca/quickstart/webapp/java-spring-boot/interactive.mdx index 7f09260e3..409db6dd7 100644 --- a/main/docs/fr-ca/quickstart/webapp/java-spring-boot/interactive.mdx +++ b/main/docs/fr-ca/quickstart/webapp/java-spring-boot/interactive.mdx @@ -1,268 +1,270 @@ ---- -title: "Ajouter une fonctionnalité de connexion à votre application Spring Web" -permalink: "interactive" -'description': "Ce guide explique comment intégrer Auth0 à une application Spring Boot à l’aide de la trousse SDK Spring Boot Auth0." -'og:title': "Ajouter une fonctionnalité de connexion à votre application Spring Web" -'og:description': "Ce guide explique comment intégrer Auth0 à une application Spring Boot à l’aide de la trousse SDK Spring Boot Auth0." -'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/spring.png" -'twitter:title': "Ajouter une fonctionnalité de connexion à votre application Spring Web" -'twitter:description': "Ce guide explique comment intégrer Auth0 à une application Spring Boot à l’aide de la trousse SDK Spring Boot Auth0." -sidebarTitle: Java Spring Boot ---- - -import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; -import { LoggedInForm } from "/snippets/Login.jsx"; -import Application from "/snippets/quickstart/webapp/java-spring-boot/application.yml.mdx"; -import Securityconfig from "/snippets/quickstart/webapp/java-spring-boot/SecurityConfig.java.mdx"; -import Index from "/snippets/quickstart/webapp/java-spring-boot/index.html.mdx"; -import Homecontroller from "/snippets/quickstart/webapp/java-spring-boot/HomeController.java.mdx"; -import Securityconfigwithlogout from "/snippets/quickstart/webapp/java-spring-boot/SecurityConfigWithLogout.java.mdx"; - -export const sections = [ - { id: "configuration-d-auth0", title: "Configuration d’Auth0" }, - { id: "configurer-l-application-sprint-boot", title: "Configurer l’application Sprint Boot" }, - { id: "configurer-spring-security", title: "Configurer Spring Security" }, - { id: "ajouter-une-fonctionnalité-de-connexion-à-votre-application", title: "Ajouter une fonctionnalité de connexion à votre application" } -] - - - - ### Vous utilisez Spring WebFlux? - - Ce tutoriel utilise [Spring MVC](https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html). Si vous utilisez [Spring WebFlux](https://docs.spring.io/spring/docs/current/spring-framework-reference/web-reactive.html#spring-web-reactive), les étapes pour ajouter l’authentification sont similaires, mais certains détails d’implémentation sont différents. Reportez-vous au [Code d’exemple Spring Boot WebFlux](https://github.com/auth0-samples/auth0-spring-boot-login-samples/tree/master/webflux-login) pour voir comment intégrer Auth0 à votre application Spring Boot WebFlux. - -
    - Pour utiliser les services Auth0, vous devez avoir une application installée dans Auth0 Dashboard. L’application Auth0 est l’endroit où vous allez configurer le fonctionnement de l’authentification pour le projet que vous développez. - - ### Configurer une application - - Utilisez le sélecteur interactif pour créer une nouvelle application Auth0 ou sélectionner une application existante qui représente le projet avec lequel vous souhaitez effectuer l’intégration. Dans Auth0, chaque application se voit attribuer un identifiant client unique alphanumérique que votre code d’application utilisera pour appeler les API Auth0 via la trousse SDK. - - Tous les paramètres que vous configurez à l’aide de ce guide de démarrage rapide seront automatiquement mis à jour pour votre application dans le [Tableau de bord](https://manage.auth0.com/#/), qui est l’endroit où vous pourrez gérer vos applications à l’avenir. - - Si vous préférez explorer une configuration complète, consultez plutôt un exemple d’application. - - ### Configuration des URL de rappel - - Une URL de rappel est une URL intégrée dans votre application vers laquelle vous souhaitez qu’Auth0 redirige les utilisateurs après leur authentification. Si elle n’est pas définie, les utilisateurs ne seront pas redirigés vers votre application après s’être connectés. - - - Si vous suivez notre projet à titre d’exemple, définissez ceci sur - `http://localhost:3000/login/oauth2/code/okta`. - - - ### Configuration des URL de déconnexion - - Une URL de déconnexion est une URL intégrée dans votre application vers laquelle vous souhaitez qu’Auth0 redirige les utilisateurs après leur déconnexion. Si elle n’est pas définie, les utilisateurs ne pourront pas se déconnecter de votre application et recevront un message d’erreur. - - - Si vous suivez notre projet à titre d’exemple, définissez ceci sur - `http://localhost:3000`. - -
    - -
    - ### Ajouter les dépendances Spring - - Pour intégrer votre application Spring Boot avec Auth0, incluez [Okta Spring Boot Starter](https://github.com/okta/okta-spring-boot/) dans les dépendances de votre application. - - - Ce guide utilise [Thymeleaf](https://www.thymeleaf.org/) et le [module d’intégration Spring Security](https://github.com/thymeleaf/thymeleaf-extras-springsecurity) pour la couche d’affichage. Si vous utilisez une technologie d’affichage différente, la configuration et les composants de Spring Security restent les mêmes. - - - Si vous utilisez Gradle, vous pouvez inclure ces dépendances comme indiqué ci-dessous. - - ``` - plugins { - id 'java' - id 'org.springframework.boot' version '3.1.4' - id 'io.spring.dependency-management' version '1.1.3' - } - implementation 'com.okta.spring:okta-spring-boot-starter:3.0.5' - implementation 'org.springframework.boot:spring-boot-starter-web' - implementation 'org.springframework.boot:spring-boot-starter-thymeleaf' - implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity6' - implementation 'nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect' - ``` - - Si vous utilisez Maven : - - ```html - - org.springframework.boot - spring-boot-starter-parent - 3.1.4 - - - - - com.okta - okta-spring-boot-starter - 3.0.5 - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-oauth2-client - - - org.springframework.boot - spring-boot-starter-thymeleaf - - - org.thymeleaf.extras - thymeleaf-extras-springsecurity6 - - - nz.net.ultraq.thymeleaf - thymeleaf-layout-dialect - - - ``` -
    - -
    - Okta Spring Boot Starter facilite la configuration de votre application avec Auth0. L’exemple ci-dessous utilise un fichier `application.yml`, mais vous pouvez également utiliser des fichiers de propriétés ou tout autre [mécanisme d’externalisation pris en charge](https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-external-config). - - ``` - #src/main/resources/application.yml - okta: - oauth2: - issuer: https://{yourDomain}/ - - client-id: {yourClientId} - - client-secret: {yourClientSecret} - - #The sample and instructions above for the callback and logout URL configuration use port 3000. - #If you wish to use a different port, change this and be sure your callback and logout URLs are - #configured with the correct port. - server: - port: 3000 - ``` -
    - -
    - Pour permettre aux utilisateurs de se connecter avec Auth0, créez une classe qui enregistrera une [SecurityFilterChain](https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/web/SecurityFilterChain.html) et ajoutez l’annotation `@Configuration`. - - - Vous pouvez configurer l’instance [HttpSecurity](https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/config/annotation/web/builders/HttpSecurity.html) pour qu’elle exige une authentification sur tous les chemins ou seulement sur certains d’entre eux. Par exemple, pour exiger l’authentification sur tous les chemins à l’exception de la page d’accueil : - - `http` - - ```http - .authorizeHttpRequests(authorize -> authorize - .requestMatchers("/").permitAll() - .anyRequest().authenticated() - ); - ``` - - ## Ajouter une page d’accueil - - Okta Spring Boot Starter utilisera la configuration client que vous avez définie précédemment pour gérer la connexion lorsqu’un utilisateur visite le chemin `//oauth2/authorization/okta` de votre application. Vous pouvez l’utiliser pour créer un lien de connexion dans votre application. - - Cette page renvoie les attributs de l’utilisateur lorsque celui-ci s’authentifie. Vous utiliserez le lien `/logout` dans le modèle pour mettre en œuvre la fonctionnalité de déconnexion. - - ## Ajouter un contrôleur - - Créez un contrôleur pour traiter la demande entrante. Ce contrôleur crée la page `index.html`. Lorsque l’utilisateur s’authentifie, l’application récupère les attributs d’information du profil utilisateur pour créer la page. - - - ##### Point de contrôle - - Lorsque vous cliquez sur le lien de connexion, vérifiez que l’application vous redirige vers la page [Connexion universelle Auth0](https://auth0.com/universal-login) et que vous pouvez maintenant vous connecter ou vous inscrire en utilisant un nom d’utilisateur et un mot de passe, ou un réseau social. - - - ![null](/docs/images/fr-ca/cdy7uua7fh8z/7L6lZ6xCi1L7sJBFZUPb9g/215ad0b724c138290b0b217edb5ddf96/Login_Screen_-_French.png) - - Auth0 active le fournisseur social Google par défaut sur les nouveaux locataires et vous offre des clés de développeur pour tester la connexion avec des [fournisseurs d’identité sociale](https://auth0.com/docs/connections/identity-providers-social). Toutefois, ces clés de développeur présentent certaines limitations qui peuvent entraîner un comportement différent de votre application. Pour plus de détails sur ce comportement et comment le résoudre, consultez le document [Tester les connexions sociales avec des clés de développeur Auth0](https://auth0.com/docs/connections/social/devkeys#limitations-of-developer-keys). - - ## Ajouter une fonctionnalité de déconnexion à votre application - - Maintenant que les utilisateurs peuvent se connecter à votre application, ils ont besoin d’un [moyen de se déconnecter](https://auth0.com/docs/logout/guides/logout-auth0). Par défaut, lorsque la déconnexion est activée, Spring Security déconnecte l’utilisateur de votre application et efface la session. Pour permettre une déconnexion réussie de Auth0, vous pouvez fournir un `LogoutHandler` pour rediriger les utilisateurs vers votre [point de terminaison de déconnexion Auth0](https://auth0.com/docs/api/authentication?javascript#logout) (`https://{yourDomain}/v2/logout`) et ensuite les rediriger immédiatement vers votre application. - - Dans la classe `SecurityConfig`, fournissez un `LogoutHandler` qui redirige vers le point de terminaison de déconnexion Auth0, et configurez `HTTPSecurity` pour ajouter le gestionnaire de déconnexion. - - - ##### Point de contrôle - Lorsque vous cliquez sur le lien de déconnexion, l’application doit vous rediriger vers l’adresse que vous avez spécifiée comme l’une des « URL de déconnexion autorisées » dans les « Paramètres d’application » et vous n’êtes plus connecté à votre application. - - -
    - - - ## Étapes suivantes - - Beau travail! Si vous en êtes arrivé là, vous devriez avoir la connexion, la déconnexion et les informations de profil utilisateur actives dans votre application. - - Cela conclut notre tutoriel de démarrage rapide, mais il y a tellement plus à explorer. Pour en savoir plus sur ce que vous pouvez faire avec Auth0, consultez : - - * [Auth0 Dashboard](https://manage.auth0.com/#) : apprenez à configurer et gérer votre locataire et vos applications Auth0 - * [Trousse SDK Okta Spring Boot Starter](https://github.com/okta/okta-spring-boot/) : explorez en détail la trousse SDK utilisée dans ce tutoriel - * [Auth0 Marketplace](https://marketplace.auth0.com/) : découvrez des intégrations que vous pouvez activer pour étendre les fonctionnalités d’Auth0 -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    +--- +title: "Ajouter une fonctionnalité de connexion à votre application Spring Web" +permalink: "interactive" +'description': "Ce guide explique comment intégrer Auth0 à une application Spring Boot à l’aide de la trousse SDK Spring Boot Auth0." +'og:title': "Ajouter une fonctionnalité de connexion à votre application Spring Web" +'og:description': "Ce guide explique comment intégrer Auth0 à une application Spring Boot à l’aide de la trousse SDK Spring Boot Auth0." +'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/spring.png" +'twitter:title': "Ajouter une fonctionnalité de connexion à votre application Spring Web" +'twitter:description': "Ce guide explique comment intégrer Auth0 à une application Spring Boot à l’aide de la trousse SDK Spring Boot Auth0." +sidebarTitle: Java Spring Boot +--- + +import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; +import { LoggedInForm } from "/snippets/Login.jsx"; +import Application from "/snippets/quickstart/webapp/java-spring-boot/application.yml.mdx"; +import Securityconfig from "/snippets/quickstart/webapp/java-spring-boot/SecurityConfig.java.mdx"; +import Index from "/snippets/quickstart/webapp/java-spring-boot/index.html.mdx"; +import Homecontroller from "/snippets/quickstart/webapp/java-spring-boot/HomeController.java.mdx"; +import Securityconfigwithlogout from "/snippets/quickstart/webapp/java-spring-boot/SecurityConfigWithLogout.java.mdx"; + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + +export const sections = [ + { id: "configuration-d-auth0", title: "Configuration d’Auth0" }, + { id: "configurer-l-application-sprint-boot", title: "Configurer l’application Sprint Boot" }, + { id: "configurer-spring-security", title: "Configurer Spring Security" }, + { id: "ajouter-une-fonctionnalité-de-connexion-à-votre-application", title: "Ajouter une fonctionnalité de connexion à votre application" } +] + + + + ### Vous utilisez Spring WebFlux? + + Ce tutoriel utilise [Spring MVC](https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html). Si vous utilisez [Spring WebFlux](https://docs.spring.io/spring/docs/current/spring-framework-reference/web-reactive.html#spring-web-reactive), les étapes pour ajouter l’authentification sont similaires, mais certains détails d’implémentation sont différents. Reportez-vous au [Code d’exemple Spring Boot WebFlux](https://github.com/auth0-samples/auth0-spring-boot-login-samples/tree/master/webflux-login) pour voir comment intégrer Auth0 à votre application Spring Boot WebFlux. + +
    + Pour utiliser les services Auth0, vous devez avoir une application installée dans Auth0 Dashboard. L’application Auth0 est l’endroit où vous allez configurer le fonctionnement de l’authentification pour le projet que vous développez. + + ### Configurer une application + + Utilisez le sélecteur interactif pour créer une nouvelle application Auth0 ou sélectionner une application existante qui représente le projet avec lequel vous souhaitez effectuer l’intégration. Dans Auth0, chaque application se voit attribuer un identifiant client unique alphanumérique que votre code d’application utilisera pour appeler les API Auth0 via la trousse SDK. + + Tous les paramètres que vous configurez à l’aide de ce guide de démarrage rapide seront automatiquement mis à jour pour votre application dans le [Tableau de bord](https://manage.auth0.com/#/), qui est l’endroit où vous pourrez gérer vos applications à l’avenir. + + Si vous préférez explorer une configuration complète, consultez plutôt un exemple d’application. + + ### Configuration des URL de rappel + + Une URL de rappel est une URL intégrée dans votre application vers laquelle vous souhaitez qu’Auth0 redirige les utilisateurs après leur authentification. Si elle n’est pas définie, les utilisateurs ne seront pas redirigés vers votre application après s’être connectés. + + + Si vous suivez notre projet à titre d’exemple, définissez ceci sur + `http://localhost:3000/login/oauth2/code/okta`. + + + ### Configuration des URL de déconnexion + + Une URL de déconnexion est une URL intégrée dans votre application vers laquelle vous souhaitez qu’Auth0 redirige les utilisateurs après leur déconnexion. Si elle n’est pas définie, les utilisateurs ne pourront pas se déconnecter de votre application et recevront un message d’erreur. + + + Si vous suivez notre projet à titre d’exemple, définissez ceci sur + `http://localhost:3000`. + +
    + +
    + ### Ajouter les dépendances Spring + + Pour intégrer votre application Spring Boot avec Auth0, incluez [Okta Spring Boot Starter](https://github.com/okta/okta-spring-boot/) dans les dépendances de votre application. + + + Ce guide utilise [Thymeleaf](https://www.thymeleaf.org/) et le [module d’intégration Spring Security](https://github.com/thymeleaf/thymeleaf-extras-springsecurity) pour la couche d’affichage. Si vous utilisez une technologie d’affichage différente, la configuration et les composants de Spring Security restent les mêmes. + + + Si vous utilisez Gradle, vous pouvez inclure ces dépendances comme indiqué ci-dessous. + + ``` + plugins { + id 'java' + id 'org.springframework.boot' version '3.1.4' + id 'io.spring.dependency-management' version '1.1.3' + } + implementation 'com.okta.spring:okta-spring-boot-starter:3.0.5' + implementation 'org.springframework.boot:spring-boot-starter-web' + implementation 'org.springframework.boot:spring-boot-starter-thymeleaf' + implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity6' + implementation 'nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect' + ``` + + Si vous utilisez Maven : + + ```html + + org.springframework.boot + spring-boot-starter-parent + 3.1.4 + + + + + com.okta + okta-spring-boot-starter + 3.0.5 + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-oauth2-client + + + org.springframework.boot + spring-boot-starter-thymeleaf + + + org.thymeleaf.extras + thymeleaf-extras-springsecurity6 + + + nz.net.ultraq.thymeleaf + thymeleaf-layout-dialect + + + ``` +
    + +
    + Okta Spring Boot Starter facilite la configuration de votre application avec Auth0. L’exemple ci-dessous utilise un fichier `application.yml`, mais vous pouvez également utiliser des fichiers de propriétés ou tout autre [mécanisme d’externalisation pris en charge](https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-external-config). + + ``` + #src/main/resources/application.yml + okta: + oauth2: + issuer: https://{yourDomain}/ + + client-id: {yourClientId} + + client-secret: {yourClientSecret} + + #The sample and instructions above for the callback and logout URL configuration use port 3000. + #If you wish to use a different port, change this and be sure your callback and logout URLs are + #configured with the correct port. + server: + port: 3000 + ``` +
    + +
    + Pour permettre aux utilisateurs de se connecter avec Auth0, créez une classe qui enregistrera une [SecurityFilterChain](https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/web/SecurityFilterChain.html) et ajoutez l’annotation `@Configuration`. + + + Vous pouvez configurer l’instance [HttpSecurity](https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/config/annotation/web/builders/HttpSecurity.html) pour qu’elle exige une authentification sur tous les chemins ou seulement sur certains d’entre eux. Par exemple, pour exiger l’authentification sur tous les chemins à l’exception de la page d’accueil : + + `http` + + ```http + .authorizeHttpRequests(authorize -> authorize + .requestMatchers("/").permitAll() + .anyRequest().authenticated() + ); + ``` + + ## Ajouter une page d’accueil + + Okta Spring Boot Starter utilisera la configuration client que vous avez définie précédemment pour gérer la connexion lorsqu’un utilisateur visite le chemin `//oauth2/authorization/okta` de votre application. Vous pouvez l’utiliser pour créer un lien de connexion dans votre application. + + Cette page renvoie les attributs de l’utilisateur lorsque celui-ci s’authentifie. Vous utiliserez le lien `/logout` dans le modèle pour mettre en œuvre la fonctionnalité de déconnexion. + + ## Ajouter un contrôleur + + Créez un contrôleur pour traiter la demande entrante. Ce contrôleur crée la page `index.html`. Lorsque l’utilisateur s’authentifie, l’application récupère les attributs d’information du profil utilisateur pour créer la page. + + + ##### Point de contrôle + + Lorsque vous cliquez sur le lien de connexion, vérifiez que l’application vous redirige vers la page [Connexion universelle Auth0](https://auth0.com/universal-login) et que vous pouvez maintenant vous connecter ou vous inscrire en utilisant un nom d’utilisateur et un mot de passe, ou un réseau social. + + + ![null](/docs/images/fr-ca/cdy7uua7fh8z/7L6lZ6xCi1L7sJBFZUPb9g/215ad0b724c138290b0b217edb5ddf96/Login_Screen_-_French.png) + + Auth0 active le fournisseur social Google par défaut sur les nouveaux locataires et vous offre des clés de développeur pour tester la connexion avec des [fournisseurs d’identité sociale](https://auth0.com/docs/connections/identity-providers-social). Toutefois, ces clés de développeur présentent certaines limitations qui peuvent entraîner un comportement différent de votre application. Pour plus de détails sur ce comportement et comment le résoudre, consultez le document [Tester les connexions sociales avec des clés de développeur Auth0](https://auth0.com/docs/connections/social/devkeys#limitations-of-developer-keys). + + ## Ajouter une fonctionnalité de déconnexion à votre application + + Maintenant que les utilisateurs peuvent se connecter à votre application, ils ont besoin d’un [moyen de se déconnecter](https://auth0.com/docs/logout/guides/logout-auth0). Par défaut, lorsque la déconnexion est activée, Spring Security déconnecte l’utilisateur de votre application et efface la session. Pour permettre une déconnexion réussie de Auth0, vous pouvez fournir un `LogoutHandler` pour rediriger les utilisateurs vers votre [point de terminaison de déconnexion Auth0](https://auth0.com/docs/api/authentication?javascript#logout) (`https://{yourDomain}/v2/logout`) et ensuite les rediriger immédiatement vers votre application. + + Dans la classe `SecurityConfig`, fournissez un `LogoutHandler` qui redirige vers le point de terminaison de déconnexion Auth0, et configurez `HTTPSecurity` pour ajouter le gestionnaire de déconnexion. + + + ##### Point de contrôle + Lorsque vous cliquez sur le lien de déconnexion, l’application doit vous rediriger vers l’adresse que vous avez spécifiée comme l’une des « URL de déconnexion autorisées » dans les « Paramètres d’application » et vous n’êtes plus connecté à votre application. + + +
    + + + ## Étapes suivantes + + Beau travail! Si vous en êtes arrivé là, vous devriez avoir la connexion, la déconnexion et les informations de profil utilisateur actives dans votre application. + + Cela conclut notre tutoriel de démarrage rapide, mais il y a tellement plus à explorer. Pour en savoir plus sur ce que vous pouvez faire avec Auth0, consultez : + + * [Auth0 Dashboard](https://manage.auth0.com/#) : apprenez à configurer et gérer votre locataire et vos applications Auth0 + * [Trousse SDK Okta Spring Boot Starter](https://github.com/okta/okta-spring-boot/) : explorez en détail la trousse SDK utilisée dans ce tutoriel + * [Auth0 Marketplace](https://marketplace.auth0.com/) : découvrez des intégrations que vous pouvez activer pour étendre les fonctionnalités d’Auth0 +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    diff --git a/main/docs/fr-ca/quickstart/webapp/java/interactive.mdx b/main/docs/fr-ca/quickstart/webapp/java/interactive.mdx index 96e1199f3..3f3ad1110 100644 --- a/main/docs/fr-ca/quickstart/webapp/java/interactive.mdx +++ b/main/docs/fr-ca/quickstart/webapp/java/interactive.mdx @@ -1,288 +1,290 @@ ---- -title: "Ajouter une fonctionnalité de connexion à votre Application Java Servlet" -permalink: "interactive" -'description': "Ce guide explique comment intégrer Auth0 dans n’importe quelle application Java Servlet, nouvelle ou existante." -'og:title': "Ajouter une fonctionnalité de connexion à votre Application Java Servlet" -'og:description': "Ce guide explique comment intégrer Auth0 dans n’importe quelle application Java Servlet, nouvelle ou existante." -'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/java.png" -'twitter:title': "Ajouter une fonctionnalité de connexion à votre Application Java Servlet" -'twitter:description': "Ce guide explique comment intégrer Auth0 dans n’importe quelle application Java Servlet, nouvelle ou existante." -sidebarTitle: Java ---- - -import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; -import { LoggedInForm } from "/snippets/Login.jsx"; -import Web from "/snippets/quickstart/webapp/java/web.xml.mdx"; -import Authenticationcontrollerprovider from "/snippets/quickstart/webapp/java/AuthenticationControllerProvider.java.mdx"; -import Loginservlet from "/snippets/quickstart/webapp/java/LoginServlet.java.mdx"; -import Callbackservlet from "/snippets/quickstart/webapp/java/CallbackServlet.java.mdx"; -import Homeservlet from "/snippets/quickstart/webapp/java/HomeServlet.java.mdx"; -import Logoutservlet from "/snippets/quickstart/webapp/java/LogoutServlet.java.mdx"; - -export const sections = [ - { id: "configuration-d-auth0", title: "Configuration d’Auth0" }, - { id: "intégrer-auth0-dans-votre-application", title: "Intégrer Auth0 dans votre application" }, - { id: "configurer-votre-application-java", title: "Configurer votre application Java" }, - { id: "créer-l-authenticationcontroller", title: "Créer l’AuthenticationController" }, - { id: "redirection-de-connexion", title: "Redirection de connexion" }, - { id: "gérer-les-jetons", title: "Gérer les jetons" }, - { id: "afficher-la-page-d-accueil", title: "Afficher la page d’accueil" }, - { id: "gérer-la-déconnexion", title: "Gérer la déconnexion" }, - { id: "exécuter-l-exemple", title: "Exécuter l’exemple" } -] - - - - Auth0 vous permet d’ajouter rapidement l’authentification et de pouvoir accéder aux informations relatives au profil utilisateur dans votre application. Ce guide explique comment intégrer Auth0 dans n’importe quelle application Java Servlet, nouvelle ou existante. - -
    - Pour utiliser les services Auth0, vous devez avoir une application installée dans Auth0 Dashboard. L’application Auth0 est l’endroit où vous allez configurer le fonctionnement de l’authentification pour le projet que vous développez. - - ### Configurer une application - - Utilisez le sélecteur interactif pour créer une nouvelle application Auth0 ou sélectionner une application existante qui représente le projet avec lequel vous souhaitez effectuer l’intégration. Dans Auth0, chaque application se voit attribuer un identifiant client unique alphanumérique que votre code d’application utilisera pour appeler les API Auth0 via la trousse SDK. - - Tous les paramètres que vous configurez à l’aide de ce guide de démarrage rapide seront automatiquement mis à jour pour votre application dans le [Tableau de bord](https://manage.auth0.com/#/), qui est l’endroit où vous pourrez gérer vos applications à l’avenir. - - Si vous préférez explorer une configuration complète, consultez plutôt un exemple d’application. - - ### Configuration des URL de rappel - - Une URL de rappel est une URL intégrée dans votre application vers laquelle vous souhaitez qu’Auth0 redirige les utilisateurs après leur authentification. Si elle n’est pas définie, les utilisateurs ne seront pas redirigés vers votre application après s’être connectés. - - - Si vous suivez notre exemple de projet, définissez cette URL comme suit : `http://localhost:3000``/callback`. - - - ### Configuration des URL de déconnexion - - Une URL de déconnexion est une URL intégrée dans votre application vers laquelle vous souhaitez qu’Auth0 redirige les utilisateurs après leur déconnexion. Si elle n’est pas définie, les utilisateurs ne pourront pas se déconnecter de votre application et recevront un message d’erreur. - - - Si vous suivez notre exemple de projet, définissez cette URL comme suit : `http://localhost:3000/logout`. - -
    - -
    - ### Régler les dépendances. - - Pour intégrer votre application Java avec Auth0, ajoutez les dépendances suivantes : - - - **javax.servlet-api** - - : est la bibliothèque qui vous permet de créer des servlets Java. Vous devez ensuite ajouter une dépendance de serveur comme Tomcat ou Gretty, selon votre choix. Consultez notre code d’exemple pour plus d’informations. - - **auth0-java-mvc-commons** : est la [bibliothèque Java](https://github.com/auth0/auth0-java-mvc-common) qui vous permet d’utiliser Auth0 avec Java pour des applications Web MVC côté serveur. Elle génère l’URL d’autorisation que vous devez appeler pour authentifier et valide le résultat reçu au retour afin d’obtenir finalement les [jetons Auth0](https://auth0.com/docs/tokens) qui identifient l’utilisateur. - - Si vous utilisez Gradle, ajoutez-les à votre `build.gradle` : - - ``` - // build.gradle - compile 'javax.servlet:javax.servlet-api:3.1.0' - compile 'com.auth0:mvc-auth-commons:1.+'W - ``` - - Si vous utilisez Maven, ajoutez-les à votre fichier `pom.xml` : - - ```html - - - com.auth0 - mvc-auth-commons - [1.0, 2.0) - - - javax.servlet - javax.servlet-api - 3.1.0 - - ``` -
    - -
    - Votre application Java a besoin de certaines informations pour s’authentifier auprès de votre compte Auth0. Les exemples lisent ces informations à partir du fichier descripteur de déploiement `src/main/webapp/WEB-INF/web.xml`, mais vous pouvez les stocker ailleurs. - - Ces informations seront utilisées pour configurer la bibliothèque **auth0-java-mvc-commons** afin de permettre aux utilisateurs de se connecter à votre application. Pour en savoir plus sur la bibliothèque, y compris ses différentes options de configuration, consultez la [documentation de la bibliothèque](https://github.com/auth0/auth0-java-mvc-common/blob/master/README.md). - - ### Vérifier les attributs remplis - - Si vous avez téléchargé cet exemple en utilisant le bouton **Download Sample (Télécharger l’exemple)**, les attributs `domain`, `clientId` et `clientSecret` seront remplis pour vous. Vous devez vérifier que les valeurs sont correctes, surtout si vous avez plusieurs applications Auth0 dans votre compte. - - ### Structure du projet - - L’exemple de projet, qui peut être téléchargé en utilisant le bouton **Download Sample (Télécharger l’exemple)** a la structure suivante : - - ``` - - src - -- main - ---- java - ------ com - -------- auth0 - ---------- example - ------------ Auth0Filter.java - ------------ AuthenticationControllerProvider.java - ------------ HomeServlet.java - ------------ CallbackServlet.java - ------------ LoginServlet.java - ------------ LogoutServlet.java - ---- webapp - ------ WEB-INF - -------- jsp - ---------- home.jsp - -------- web.xml - - build.gradle - ``` - - Le projet contient un seul JSP : `home.jsp` qui affichera les jetons associés à l’utilisateur après une connexion réussie et proposera l’option de déconnexion. - - Le projet contient un WebFilter : le `Auth0Filter.java` qui vérifiera l’existence de jetons avant de donner à l’utilisateur accès à notre chemin protégé `/portal/*`. Si les jetons n’existent pas, la requête sera redirigée vers `LoginServlet`. - - Le projet contient également quatre servlets : - - - `LoginServlet.java` : Appelé lorsque l’utilisateur essaie de se connecter. Le servlet utilise les paramètres `client_id` et `domain` pour créer une URL d’autorisation valide et y redirige l’utilisateur. - - `CallbackServlet.java` : Le servlet enregistre les requêtes adressées à notre URL de rappel et traite les données pour obtenir les identifiants. Après une connexion réussie, les identifiants sont ensuite enregistrés dans la HttpSession de la requête. - - `HomeServlet.java` : Le servlet lit les jetons précédemment enregistrés et les affiche sur la ressource `home.jsp`. - - `LogoutServlet.java` : Appelé lorsque l’utilisateur clique sur le lien de déconnexion. Le servlet invalide la session de l’utilisateur et redirige l’utilisateur vers la page de connexion, gérée par `LoginServlet`. - - `AuthenticationControllerProvider.java` : Responsable de la création et de la gestion d’une seule instance de `AuthenticationController` -
    - -
    - Pour permettre aux utilisateurs de s’authentifier, créez une instance de l’`AuthenticationController` fournie par la trousse SDK `auth0-java-mvc-commons` en utilisant le `domain`, `clientId`, et `clientSecret`. L’exemple présente comment configurer le composant pour l’utiliser avec des jetons signés à l’aide de l’algorithme de signature asymétrique RS256, en précisant un `JwkProvider` pour récupérer la clé publique utilisée pour vérifier la signature du jeton. Consultez le [référentiel jwks-rsa-java](https://github.com/auth0/jwks-rsa-java) pour en savoir plus sur les options de configuration supplémentaires. Si vous utilisez HS256, il n’est pas nécessaire de configurer `JwkProvider`. - - - `AuthenticationController` ne stocke aucun contexte et est destiné à être réutilisé. Une création inutile peut entraîner la génération de ressources supplémentaires, ce qui peut avoir une incidence sur les performances. - -
    - -
    - Pour permettre aux utilisateurs de se connecter, votre application les redirigera vers la page de Connexion universelle. En utilisant l’instance `AuthenticationController` , vous pouvez générer l’URL de redirection en appelant la méthode `buildAuthorizeUrl(HttpServletRequest request`, `HttpServletResponse response`, `String redirectUrl)`. L’URL de redirection doit être celle qui a été ajoutée aux **URL de rappel autorisées** de votre application Auth0. -
    - -
    - Après que l’utilisateur s’est connecté, le résultat sera reçu dans notre `CallbackServlet` via une requête HTTP GET ou POST. Comme nous utilisons le flux de code d’autorisation (par défaut), une requête GET sera envoyée. Si vous avez configuré la bibliothèque pour le flux implicite, une requête POST sera plutôt envoyée. - - La requête contient le contexte d’appel que la bibliothèque a précédemment défini en générant l’URL d’autorisation avec `AuthenticationController`. Lorsqu’il est passé au contrôleur, vous recevez soit une instance `Tokens` valide soit une Exception indiquant ce qui a mal tourné. En cas d’appel réussi, vous devez enregistrer les identifiants afin de pouvoir y accéder ultérieurement. Vous pouvez utiliser `HttpSession` de la requête en utilisant la classe `SessionsUtils` comprise dans la bibliothèque. - - - Il est recommandé d’enregistrer le moment où nous avons demandé les jetons ainsi que la valeur `expiresIn` reçue, afin que la prochaine fois que nous utiliserons le jeton, nous puissions vérifier s’il a déjà expiré ou s’il est encore valide. Pour les besoins de cet exemple, nous ignorerons cette validation. - -
    - -
    - Maintenant que l’utilisateur est authentifié (les jetons existent), `Auth0Filter` leur permettra d’accéder à nos ressources protégées. Dans le `HomeServlet` nous obtenons les jetons de la session de la requête et les définissons comme l’attribut `userId` afin qu’ils puissent être utilisés dans le code JSP. -
    - -
    - Pour gérer adéquatement la déconnexion, nous devons effacer la session et déconnecter l’utilisateur d’Auth0. Cette opération est gérée dans `LogoutServlet` de notre exemple d’application. - - Tout d’abord, nous effaçons la session en appelant `request.getSession().invalidate()`. Nous générons ensuite l’URL de déconnexion, en veillant à inclure le paramètre de requête `returnTo` qui est l’endroit où l’utilisateur sera redirigé après la déconnexion. Enfin, nous redirigeons la réponse vers notre URL de déconnexion. -
    - -
    - Pour exécuter l’exemple à partir d’un terminal, placez-vous dans le dossier racine du projet et exécutez la ligne suivante : - - `./gradlew clean app` - - Après quelques secondes, l’application sera accessible sur `http://localhost:3000/`. Essayez d’accéder à la ressource protégée http://localhost:3000/portal/home et notez comment vous êtes redirigé par `Auth0Filter` vers la page de connexion Auth0. Le gadget logiciel affiche toutes les connexions via réseaux sociaux et de bases de données que vous avez définies pour cette application dans le [tableau de bord](https://manage.auth0.com/#/). - - ![null](/docs/images/fr-ca/cdy7uua7fh8z/7L6lZ6xCi1L7sJBFZUPb9g/215ad0b724c138290b0b217edb5ddf96/Login_Screen_-_French.png) - - Vous serez en mesure de voir le contenu de la page d’accueil après une authentification réussie. - - ![null](/docs/images/fr-ca/cdy7uua7fh8z/FzK3jxfSGoeIDYQamxnJl/6b608e39ff39e044644193cfd2ee0f69/java-step-9-2.png) - - Déconnectez-vous en cliquant sur le bouton **logout (déconnexion)** en haut à droite de la page d’accueil. -
    - - ## Étapes suivantes - - Beau travail! Si vous en êtes arrivé là, vous devriez avoir la connexion, la déconnexion et les informations de profil utilisateur actives dans votre application. - - Cela conclut notre tutoriel de démarrage rapide, mais il y a tellement plus à explorer. Pour en savoir plus sur ce que vous pouvez faire avec Auth0, consultez : - - * [Auth0 Dashboard](https://manage.auth0.com/#) : apprenez à configurer et gérer votre locataire et vos applications Auth0 - * [Trousse SDK auth0-java-mvc-common](https://github.com/auth0/auth0-java-mvc-common) : explorez en détail la trousse SDK utilisée dans ce tutoriel - * [Auth0 Marketplace](https://marketplace.auth0.com/) : découvrez des intégrations que vous pouvez activer pour étendre les fonctionnalités d’Auth0 -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    +--- +title: "Ajouter une fonctionnalité de connexion à votre Application Java Servlet" +permalink: "interactive" +'description': "Ce guide explique comment intégrer Auth0 dans n’importe quelle application Java Servlet, nouvelle ou existante." +'og:title': "Ajouter une fonctionnalité de connexion à votre Application Java Servlet" +'og:description': "Ce guide explique comment intégrer Auth0 dans n’importe quelle application Java Servlet, nouvelle ou existante." +'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/java.png" +'twitter:title': "Ajouter une fonctionnalité de connexion à votre Application Java Servlet" +'twitter:description': "Ce guide explique comment intégrer Auth0 dans n’importe quelle application Java Servlet, nouvelle ou existante." +sidebarTitle: Java +--- + +import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; +import { LoggedInForm } from "/snippets/Login.jsx"; +import Web from "/snippets/quickstart/webapp/java/web.xml.mdx"; +import Authenticationcontrollerprovider from "/snippets/quickstart/webapp/java/AuthenticationControllerProvider.java.mdx"; +import Loginservlet from "/snippets/quickstart/webapp/java/LoginServlet.java.mdx"; +import Callbackservlet from "/snippets/quickstart/webapp/java/CallbackServlet.java.mdx"; +import Homeservlet from "/snippets/quickstart/webapp/java/HomeServlet.java.mdx"; +import Logoutservlet from "/snippets/quickstart/webapp/java/LogoutServlet.java.mdx"; + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + +export const sections = [ + { id: "configuration-d-auth0", title: "Configuration d’Auth0" }, + { id: "intégrer-auth0-dans-votre-application", title: "Intégrer Auth0 dans votre application" }, + { id: "configurer-votre-application-java", title: "Configurer votre application Java" }, + { id: "créer-l-authenticationcontroller", title: "Créer l’AuthenticationController" }, + { id: "redirection-de-connexion", title: "Redirection de connexion" }, + { id: "gérer-les-jetons", title: "Gérer les jetons" }, + { id: "afficher-la-page-d-accueil", title: "Afficher la page d’accueil" }, + { id: "gérer-la-déconnexion", title: "Gérer la déconnexion" }, + { id: "exécuter-l-exemple", title: "Exécuter l’exemple" } +] + + + + Auth0 vous permet d’ajouter rapidement l’authentification et de pouvoir accéder aux informations relatives au profil utilisateur dans votre application. Ce guide explique comment intégrer Auth0 dans n’importe quelle application Java Servlet, nouvelle ou existante. + +
    + Pour utiliser les services Auth0, vous devez avoir une application installée dans Auth0 Dashboard. L’application Auth0 est l’endroit où vous allez configurer le fonctionnement de l’authentification pour le projet que vous développez. + + ### Configurer une application + + Utilisez le sélecteur interactif pour créer une nouvelle application Auth0 ou sélectionner une application existante qui représente le projet avec lequel vous souhaitez effectuer l’intégration. Dans Auth0, chaque application se voit attribuer un identifiant client unique alphanumérique que votre code d’application utilisera pour appeler les API Auth0 via la trousse SDK. + + Tous les paramètres que vous configurez à l’aide de ce guide de démarrage rapide seront automatiquement mis à jour pour votre application dans le [Tableau de bord](https://manage.auth0.com/#/), qui est l’endroit où vous pourrez gérer vos applications à l’avenir. + + Si vous préférez explorer une configuration complète, consultez plutôt un exemple d’application. + + ### Configuration des URL de rappel + + Une URL de rappel est une URL intégrée dans votre application vers laquelle vous souhaitez qu’Auth0 redirige les utilisateurs après leur authentification. Si elle n’est pas définie, les utilisateurs ne seront pas redirigés vers votre application après s’être connectés. + + + Si vous suivez notre exemple de projet, définissez cette URL comme suit : `http://localhost:3000``/callback`. + + + ### Configuration des URL de déconnexion + + Une URL de déconnexion est une URL intégrée dans votre application vers laquelle vous souhaitez qu’Auth0 redirige les utilisateurs après leur déconnexion. Si elle n’est pas définie, les utilisateurs ne pourront pas se déconnecter de votre application et recevront un message d’erreur. + + + Si vous suivez notre exemple de projet, définissez cette URL comme suit : `http://localhost:3000/logout`. + +
    + +
    + ### Régler les dépendances. + + Pour intégrer votre application Java avec Auth0, ajoutez les dépendances suivantes : + + - **javax.servlet-api** + + : est la bibliothèque qui vous permet de créer des servlets Java. Vous devez ensuite ajouter une dépendance de serveur comme Tomcat ou Gretty, selon votre choix. Consultez notre code d’exemple pour plus d’informations. + - **auth0-java-mvc-commons** : est la [bibliothèque Java](https://github.com/auth0/auth0-java-mvc-common) qui vous permet d’utiliser Auth0 avec Java pour des applications Web MVC côté serveur. Elle génère l’URL d’autorisation que vous devez appeler pour authentifier et valide le résultat reçu au retour afin d’obtenir finalement les [jetons Auth0](https://auth0.com/docs/tokens) qui identifient l’utilisateur. + + Si vous utilisez Gradle, ajoutez-les à votre `build.gradle` : + + ``` + // build.gradle + compile 'javax.servlet:javax.servlet-api:3.1.0' + compile 'com.auth0:mvc-auth-commons:1.+'W + ``` + + Si vous utilisez Maven, ajoutez-les à votre fichier `pom.xml` : + + ```html + + + com.auth0 + mvc-auth-commons + [1.0, 2.0) + + + javax.servlet + javax.servlet-api + 3.1.0 + + ``` +
    + +
    + Votre application Java a besoin de certaines informations pour s’authentifier auprès de votre compte Auth0. Les exemples lisent ces informations à partir du fichier descripteur de déploiement `src/main/webapp/WEB-INF/web.xml`, mais vous pouvez les stocker ailleurs. + + Ces informations seront utilisées pour configurer la bibliothèque **auth0-java-mvc-commons** afin de permettre aux utilisateurs de se connecter à votre application. Pour en savoir plus sur la bibliothèque, y compris ses différentes options de configuration, consultez la [documentation de la bibliothèque](https://github.com/auth0/auth0-java-mvc-common/blob/master/README.md). + + ### Vérifier les attributs remplis + + Si vous avez téléchargé cet exemple en utilisant le bouton **Download Sample (Télécharger l’exemple)**, les attributs `domain`, `clientId` et `clientSecret` seront remplis pour vous. Vous devez vérifier que les valeurs sont correctes, surtout si vous avez plusieurs applications Auth0 dans votre compte. + + ### Structure du projet + + L’exemple de projet, qui peut être téléchargé en utilisant le bouton **Download Sample (Télécharger l’exemple)** a la structure suivante : + + ``` + - src + -- main + ---- java + ------ com + -------- auth0 + ---------- example + ------------ Auth0Filter.java + ------------ AuthenticationControllerProvider.java + ------------ HomeServlet.java + ------------ CallbackServlet.java + ------------ LoginServlet.java + ------------ LogoutServlet.java + ---- webapp + ------ WEB-INF + -------- jsp + ---------- home.jsp + -------- web.xml + + build.gradle + ``` + + Le projet contient un seul JSP : `home.jsp` qui affichera les jetons associés à l’utilisateur après une connexion réussie et proposera l’option de déconnexion. + + Le projet contient un WebFilter : le `Auth0Filter.java` qui vérifiera l’existence de jetons avant de donner à l’utilisateur accès à notre chemin protégé `/portal/*`. Si les jetons n’existent pas, la requête sera redirigée vers `LoginServlet`. + + Le projet contient également quatre servlets : + + - `LoginServlet.java` : Appelé lorsque l’utilisateur essaie de se connecter. Le servlet utilise les paramètres `client_id` et `domain` pour créer une URL d’autorisation valide et y redirige l’utilisateur. + - `CallbackServlet.java` : Le servlet enregistre les requêtes adressées à notre URL de rappel et traite les données pour obtenir les identifiants. Après une connexion réussie, les identifiants sont ensuite enregistrés dans la HttpSession de la requête. + - `HomeServlet.java` : Le servlet lit les jetons précédemment enregistrés et les affiche sur la ressource `home.jsp`. + - `LogoutServlet.java` : Appelé lorsque l’utilisateur clique sur le lien de déconnexion. Le servlet invalide la session de l’utilisateur et redirige l’utilisateur vers la page de connexion, gérée par `LoginServlet`. + - `AuthenticationControllerProvider.java` : Responsable de la création et de la gestion d’une seule instance de `AuthenticationController` +
    + +
    + Pour permettre aux utilisateurs de s’authentifier, créez une instance de l’`AuthenticationController` fournie par la trousse SDK `auth0-java-mvc-commons` en utilisant le `domain`, `clientId`, et `clientSecret`. L’exemple présente comment configurer le composant pour l’utiliser avec des jetons signés à l’aide de l’algorithme de signature asymétrique RS256, en précisant un `JwkProvider` pour récupérer la clé publique utilisée pour vérifier la signature du jeton. Consultez le [référentiel jwks-rsa-java](https://github.com/auth0/jwks-rsa-java) pour en savoir plus sur les options de configuration supplémentaires. Si vous utilisez HS256, il n’est pas nécessaire de configurer `JwkProvider`. + + + `AuthenticationController` ne stocke aucun contexte et est destiné à être réutilisé. Une création inutile peut entraîner la génération de ressources supplémentaires, ce qui peut avoir une incidence sur les performances. + +
    + +
    + Pour permettre aux utilisateurs de se connecter, votre application les redirigera vers la page de Connexion universelle. En utilisant l’instance `AuthenticationController` , vous pouvez générer l’URL de redirection en appelant la méthode `buildAuthorizeUrl(HttpServletRequest request`, `HttpServletResponse response`, `String redirectUrl)`. L’URL de redirection doit être celle qui a été ajoutée aux **URL de rappel autorisées** de votre application Auth0. +
    + +
    + Après que l’utilisateur s’est connecté, le résultat sera reçu dans notre `CallbackServlet` via une requête HTTP GET ou POST. Comme nous utilisons le flux de code d’autorisation (par défaut), une requête GET sera envoyée. Si vous avez configuré la bibliothèque pour le flux implicite, une requête POST sera plutôt envoyée. + + La requête contient le contexte d’appel que la bibliothèque a précédemment défini en générant l’URL d’autorisation avec `AuthenticationController`. Lorsqu’il est passé au contrôleur, vous recevez soit une instance `Tokens` valide soit une Exception indiquant ce qui a mal tourné. En cas d’appel réussi, vous devez enregistrer les identifiants afin de pouvoir y accéder ultérieurement. Vous pouvez utiliser `HttpSession` de la requête en utilisant la classe `SessionsUtils` comprise dans la bibliothèque. + + + Il est recommandé d’enregistrer le moment où nous avons demandé les jetons ainsi que la valeur `expiresIn` reçue, afin que la prochaine fois que nous utiliserons le jeton, nous puissions vérifier s’il a déjà expiré ou s’il est encore valide. Pour les besoins de cet exemple, nous ignorerons cette validation. + +
    + +
    + Maintenant que l’utilisateur est authentifié (les jetons existent), `Auth0Filter` leur permettra d’accéder à nos ressources protégées. Dans le `HomeServlet` nous obtenons les jetons de la session de la requête et les définissons comme l’attribut `userId` afin qu’ils puissent être utilisés dans le code JSP. +
    + +
    + Pour gérer adéquatement la déconnexion, nous devons effacer la session et déconnecter l’utilisateur d’Auth0. Cette opération est gérée dans `LogoutServlet` de notre exemple d’application. + + Tout d’abord, nous effaçons la session en appelant `request.getSession().invalidate()`. Nous générons ensuite l’URL de déconnexion, en veillant à inclure le paramètre de requête `returnTo` qui est l’endroit où l’utilisateur sera redirigé après la déconnexion. Enfin, nous redirigeons la réponse vers notre URL de déconnexion. +
    + +
    + Pour exécuter l’exemple à partir d’un terminal, placez-vous dans le dossier racine du projet et exécutez la ligne suivante : + + `./gradlew clean app` + + Après quelques secondes, l’application sera accessible sur `http://localhost:3000/`. Essayez d’accéder à la ressource protégée http://localhost:3000/portal/home et notez comment vous êtes redirigé par `Auth0Filter` vers la page de connexion Auth0. Le gadget logiciel affiche toutes les connexions via réseaux sociaux et de bases de données que vous avez définies pour cette application dans le [tableau de bord](https://manage.auth0.com/#/). + + ![null](/docs/images/fr-ca/cdy7uua7fh8z/7L6lZ6xCi1L7sJBFZUPb9g/215ad0b724c138290b0b217edb5ddf96/Login_Screen_-_French.png) + + Vous serez en mesure de voir le contenu de la page d’accueil après une authentification réussie. + + ![null](/docs/images/fr-ca/cdy7uua7fh8z/FzK3jxfSGoeIDYQamxnJl/6b608e39ff39e044644193cfd2ee0f69/java-step-9-2.png) + + Déconnectez-vous en cliquant sur le bouton **logout (déconnexion)** en haut à droite de la page d’accueil. +
    + + ## Étapes suivantes + + Beau travail! Si vous en êtes arrivé là, vous devriez avoir la connexion, la déconnexion et les informations de profil utilisateur actives dans votre application. + + Cela conclut notre tutoriel de démarrage rapide, mais il y a tellement plus à explorer. Pour en savoir plus sur ce que vous pouvez faire avec Auth0, consultez : + + * [Auth0 Dashboard](https://manage.auth0.com/#) : apprenez à configurer et gérer votre locataire et vos applications Auth0 + * [Trousse SDK auth0-java-mvc-common](https://github.com/auth0/auth0-java-mvc-common) : explorez en détail la trousse SDK utilisée dans ce tutoriel + * [Auth0 Marketplace](https://marketplace.auth0.com/) : découvrez des intégrations que vous pouvez activer pour étendre les fonctionnalités d’Auth0 +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    diff --git a/main/docs/fr-ca/quickstart/webapp/nextjs/interactive.mdx b/main/docs/fr-ca/quickstart/webapp/nextjs/interactive.mdx index 241d0282b..98402b03b 100644 --- a/main/docs/fr-ca/quickstart/webapp/nextjs/interactive.mdx +++ b/main/docs/fr-ca/quickstart/webapp/nextjs/interactive.mdx @@ -1,199 +1,202 @@ ---- -title: "Ajouter une connexion à votre application Next.js" -permalink: "interactive" -'description': "Ce guide explique comment intégrer Auth0 à n’importe quelle application Next.js, nouvelle ou existante, à l’aide de la trousse SDK Next.js Auth0." -'og:title': "Ajouter une connexion à votre application Next.js" -'og:description': "Ce guide explique comment intégrer Auth0 à n’importe quelle application Next.js, nouvelle ou existante, à l’aide de la trousse SDK Next.js Auth0." -'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/nginx-plus.png" -'twitter:title': "Ajouter une connexion à votre application Next.js" -'twitter:description': "Ce guide explique comment intégrer Auth0 à n’importe quelle application Next.js, nouvelle ou existante, à l’aide de la trousse SDK Next.js Auth0." -sidebarTitle: Next.js ---- - -import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx" -import ConfigureSDK from "/snippets/quickstart/webapp/nextjs/configure-the-sdk.mdx" -import CreateAuth0SDKClient from "/snippets/quickstart/webapp/nextjs/create-the-auth0-sdk-client.mdx" -import CreateLoginPage from "/snippets/quickstart/webapp/nextjs/create-a-login-page.mdx" -import AddLandingPageContent from "/snippets/quickstart/webapp/nextjs/add-the-landing-page-content.mdx" - -export const sections = [ - { id: "configuration-d-auth0", title: "Configuration d’Auth0" }, - { id: "installer-la-trousse-sdk-next-js-auth0", title: "Installer la trousse SDK Next.js Auth0" }, - { id: "configuration-de-la-trousse-sdk", title: "Configuration de la trousse SDK" }, - { id: "ajouter-le-gestionnaire-de-route-dynamique", title: "Ajouter le gestionnaire de route dynamique" }, - { id: "ajouter-le-composant-userprovider", title: "Ajouter le composant UserProvider" }, - { id: "ajouter-une-connexion-à-votre-application", title: "Ajouter une connexion à votre application" }, - { id: "ajouter-une-fonctionnalité-de-déconnexion-à-votre-application", title: "Ajouter une fonctionnalité de déconnexion à votre application" } -] - - - - Ce guide explique comment intégrer Auth0 à n’importe quelle application Next.js, nouvelle ou existante, à l’aide de la trousse SDK Next.js Auth0. Nous vous recommandons de vous connecter pour suivre ce guide de démarrage rapide avec les exemples configurés pour votre compte. - -
    - Pour utiliser les services Auth0, vous devez avoir une application installée dans Auth0 Dashboard. L’application Auth0 est l’endroit où vous allez configurer le fonctionnement de l’authentification pour le projet que vous développez. - - ### Configurer une application - - Utilisez le sélecteur interactif pour créer une nouvelle application Auth0 ou sélectionner une application existante qui représente le projet avec lequel vous souhaitez effectuer l’intégration. Dans Auth0, chaque application se voit attribuer un identifiant client unique alphanumérique que votre code d’application utilisera pour appeler les API Auth0 via la trousse SDK. - - Tous les paramètres que vous configurez à l’aide de ce guide rapide seront automatiquement mis à jour pour votre application dans le [Tableau de bord](https://manage.auth0.com/#/), qui est l’endroit où vous pourrez gérer vos applications à l’avenir. - - Si vous préférez explorer une configuration complète, consultez plutôt un exemple d’application. - - ### Configuration des URL de rappel - - Une URL de rappel est une URL intégrée dans votre application vers laquelle vous souhaitez qu’Auth0 redirige les utilisateurs après leur authentification. Si elle n’est pas définie, les utilisateurs ne seront pas redirigés vers votre application après s’être connectés. - - - Si vous suivez notre projet à titre d’exemple, définissez ceci sur `http://localhost:3000/api/auth/callback`. - - - ### Configuration des URL de déconnexion - - Une URL de déconnexion est une URL intégrée dans votre application vers laquelle vous souhaitez qu’Auth0 redirige les utilisateurs après leur déconnexion. Si elle n’est pas définie, les utilisateurs ne pourront pas se déconnecter de votre application et recevront un message d’erreur. - - - Si vous suivez notre projet à titre d’exemple, définissez ceci sur `http://localhost:3000`. - -
    - -
    - Exécutez la commande suivante dans le répertoire de votre projet pour installer la trousse SDK Next.js Auth0 : - - `npm install @auth0/nextjs-auth0` - - La trousse SDK expose des méthodes et des variables qui vous aident à intégrer Auth0 à votre application Next.js en utilisant les [gestionnaires de route](https://nextjs.org/docs/app/building-your-application/routing/route-handlers) sur le système dorsal et le [contexte React](https://reactjs.org/docs/context.html) avec les [Crochets React](https://reactjs.org/docs/hooks-overview.html) sur le système frontal. -
    - -
    - Dans le répertoire racine de votre projet, ajoutez le fichier `.env.local` avec les [variables d’environnement](https://nextjs.org/docs/basic-features/environment-variables) suivantes : - - - `AUTH0_SECRET` : valeur secrète longue utilisée pour chiffrer le témoin de session. Vous pouvez générer une chaîne appropriée en utilisant `openssl rand -hex 32` sur la ligne de commande. - - `AUTH0_BASE_URL` : URL de base de votre application. - - `AUTH0_ISSUER_BASE_URL` : URL de votre domaine de locataire Auth0. Si vous utilisez un [domaine personnalisé avec Auth0](https://auth0.com/docs/custom-domains), utilisez la valeur de votre domaine personnalisé au lieu de la valeur indiquée dans l’onglet Settings (Paramètres). - - `AUTH0_CLIENT_ID` : identifiant client de votre application Auth0. - - `AUTH0_CLIENT_SECRET` : secret client de votre application Auth0. - - La trousse SDK lira ces valeurs à partir de l’environnement du processus Node.js et se configurera automatiquement. -
    - -
    - - Ce guide rapide s’adresse au [routeur d’application](https://nextjs.org/docs/app) Next.js. Si vous utilisez le [routeur Pages](https://nextjs.org/docs/pages), consultez l’exemple dans le [README](https://github.com/auth0/nextjs-auth0#page-router) de la trousse SDK. - - - Créez un fichier dans `app/api/auth/[auth0]/route.js`. Il s’agit de votre fichier Route Handler (Gestionnaire de route) avec un [Dynamic Route Segment (Segment de route dynamique)](https://nextjs.org/docs/app/building-your-application/routing/route-handlers#dynamic-route-segments). - - Ensuite, importez la méthode `handleAuth` de la trousse SDK et appelez-la à partir de l’exportation `GET`. Cette opération crée les routes suivantes : - - - `/api/auth/login` : la route utilisée pour se connecter avec Auth0. - - `/api/auth/logout` : la route utilisée pour déconnecter l’utilisateur. - - `/api/auth/callback` : la route vers laquelle Auth0 redirigera l’utilisateur après une connexion réussie. - - `/api/auth/me` : la route à partir de laquelle le profil utilisateur doit être récupéré. -
    - -
    - Côté frontal, la trousse SDK utilise React Context pour gérer l’état d’authentification de vos utilisateurs. Pour que cet état soit accessible à toutes vos pages, vous devez remplacer le [Root Layout component (composant Disposition racine)](https://nextjs.org/docs/app/building-your-application/routing/pages-and-layouts#root-layout-required) et envelopper la balise `` avec un `UserProvider` dans le fichier `app/layout.jsx`. - - L’état d’authentification exposé par `UserProvider` est accessible dans n’importe quel composant client à l’aide de l’appel `useUser()`. - - - ##### Point de contrôle - Maintenant que vous avez ajouté le gestionnaire de route et `UserProvider`, exécutez votre application pour vérifier qu’elle ne génère pas d’erreurs liées à Auth0. - -
    - -
    - Les utilisateurs peuvent désormais se connecter à votre application en visitant Gestionnaire de route `/api/auth/login` fourni par la trousse SDK. Ajoutez un lien qui pointe vers la route de connexion à l’aide d’une **balise d’ancrage**. En cliquant sur ce lien, vos utilisateurs seront redirigés vers la page de connexion universelle Auth0, où Auth0 pourra les authentifier. Une fois l’authentification réussie, Auth0 redirigera vos utilisateurs vers votre application. - - - Les prochaines règles de liaison pourraient suggérer d’utiliser le composant `Link` au lieu d’une balise d’ancrage. Le composant `Link` est destiné à effectuer des [transitions côté client entre les pages](https://nextjs.org/docs/api-reference/next/link). Comme le lien pointe vers une route API et non vers une page, vous devez le conserver en tant que balise d’ancrage. - - - - ##### Point de contrôle - Ajoutez le lien de connexion à votre application. - - Lorsque vous cliquez dessus, vérifiez que votre application Next.js vous redirige vers la page [Connexion universelle Auth0](https://auth0.com/universal-login) et que vous pouvez maintenant vous connecter ou vous inscrire en utilisant un nom d’utilisateur et un mot de passe ou un fournisseur social. - - Une fois l’opération terminée, vérifiez qu’Auth0 vous redirige vers votre application. - - - ![null](/docs/images/fr-ca/cdy7uua7fh8z/7L6lZ6xCi1L7sJBFZUPb9g/215ad0b724c138290b0b217edb5ddf96/Login_Screen_-_French.png) - - - Auth0 active le fournisseur social Google par défaut sur les nouveaux locataires et vous offre des clés de développeur pour tester la connexion avec des [fournisseurs d’identité sociale](https://auth0.com/docs/connections/identity-providers-social). Toutefois, ces clés de développeur présentent certaines limitations qui peuvent entraîner un comportement différent de votre application. Pour plus de détails sur ce comportement et comment le résoudre, consultez le document [Tester les connexions sociales avec des clés de développeur Auth0](https://auth0.com/docs/connections/social/devkeys#limitations-of-developer-keys). - -
    - -
    - Maintenant que vous pouvez vous connecter à votre application Next.js, vous avez besoin [d’un moyen de vous déconnecter](https://auth0.com/docs/logout/log-users-out-of-auth0). Ajoutez un lien qui pointe vers la route API `/api/auth/logout`. En cliquant dessus, vous redirigez vos utilisateurs vers votre [point de terminaison de déconnexion Auth0](https://auth0.com/docs/api/authentication?javascript#logout) (`https://YOUR_DOMAIN/v2/logout`), puis vous les redirigez immédiatement vers votre application. - - - ##### Point de contrôle - Lancez votre application. - - Vérifiez que votre application Next.js vous redirige vers la page de [connexion universelle Auth0](https://auth0.com/universal-login) et que vous pouvez désormais vous connecter ou vous inscrire à l’aide d’un nom d’utilisateur et d’un mot de passe ou d’un fournisseur de réseau social. - - Une fois cette opération terminée, vérifiez qu’Auth0 effectue une redirection vers votre application. - -
    - - ## Étapes suivantes - - Beau travail! Si vous en êtes arrivé là, vous devriez avoir la connexion, la déconnexion et les informations de profil utilisateur actives dans votre application. - - Cela conclut notre tutoriel de démarrage rapide, mais il y a tellement plus à explorer. Pour en savoir plus sur ce que vous pouvez faire avec Auth0, consultez : - - * [Auth0 Dashboard](https://manage.auth0.com/#) : apprenez à configurer et gérer votre locataire et vos applications Auth0 - * [Trousse SDK nextjs-auth0](https://github.com/auth0/nextjs-auth0/) : explorez en détail la trousse SDK utilisée dans ce tutoriel - * [Auth0 Marketplace](https://marketplace.auth0.com/) : découvrez des intégrations que vous pouvez activer pour étendre les fonctionnalités d’Auth0 -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    +--- +title: "Ajouter une connexion à votre application Next.js" +permalink: "interactive" +'description': "Ce guide explique comment intégrer Auth0 à n’importe quelle application Next.js, nouvelle ou existante, à l’aide de la trousse SDK Next.js Auth0." +'og:title': "Ajouter une connexion à votre application Next.js" +'og:description': "Ce guide explique comment intégrer Auth0 à n’importe quelle application Next.js, nouvelle ou existante, à l’aide de la trousse SDK Next.js Auth0." +'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/nginx-plus.png" +'twitter:title': "Ajouter une connexion à votre application Next.js" +'twitter:description': "Ce guide explique comment intégrer Auth0 à n’importe quelle application Next.js, nouvelle ou existante, à l’aide de la trousse SDK Next.js Auth0." +sidebarTitle: Next.js +--- + + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + +import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx" +import ConfigureSDK from "/snippets/quickstart/webapp/nextjs/configure-the-sdk.mdx" +import CreateAuth0SDKClient from "/snippets/quickstart/webapp/nextjs/create-the-auth0-sdk-client.mdx" +import CreateLoginPage from "/snippets/quickstart/webapp/nextjs/create-a-login-page.mdx" +import AddLandingPageContent from "/snippets/quickstart/webapp/nextjs/add-the-landing-page-content.mdx" + +export const sections = [ + { id: "configuration-d-auth0", title: "Configuration d’Auth0" }, + { id: "installer-la-trousse-sdk-next-js-auth0", title: "Installer la trousse SDK Next.js Auth0" }, + { id: "configuration-de-la-trousse-sdk", title: "Configuration de la trousse SDK" }, + { id: "ajouter-le-gestionnaire-de-route-dynamique", title: "Ajouter le gestionnaire de route dynamique" }, + { id: "ajouter-le-composant-userprovider", title: "Ajouter le composant UserProvider" }, + { id: "ajouter-une-connexion-à-votre-application", title: "Ajouter une connexion à votre application" }, + { id: "ajouter-une-fonctionnalité-de-déconnexion-à-votre-application", title: "Ajouter une fonctionnalité de déconnexion à votre application" } +] + + + + Ce guide explique comment intégrer Auth0 à n’importe quelle application Next.js, nouvelle ou existante, à l’aide de la trousse SDK Next.js Auth0. Nous vous recommandons de vous connecter pour suivre ce guide de démarrage rapide avec les exemples configurés pour votre compte. + +
    + Pour utiliser les services Auth0, vous devez avoir une application installée dans Auth0 Dashboard. L’application Auth0 est l’endroit où vous allez configurer le fonctionnement de l’authentification pour le projet que vous développez. + + ### Configurer une application + + Utilisez le sélecteur interactif pour créer une nouvelle application Auth0 ou sélectionner une application existante qui représente le projet avec lequel vous souhaitez effectuer l’intégration. Dans Auth0, chaque application se voit attribuer un identifiant client unique alphanumérique que votre code d’application utilisera pour appeler les API Auth0 via la trousse SDK. + + Tous les paramètres que vous configurez à l’aide de ce guide rapide seront automatiquement mis à jour pour votre application dans le [Tableau de bord](https://manage.auth0.com/#/), qui est l’endroit où vous pourrez gérer vos applications à l’avenir. + + Si vous préférez explorer une configuration complète, consultez plutôt un exemple d’application. + + ### Configuration des URL de rappel + + Une URL de rappel est une URL intégrée dans votre application vers laquelle vous souhaitez qu’Auth0 redirige les utilisateurs après leur authentification. Si elle n’est pas définie, les utilisateurs ne seront pas redirigés vers votre application après s’être connectés. + + + Si vous suivez notre projet à titre d’exemple, définissez ceci sur `http://localhost:3000/api/auth/callback`. + + + ### Configuration des URL de déconnexion + + Une URL de déconnexion est une URL intégrée dans votre application vers laquelle vous souhaitez qu’Auth0 redirige les utilisateurs après leur déconnexion. Si elle n’est pas définie, les utilisateurs ne pourront pas se déconnecter de votre application et recevront un message d’erreur. + + + Si vous suivez notre projet à titre d’exemple, définissez ceci sur `http://localhost:3000`. + +
    + +
    + Exécutez la commande suivante dans le répertoire de votre projet pour installer la trousse SDK Next.js Auth0 : + + `npm install @auth0/nextjs-auth0` + + La trousse SDK expose des méthodes et des variables qui vous aident à intégrer Auth0 à votre application Next.js en utilisant les [gestionnaires de route](https://nextjs.org/docs/app/building-your-application/routing/route-handlers) sur le système dorsal et le [contexte React](https://reactjs.org/docs/context.html) avec les [Crochets React](https://reactjs.org/docs/hooks-overview.html) sur le système frontal. +
    + +
    + Dans le répertoire racine de votre projet, ajoutez le fichier `.env.local` avec les [variables d’environnement](https://nextjs.org/docs/basic-features/environment-variables) suivantes : + + - `AUTH0_SECRET` : valeur secrète longue utilisée pour chiffrer le témoin de session. Vous pouvez générer une chaîne appropriée en utilisant `openssl rand -hex 32` sur la ligne de commande. + - `AUTH0_BASE_URL` : URL de base de votre application. + - `AUTH0_ISSUER_BASE_URL` : URL de votre domaine de locataire Auth0. Si vous utilisez un [domaine personnalisé avec Auth0](https://auth0.com/docs/custom-domains), utilisez la valeur de votre domaine personnalisé au lieu de la valeur indiquée dans l’onglet Settings (Paramètres). + - `AUTH0_CLIENT_ID` : identifiant client de votre application Auth0. + - `AUTH0_CLIENT_SECRET` : secret client de votre application Auth0. + + La trousse SDK lira ces valeurs à partir de l’environnement du processus Node.js et se configurera automatiquement. +
    + +
    + + Ce guide rapide s’adresse au [routeur d’application](https://nextjs.org/docs/app) Next.js. Si vous utilisez le [routeur Pages](https://nextjs.org/docs/pages), consultez l’exemple dans le [README](https://github.com/auth0/nextjs-auth0#page-router) de la trousse SDK. + + + Créez un fichier dans `app/api/auth/[auth0]/route.js`. Il s’agit de votre fichier Route Handler (Gestionnaire de route) avec un [Dynamic Route Segment (Segment de route dynamique)](https://nextjs.org/docs/app/building-your-application/routing/route-handlers#dynamic-route-segments). + + Ensuite, importez la méthode `handleAuth` de la trousse SDK et appelez-la à partir de l’exportation `GET`. Cette opération crée les routes suivantes : + + - `/api/auth/login` : la route utilisée pour se connecter avec Auth0. + - `/api/auth/logout` : la route utilisée pour déconnecter l’utilisateur. + - `/api/auth/callback` : la route vers laquelle Auth0 redirigera l’utilisateur après une connexion réussie. + - `/api/auth/me` : la route à partir de laquelle le profil utilisateur doit être récupéré. +
    + +
    + Côté frontal, la trousse SDK utilise React Context pour gérer l’état d’authentification de vos utilisateurs. Pour que cet état soit accessible à toutes vos pages, vous devez remplacer le [Root Layout component (composant Disposition racine)](https://nextjs.org/docs/app/building-your-application/routing/pages-and-layouts#root-layout-required) et envelopper la balise `` avec un `UserProvider` dans le fichier `app/layout.jsx`. + + L’état d’authentification exposé par `UserProvider` est accessible dans n’importe quel composant client à l’aide de l’appel `useUser()`. + + + ##### Point de contrôle + Maintenant que vous avez ajouté le gestionnaire de route et `UserProvider`, exécutez votre application pour vérifier qu’elle ne génère pas d’erreurs liées à Auth0. + +
    + +
    + Les utilisateurs peuvent désormais se connecter à votre application en visitant Gestionnaire de route `/api/auth/login` fourni par la trousse SDK. Ajoutez un lien qui pointe vers la route de connexion à l’aide d’une **balise d’ancrage**. En cliquant sur ce lien, vos utilisateurs seront redirigés vers la page de connexion universelle Auth0, où Auth0 pourra les authentifier. Une fois l’authentification réussie, Auth0 redirigera vos utilisateurs vers votre application. + + + Les prochaines règles de liaison pourraient suggérer d’utiliser le composant `Link` au lieu d’une balise d’ancrage. Le composant `Link` est destiné à effectuer des [transitions côté client entre les pages](https://nextjs.org/docs/api-reference/next/link). Comme le lien pointe vers une route API et non vers une page, vous devez le conserver en tant que balise d’ancrage. + + + + ##### Point de contrôle + Ajoutez le lien de connexion à votre application. + - Lorsque vous cliquez dessus, vérifiez que votre application Next.js vous redirige vers la page [Connexion universelle Auth0](https://auth0.com/universal-login) et que vous pouvez maintenant vous connecter ou vous inscrire en utilisant un nom d’utilisateur et un mot de passe ou un fournisseur social. + - Une fois l’opération terminée, vérifiez qu’Auth0 vous redirige vers votre application. + + + ![null](/docs/images/fr-ca/cdy7uua7fh8z/7L6lZ6xCi1L7sJBFZUPb9g/215ad0b724c138290b0b217edb5ddf96/Login_Screen_-_French.png) + + + Auth0 active le fournisseur social Google par défaut sur les nouveaux locataires et vous offre des clés de développeur pour tester la connexion avec des [fournisseurs d’identité sociale](https://auth0.com/docs/connections/identity-providers-social). Toutefois, ces clés de développeur présentent certaines limitations qui peuvent entraîner un comportement différent de votre application. Pour plus de détails sur ce comportement et comment le résoudre, consultez le document [Tester les connexions sociales avec des clés de développeur Auth0](https://auth0.com/docs/connections/social/devkeys#limitations-of-developer-keys). + +
    + +
    + Maintenant que vous pouvez vous connecter à votre application Next.js, vous avez besoin [d’un moyen de vous déconnecter](https://auth0.com/docs/logout/log-users-out-of-auth0). Ajoutez un lien qui pointe vers la route API `/api/auth/logout`. En cliquant dessus, vous redirigez vos utilisateurs vers votre [point de terminaison de déconnexion Auth0](https://auth0.com/docs/api/authentication?javascript#logout) (`https://YOUR_DOMAIN/v2/logout`), puis vous les redirigez immédiatement vers votre application. + + + ##### Point de contrôle + Lancez votre application. + - Vérifiez que votre application Next.js vous redirige vers la page de [connexion universelle Auth0](https://auth0.com/universal-login) et que vous pouvez désormais vous connecter ou vous inscrire à l’aide d’un nom d’utilisateur et d’un mot de passe ou d’un fournisseur de réseau social. + - Une fois cette opération terminée, vérifiez qu’Auth0 effectue une redirection vers votre application. + +
    + + ## Étapes suivantes + + Beau travail! Si vous en êtes arrivé là, vous devriez avoir la connexion, la déconnexion et les informations de profil utilisateur actives dans votre application. + + Cela conclut notre tutoriel de démarrage rapide, mais il y a tellement plus à explorer. Pour en savoir plus sur ce que vous pouvez faire avec Auth0, consultez : + + * [Auth0 Dashboard](https://manage.auth0.com/#) : apprenez à configurer et gérer votre locataire et vos applications Auth0 + * [Trousse SDK nextjs-auth0](https://github.com/auth0/nextjs-auth0/) : explorez en détail la trousse SDK utilisée dans ce tutoriel + * [Auth0 Marketplace](https://marketplace.auth0.com/) : découvrez des intégrations que vous pouvez activer pour étendre les fonctionnalités d’Auth0 +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    diff --git a/main/docs/fr-ca/quickstart/webapp/nginx-plus/interactive.mdx b/main/docs/fr-ca/quickstart/webapp/nginx-plus/interactive.mdx index a123163fb..423540bea 100644 --- a/main/docs/fr-ca/quickstart/webapp/nginx-plus/interactive.mdx +++ b/main/docs/fr-ca/quickstart/webapp/nginx-plus/interactive.mdx @@ -1,167 +1,169 @@ ---- -permalink: "interactive" -'description': "Ce tutoriel explique comment utiliser le module nginx-openid-connect pour ajouter une authentification et une autorisation à votre serveur NGINX." -'og:title': "NGINX Plus" -'og:description': "Ce tutoriel explique comment utiliser le module nginx-openid-connect pour ajouter une authentification et une autorisation à votre serveur NGINX." -'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/nginx-plus.png" -'twitter:title': "NGINX Plus" -'twitter:description': "Ce tutoriel explique comment utiliser le module nginx-openid-connect pour ajouter une authentification et une autorisation à votre serveur NGINX." -title: NGINX Plus ---- - -import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; -import { LoggedInForm } from "/snippets/Login.jsx"; -import Nginx from "/snippets/quickstart/webapp/nginx-plus/nginx.conf.mdx"; -import OpenidConnectionConfiguration from "/snippets/quickstart/webapp/nginx-plus/openid_connection_configuration.conf.mdx"; -import OpenidConnect from "/snippets/quickstart/webapp/nginx-plus/openid_connect.server_conf.mdx"; -import Frontend from "/snippets/quickstart/webapp/nginx-plus/frontend.conf.mdx"; - -export const sections = [ - { id: "configuration-requise", title: "Configuration requise" }, - { id: "installer-et-activer-le-module-nginx-plus-module-njs", title: "Installer et activer le module nginx-plus-module-njs" }, - { id: "vérifier-le-référentiel-de-modèles-nginx-openid-connect", title: "Vérifier le référentiel de modèles nginx-openid-connect" }, - { id: "configurez-nginx-avec-les-détails-de-votre-application-auth0", title: "Configurez NGINX avec les détails de votre application Auth0" }, - { id: "configuration-de-l-en-tête-accept-encoding-pour-les-points-de-terminaison-du-jeton-et-jwks", title: "Configuration de l’en-tête Accept-Encoding pour les points de terminaison du jeton et JWKS" }, - { id: "copier-les-fichiers-de-configuration-openid-connect", title: "Copier les fichiers de configuration OpenID Connect" }, - { id: "configuration-des-paramètres-de-l-application-auth0", title: "Configuration des paramètres de l’application Auth0" }, - { id: "transmettre-les-en-têtes-à-l-application-en-amont", title: "Transmettre les en-têtes à l’application en amont" } -] - - - - Ce tutoriel explique comment utiliser le module nginx-openid-connect pour ajouter une authentification et une autorisation à votre serveur NGINX. Nous vous recommandons de vous connecter pour suivre ce démarrage rapide avec les exemples configurés pour votre compte. - -
    - Ce tutoriel et le projet initial ont été testés avec la fonctionnalité suivante : - - - NGINX Plus R24 -
    - -
    - Vous devez d’abord installer le module `nginx-plus-module-njs` pour NGINX Plus. - - Suivez le guide d’installation des modules dynamiques pour installer les packages dans votre système d’exploitation hôte. - - Pour les distributions Linux qui utilisent le gestionnaire de packages `yum`, il est possible d’installer le module de la manière suivante : - - `sudo yum install nginx-plus-module-njs jq` - - Une fois le module installé, vous devez l’activer pour NGINX en ajoutant la ligne suivante au début de votre fichier `/etc/nginx/nginx.conf` : - - `load_module modules/ngx_http_js_module.so;` -
    - -
    - Clonez le référentiel `nginx-openid-connect`. Ce référentiel est accompagné d’un modèle de configuration. - - `git clone https://github.com/nginxinc/nginx-openid-connect` -
    - -
    - Exécutez le script configure.sh dans le dossier nginx-openid-connect pour renseigner le modèle de configuration pour votre application Auth0 : - - ``` - ./configure.sh --auth_jwt_key request \ - --client_id {yourClientId} \ - --pkce_enable \ - https://{yourDomain}/.well-known/openid-configuration - ``` - - Puis, ajoutez l’[URL de déconnexion de votre locataire](/docs/api/authentication#auth0-logout) à votre fichier `openid_connect_configuration.conf`. -
    - -
    - Ajoutez l’en-tête `Accept-Encoding` et définissez la valeur `gzip` dans votre fichier `openid_connect.server_conf`. -
    - -
    - Copiez vos quatre fichiers de configuration dans le dossier `conf.d`. - - ```bash - sudo cp openid_connect.js \ - frontend.conf \ - openid_connect_configuration.conf \ - openid_connect.server_conf /etc/nginx/conf.d - ``` -
    - -
    - Dans Auth0 Dashboard : - - 1. Accédez à **Applications** > **Applications**, puis sélectionnez votre application dans la liste. - 2. Passez à l’affichage **Paramètres**. - 3. Dans la section  **URI de l’application**, ajoutez https://{yourDomain}/\_codexch à **URL de rappel autorisées)**. - 4. Passez à l’affichage **Credentials (Identifiants)**. - - Dans la section **Application Authentication (Authentification de l’application)**, définissez **Authentication Method (Méthode d’authentification)** sur « None ». -
    - -
    - Ajoutez des en-têtes supplémentaires du jeton d’ID (JWT) à la cible en amont dans votre fichier `/etc/nginx/conf.d/frontend.conf`. -
    - - ## Étapes suivantes - - Beau travail! Si vous en êtes arrivé là, vous devriez avoir la connexion, la déconnexion et les informations de profil utilisateur actives dans votre application. - - Cela conclut notre tutoriel de démarrage rapide, mais il y a tellement plus à explorer. Pour en savoir plus sur ce que vous pouvez faire avec Auth0, consultez : - - * [Auth0 Dashboard](https://manage.auth0.com/#) : apprenez à configurer et gérer votre locataire et vos applications Auth0 - * [Auth0 Marketplace](https://marketplace.auth0.com/) : découvrez des intégrations que vous pouvez activer pour étendre les fonctionnalités d’Auth0 -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    +--- +permalink: "interactive" +'description': "Ce tutoriel explique comment utiliser le module nginx-openid-connect pour ajouter une authentification et une autorisation à votre serveur NGINX." +'og:title': "NGINX Plus" +'og:description': "Ce tutoriel explique comment utiliser le module nginx-openid-connect pour ajouter une authentification et une autorisation à votre serveur NGINX." +'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/nginx-plus.png" +'twitter:title': "NGINX Plus" +'twitter:description': "Ce tutoriel explique comment utiliser le module nginx-openid-connect pour ajouter une authentification et une autorisation à votre serveur NGINX." +title: NGINX Plus +--- + +import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; +import { LoggedInForm } from "/snippets/Login.jsx"; +import Nginx from "/snippets/quickstart/webapp/nginx-plus/nginx.conf.mdx"; +import OpenidConnectionConfiguration from "/snippets/quickstart/webapp/nginx-plus/openid_connection_configuration.conf.mdx"; +import OpenidConnect from "/snippets/quickstart/webapp/nginx-plus/openid_connect.server_conf.mdx"; +import Frontend from "/snippets/quickstart/webapp/nginx-plus/frontend.conf.mdx"; + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + +export const sections = [ + { id: "configuration-requise", title: "Configuration requise" }, + { id: "installer-et-activer-le-module-nginx-plus-module-njs", title: "Installer et activer le module nginx-plus-module-njs" }, + { id: "vérifier-le-référentiel-de-modèles-nginx-openid-connect", title: "Vérifier le référentiel de modèles nginx-openid-connect" }, + { id: "configurez-nginx-avec-les-détails-de-votre-application-auth0", title: "Configurez NGINX avec les détails de votre application Auth0" }, + { id: "configuration-de-l-en-tête-accept-encoding-pour-les-points-de-terminaison-du-jeton-et-jwks", title: "Configuration de l’en-tête Accept-Encoding pour les points de terminaison du jeton et JWKS" }, + { id: "copier-les-fichiers-de-configuration-openid-connect", title: "Copier les fichiers de configuration OpenID Connect" }, + { id: "configuration-des-paramètres-de-l-application-auth0", title: "Configuration des paramètres de l’application Auth0" }, + { id: "transmettre-les-en-têtes-à-l-application-en-amont", title: "Transmettre les en-têtes à l’application en amont" } +] + + + + Ce tutoriel explique comment utiliser le module nginx-openid-connect pour ajouter une authentification et une autorisation à votre serveur NGINX. Nous vous recommandons de vous connecter pour suivre ce démarrage rapide avec les exemples configurés pour votre compte. + +
    + Ce tutoriel et le projet initial ont été testés avec la fonctionnalité suivante : + + - NGINX Plus R24 +
    + +
    + Vous devez d’abord installer le module `nginx-plus-module-njs` pour NGINX Plus. + + Suivez le guide d’installation des modules dynamiques pour installer les packages dans votre système d’exploitation hôte. + + Pour les distributions Linux qui utilisent le gestionnaire de packages `yum`, il est possible d’installer le module de la manière suivante : + + `sudo yum install nginx-plus-module-njs jq` + + Une fois le module installé, vous devez l’activer pour NGINX en ajoutant la ligne suivante au début de votre fichier `/etc/nginx/nginx.conf` : + + `load_module modules/ngx_http_js_module.so;` +
    + +
    + Clonez le référentiel `nginx-openid-connect`. Ce référentiel est accompagné d’un modèle de configuration. + + `git clone https://github.com/nginxinc/nginx-openid-connect` +
    + +
    + Exécutez le script configure.sh dans le dossier nginx-openid-connect pour renseigner le modèle de configuration pour votre application Auth0 : + + ``` + ./configure.sh --auth_jwt_key request \ + --client_id {yourClientId} \ + --pkce_enable \ + https://{yourDomain}/.well-known/openid-configuration + ``` + + Puis, ajoutez l’[URL de déconnexion de votre locataire](/docs/api/authentication#auth0-logout) à votre fichier `openid_connect_configuration.conf`. +
    + +
    + Ajoutez l’en-tête `Accept-Encoding` et définissez la valeur `gzip` dans votre fichier `openid_connect.server_conf`. +
    + +
    + Copiez vos quatre fichiers de configuration dans le dossier `conf.d`. + + ```bash + sudo cp openid_connect.js \ + frontend.conf \ + openid_connect_configuration.conf \ + openid_connect.server_conf /etc/nginx/conf.d + ``` +
    + +
    + Dans Auth0 Dashboard : + + 1. Accédez à **Applications** > **Applications**, puis sélectionnez votre application dans la liste. + 2. Passez à l’affichage **Paramètres**. + 3. Dans la section  **URI de l’application**, ajoutez https://{yourDomain}/\_codexch à **URL de rappel autorisées)**. + 4. Passez à l’affichage **Credentials (Identifiants)**. + + Dans la section **Application Authentication (Authentification de l’application)**, définissez **Authentication Method (Méthode d’authentification)** sur « None ». +
    + +
    + Ajoutez des en-têtes supplémentaires du jeton d’ID (JWT) à la cible en amont dans votre fichier `/etc/nginx/conf.d/frontend.conf`. +
    + + ## Étapes suivantes + + Beau travail! Si vous en êtes arrivé là, vous devriez avoir la connexion, la déconnexion et les informations de profil utilisateur actives dans votre application. + + Cela conclut notre tutoriel de démarrage rapide, mais il y a tellement plus à explorer. Pour en savoir plus sur ce que vous pouvez faire avec Auth0, consultez : + + * [Auth0 Dashboard](https://manage.auth0.com/#) : apprenez à configurer et gérer votre locataire et vos applications Auth0 + * [Auth0 Marketplace](https://marketplace.auth0.com/) : découvrez des intégrations que vous pouvez activer pour étendre les fonctionnalités d’Auth0 +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    diff --git a/main/docs/fr-ca/quickstart/webapp/php/interactive.mdx b/main/docs/fr-ca/quickstart/webapp/php/interactive.mdx index 173fcecb2..fc2cd2ae5 100644 --- a/main/docs/fr-ca/quickstart/webapp/php/interactive.mdx +++ b/main/docs/fr-ca/quickstart/webapp/php/interactive.mdx @@ -1,237 +1,239 @@ ---- -title: "Ajouter une connexion à votre application PHP" -permalink: "interactive" -'description': "Ce guide explique comment intégrer Auth0, ajouter l’authentification et afficher les informations de profil utilisateur dans n’importe quelle application PHP à l’aide de la trousse SDK Auth0 PHP." -'og:title': "Ajouter une connexion à votre application PHP" -'og:description': "Ce guide explique comment intégrer Auth0, ajouter l’authentification et afficher les informations de profil utilisateur dans n’importe quelle application PHP à l’aide de la trousse SDK Auth0 PHP." -'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/php.png" -'twitter:title': "Ajouter une connexion à votre application PHP" -'twitter:description': "Ce guide explique comment intégrer Auth0, ajouter l’authentification et afficher les informations de profil utilisateur dans n’importe quelle application PHP à l’aide de la trousse SDK Auth0 PHP." -sidebarTitle: PHP ---- - -import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; -import { LoggedInForm } from "/snippets/Login.jsx"; -import Index from "/snippets/quickstart/webapp/php/index.php.mdx"; -import Login from "/snippets/quickstart/webapp/php/login.php.mdx"; -import Logout from "/snippets/quickstart/webapp/php/logout.php.mdx"; -import Profile from "/snippets/quickstart/webapp/php/profile.php.mdx"; -import Router from "/snippets/quickstart/webapp/php/router.php.mdx"; -import Callback from "/snippets/quickstart/webapp/php/callback.php.mdx"; - -export const sections = [ - { id: "configuration-d-auth0", title: "Configuration d’Auth0" }, - { id: "installer-la-trousse-sdk-auth0-php", title: "Installer la trousse SDK Auth0 PHP" }, - { id: "créer-des-routes", title: "Créer des routes" }, - { id: "ajouter-une-fonctionnalité-de-connexion-à-votre-application", title: "Ajouter une fonctionnalité de connexion à votre application" }, - { id: "ajouter-une-fonctionnalité-de-déconnexion-à-votre-application", title: "Ajouter une fonctionnalité de déconnexion à votre application" }, - { id: "afficher-les-informations-du-profil-utilisateur", title: "Afficher les informations du profil utilisateur" } -] - - - - Auth0 vous permet d’ajouter rapidement l’authentification à presque tous les types d’application. Ce guide explique comment intégrer Auth0, ajouter l’authentification et afficher les informations de profil utilisateur dans n’importe quelle application PHP à l’aide de la trousse SDK Auth0 PHP. - - Pour utiliser ce guide rapide, vous devez : - - - Vous inscrire à un compte Auth0 gratuit ou vous connecter à Auth0. - - Disposer d’un projet PHP fonctionnel avec lequel vous souhaitez vous intégrer. Vous pouvez également consulter ou télécharger une application faisant office d’exemple lorsque vous vous connectez. - -
    - Pour utiliser les services Auth0, vous devez avoir une application installée dans Auth0 Dashboard. L’application Auth0 est l’endroit où vous allez configurer le fonctionnement de l’authentification pour le projet que vous développez. - - ### Configurer une application - - Utilisez le sélecteur interactif pour créer une nouvelle application Auth0 ou sélectionner une application existante qui représente le projet avec lequel vous souhaitez effectuer l’intégration. Dans Auth0, il est attribué à chaque application un identifiant client unique alphanumérique que votre code d’application utilisera pour appeler les API Auth0 via la trousse SDK. - - Tous les paramètres que vous configurez à l’aide de ce guide rapide seront automatiquement mis à jour pour votre application dans le [Dashboard](https://manage.auth0.com/#/), qui est l’endroit où vous pourrez gérer vos applications à l’avenir. - - Si vous préférez explorer une configuration complète, consultez plutôt un exemple d’application. - - ### Configurer les URL de rappel - - Une URL de rappel est une URL intégrée dans votre application vers laquelle vous souhaitez qu’Auth0 redirige les utilisateurs après leur authentification. Si elle n’est pas définie, les utilisateurs ne seront pas redirigés vers votre application après s’être connectés. - - - Si vous suivez notre projet à titre d’exemple, définissez ceci sur `http://localhost:3000/callback`. - - - ### Configuration des URL de déconnexion - - Une URL de déconnexion est une URL intégrée dans votre application vers laquelle vous souhaitez qu’Auth0 redirige les utilisateurs après leur déconnexion. Si elle n’est pas définie, les utilisateurs ne pourront pas se déconnecter de votre application et recevront un message d’erreur. - - - Si vous suivez notre projet à titre d’exemple, définissez ceci sur `http://localhost:3000`. - - - ### Configurer les origines Web autorisées - - Une origine Web autorisée est une URL que vous souhaitez autoriser à accéder à votre flux d’authentification. Elle doit contenir l’URL de votre projet. Si elle n’est pas configurée adéquatement, votre projet ne pourra pas actualiser silencieusement les jetons d’authentification, ce qui entraînera la déconnexion de vos utilisateurs lorsque prochainement ils visiteront votre application ou lors de l’actualisation d’une page. - - - Si vous suivez notre projet à titre d’exemple, définissez ceci sur `http://localhost:3000`. - -
    - -
    - Auth0 fournit une [trousse SDK PHP](https://github.com/auth0/auth0-PHP) (Auth0-PHP) pour simplifier le processus de mise en œuvre de l’authentification et de l’autorisation Auth0 dans les applications PHP. - - La trousse SDK Auth0 PHP nécessite l’installation des bibliothèques HTTP compatibles [PSR-17](https://www.php-fig.org/psr/psr-17/) et [PSR-18](https://www.php-fig.org/psr/psr-18/) pour la gestion des requêtes réseau. Si vous ne disposez pas de bibliothèques, vous pouvez installer des choix fiables en exécutant les commandes suivantes dans votre terminal : - - ``` - cd - composer require symfony/http-client nyholm/psr7 - ``` - - Installez maintenant la trousse SDK PHP Auth0 en exécutant la commande suivante dans votre terminal : - - ``` - composer require auth0/auth0-php - ``` - - ### Configurer la trousse SDK Auth0 - - Créez un nouveau fichier dans votre application, appelé `index.php`, et copiez le code du panneau interactif à droite sous l’onglet **index.php**. - - Pour que la trousse SDK fonctionne correctement, vous devez définir les propriétés suivantes dans la trousse SDK Auth0 lors de l’initialisation : - - - `domain` : Le domaine de votre locataire Auth0. En général, vous le trouvez dans Auth0 Dashboard sous vos paramètres d’application dans le champ Domain (Domaine). Si vous utilisez un [domaine personnalisé](https://auth0.com/docs/custom-domains), définissez-le plutôt sur la valeur de votre domaine personnalisé. - - `clientId` : l’identificateur de l’application Auth0 que vous avez configurée précédemment dans ce guide rapide. Vous pouvez le trouver dans Auth0 Dashboard, dans les paramètres de votre application, dans le champ Client ID (ID client). - - `clientSecret` : le secret de l’application Auth0 que vous avez configurée précédemment dans ce guide rapide. Vous pouvez le trouver dans Auth0 Dashboard, dans la rubrique des paramètres de votre application, dans le champ Client Secret (Secret client). - - `redirectUri` : l’URL dans votre application vers laquelle vous souhaitez qu’Auth0 redirige les utilisateurs après leur authentification. Cela correspond à l’URL de rappel que vous avez configurée précédemment dans ce guide rapide. Cette valeur se trouve également dans Auth0 Dashboard, sous les paramètres de votre application, dans le champ URL de rappel. Assurez-vous que ce que vous saisissez dans votre code correspond à ce que vous avez configuré précédemment, au cas contraire, vos utilisateurs verront une erreur. - - `cookieSecret` : Valeur secrète longue utilisée pour chiffrer le témoin de session. Vous pouvez générer une chaîne appropriée en exécutant `openssl rand -hex 32` dans votre terminal. - - - ##### Point de contrôle - Votre trousse SDK Auth0 devrait maintenant être correctement configurée. Exécutez votre application pour vérifier que: - La trousse SDK s’initialise correctement. - Votre application ne génère aucune erreur liée à Auth0. - -
    - -
    - Installez maintenant une bibliothèque de routage, pour aider à diriger les requêtes entrantes vers votre application. Cette étape n’est pas obligatoire, mais elle simplifie la structure de l’application pour les besoins de ce guide rapide. - - ``` - composer require steampixel/simple-php-router - ``` - - Créez un nouveau fichier dans votre application, appelé `router.php`, pour définir nos routes, et copiez le code du panneau interactif à droite. -
    - -
    - À présent que vous avez configuré votre application Auth0 et la trousse SDK PHP Auth0, vous devez configurer la connexion pour votre projet. Pour ce faire, vous utiliserez la méthode `login()` de la trousse SDK pour créer un bouton de connexion qui redirige les utilisateurs vers la page de connexion universelle Auth0. Une fois un utilisateur authentifié avec succès, il est redirigé vers l’URL de rappel que vous avez configurée précédemment dans ce guide de démarrage rapide. - - Créez un nouveau fichier dans votre application, appelé `login.php`, pour gérer le processus de connexion, et copiez le code du panneau interactif à droite, qui contient la logique nécessaire à la connexion. - - - ##### Point de contrôle - Vous devez désormais pouvoir vous connecter ou vous inscrire en utilisant un nom d’utilisateur et un mot de passe. - - Cliquez sur le lien de connexion et vérifiez que: - - Votre application vous redirige vers la page de connexion universelle Auth0. - - Vous pouvez vous connecter ou vous inscrire. - - Auth0 vous redirige vers votre application en utilisant la valeur de `redirectUri` que vous avez utilisée pour configurer la trousse SDK. - -
    - -
    - Les utilisateurs qui se connectent à votre projet auront également besoin d’un moyen de se déconnecter. Nous allons gérer un bouton de déconnexion à l’aide de la méthode`logout()` de la trousse SDK. Lorsque les utilisateurs se déconnecteront, ils seront redirigés vers votre point de terminaison [Auth0 logout](https://auth0.com/docs/api/authentication?http#logout) qui par la suite les redirigera immédiatement vers l’URL de déconnexion que vous avez configurée précédemment dans ce guide de démarrage rapide. - - Créez un nouveau fichier dans votre application, appelé `logout.php`, pour gérer le processus, et copiez le code du panneau interactif, qui contient la logique nécessaire à la déconnexion. Ensuite, mettez à jour votre fichier `index.php` pour y intégrer le nouveau bouton de déconnexion. - - - ##### Point de contrôle - Exécutez votre application et cliquez sur le bouton de déconnexion, vérifiez que: - - Votre application vous redirige vers l’adresse que vous avez précisée comme l’une des URL de déconnexion autorisées dans les paramètres de votre application. - - Vous n’êtes plus connecté à votre application. - -
    - -
    - Vu que vos utilisateurs peuvent désormais se connecter et se déconnecter, vous voudrez probablement pouvoir récupérer les [informations de profil](https://auth0.com/docs/users/concepts/overview-user-profile) associées aux utilisateurs authentifiés. Par exemple, vous voudrez peut-être pouvoir afficher le nom ou la photo de profil d’un utilisateur connecté dans votre projet. - - La trousse SDK PHP Auth0 fournit des informations sur les utilisateurs via la méthode `getCredentials()`. Examinez le code `profile.php` dans le panneau interactif pour voir un exemple de la façon de l’utiliser. - - Étant donné que la méthode contient des informations sensibles liées à l’identité de l’utilisateur, sa disponibilité dépend du statut d’authentification de l’utilisateur. Pour éviter les erreurs de rendu, vous devez toujours vérifier si la méthode `getCredentials()` renvoie un `object` ou `null` pour déterminer si Auth0 a authentifié l’utilisateur avant que votre application ne consomme les résultats. - - - ##### Point de contrôle - Vérifiez que: - - vous pouvez afficher le `nickname` ou toute autre propriété de l’utilisateur adéquatement, après vous être connecté. - -
    - - ## Étapes suivantes - - Beau travail! Si vous en êtes arrivé là, vous devriez avoir la connexion, la déconnexion et les informations de profil utilisateur actives dans votre application. - - Cela conclut notre tutoriel de démarrage rapide, mais il y a tellement plus à explorer. Pour en savoir plus sur ce que vous pouvez faire avec Auth0, consultez : - - * [Auth0 Dashboard](https://manage.auth0.com/#) : apprenez à configurer et gérer votre locataire et vos applications Auth0 - * [Trousse SDK Auth0-PHP](https://github.com/auth0/auth0-php) : explorez en détail la trousse SDK utilisée dans ce tutoriel - * [Auth0 Marketplace](https://marketplace.auth0.com/) : découvrez des intégrations que vous pouvez activer pour étendre les fonctionnalités d’Auth0 -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    +--- +title: "Ajouter une connexion à votre application PHP" +permalink: "interactive" +'description': "Ce guide explique comment intégrer Auth0, ajouter l’authentification et afficher les informations de profil utilisateur dans n’importe quelle application PHP à l’aide de la trousse SDK Auth0 PHP." +'og:title': "Ajouter une connexion à votre application PHP" +'og:description': "Ce guide explique comment intégrer Auth0, ajouter l’authentification et afficher les informations de profil utilisateur dans n’importe quelle application PHP à l’aide de la trousse SDK Auth0 PHP." +'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/php.png" +'twitter:title': "Ajouter une connexion à votre application PHP" +'twitter:description': "Ce guide explique comment intégrer Auth0, ajouter l’authentification et afficher les informations de profil utilisateur dans n’importe quelle application PHP à l’aide de la trousse SDK Auth0 PHP." +sidebarTitle: PHP +--- + +import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; +import { LoggedInForm } from "/snippets/Login.jsx"; +import Index from "/snippets/quickstart/webapp/php/index.php.mdx"; +import Login from "/snippets/quickstart/webapp/php/login.php.mdx"; +import Logout from "/snippets/quickstart/webapp/php/logout.php.mdx"; +import Profile from "/snippets/quickstart/webapp/php/profile.php.mdx"; +import Router from "/snippets/quickstart/webapp/php/router.php.mdx"; +import Callback from "/snippets/quickstart/webapp/php/callback.php.mdx"; + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + +export const sections = [ + { id: "configuration-d-auth0", title: "Configuration d’Auth0" }, + { id: "installer-la-trousse-sdk-auth0-php", title: "Installer la trousse SDK Auth0 PHP" }, + { id: "créer-des-routes", title: "Créer des routes" }, + { id: "ajouter-une-fonctionnalité-de-connexion-à-votre-application", title: "Ajouter une fonctionnalité de connexion à votre application" }, + { id: "ajouter-une-fonctionnalité-de-déconnexion-à-votre-application", title: "Ajouter une fonctionnalité de déconnexion à votre application" }, + { id: "afficher-les-informations-du-profil-utilisateur", title: "Afficher les informations du profil utilisateur" } +] + + + + Auth0 vous permet d’ajouter rapidement l’authentification à presque tous les types d’application. Ce guide explique comment intégrer Auth0, ajouter l’authentification et afficher les informations de profil utilisateur dans n’importe quelle application PHP à l’aide de la trousse SDK Auth0 PHP. + + Pour utiliser ce guide rapide, vous devez : + + - Vous inscrire à un compte Auth0 gratuit ou vous connecter à Auth0. + - Disposer d’un projet PHP fonctionnel avec lequel vous souhaitez vous intégrer. Vous pouvez également consulter ou télécharger une application faisant office d’exemple lorsque vous vous connectez. + +
    + Pour utiliser les services Auth0, vous devez avoir une application installée dans Auth0 Dashboard. L’application Auth0 est l’endroit où vous allez configurer le fonctionnement de l’authentification pour le projet que vous développez. + + ### Configurer une application + + Utilisez le sélecteur interactif pour créer une nouvelle application Auth0 ou sélectionner une application existante qui représente le projet avec lequel vous souhaitez effectuer l’intégration. Dans Auth0, il est attribué à chaque application un identifiant client unique alphanumérique que votre code d’application utilisera pour appeler les API Auth0 via la trousse SDK. + + Tous les paramètres que vous configurez à l’aide de ce guide rapide seront automatiquement mis à jour pour votre application dans le [Dashboard](https://manage.auth0.com/#/), qui est l’endroit où vous pourrez gérer vos applications à l’avenir. + + Si vous préférez explorer une configuration complète, consultez plutôt un exemple d’application. + + ### Configurer les URL de rappel + + Une URL de rappel est une URL intégrée dans votre application vers laquelle vous souhaitez qu’Auth0 redirige les utilisateurs après leur authentification. Si elle n’est pas définie, les utilisateurs ne seront pas redirigés vers votre application après s’être connectés. + + + Si vous suivez notre projet à titre d’exemple, définissez ceci sur `http://localhost:3000/callback`. + + + ### Configuration des URL de déconnexion + + Une URL de déconnexion est une URL intégrée dans votre application vers laquelle vous souhaitez qu’Auth0 redirige les utilisateurs après leur déconnexion. Si elle n’est pas définie, les utilisateurs ne pourront pas se déconnecter de votre application et recevront un message d’erreur. + + + Si vous suivez notre projet à titre d’exemple, définissez ceci sur `http://localhost:3000`. + + + ### Configurer les origines Web autorisées + + Une origine Web autorisée est une URL que vous souhaitez autoriser à accéder à votre flux d’authentification. Elle doit contenir l’URL de votre projet. Si elle n’est pas configurée adéquatement, votre projet ne pourra pas actualiser silencieusement les jetons d’authentification, ce qui entraînera la déconnexion de vos utilisateurs lorsque prochainement ils visiteront votre application ou lors de l’actualisation d’une page. + + + Si vous suivez notre projet à titre d’exemple, définissez ceci sur `http://localhost:3000`. + +
    + +
    + Auth0 fournit une [trousse SDK PHP](https://github.com/auth0/auth0-PHP) (Auth0-PHP) pour simplifier le processus de mise en œuvre de l’authentification et de l’autorisation Auth0 dans les applications PHP. + + La trousse SDK Auth0 PHP nécessite l’installation des bibliothèques HTTP compatibles [PSR-17](https://www.php-fig.org/psr/psr-17/) et [PSR-18](https://www.php-fig.org/psr/psr-18/) pour la gestion des requêtes réseau. Si vous ne disposez pas de bibliothèques, vous pouvez installer des choix fiables en exécutant les commandes suivantes dans votre terminal : + + ``` + cd + composer require symfony/http-client nyholm/psr7 + ``` + + Installez maintenant la trousse SDK PHP Auth0 en exécutant la commande suivante dans votre terminal : + + ``` + composer require auth0/auth0-php + ``` + + ### Configurer la trousse SDK Auth0 + + Créez un nouveau fichier dans votre application, appelé `index.php`, et copiez le code du panneau interactif à droite sous l’onglet **index.php**. + + Pour que la trousse SDK fonctionne correctement, vous devez définir les propriétés suivantes dans la trousse SDK Auth0 lors de l’initialisation : + + - `domain` : Le domaine de votre locataire Auth0. En général, vous le trouvez dans Auth0 Dashboard sous vos paramètres d’application dans le champ Domain (Domaine). Si vous utilisez un [domaine personnalisé](https://auth0.com/docs/custom-domains), définissez-le plutôt sur la valeur de votre domaine personnalisé. + - `clientId` : l’identificateur de l’application Auth0 que vous avez configurée précédemment dans ce guide rapide. Vous pouvez le trouver dans Auth0 Dashboard, dans les paramètres de votre application, dans le champ Client ID (ID client). + - `clientSecret` : le secret de l’application Auth0 que vous avez configurée précédemment dans ce guide rapide. Vous pouvez le trouver dans Auth0 Dashboard, dans la rubrique des paramètres de votre application, dans le champ Client Secret (Secret client). + - `redirectUri` : l’URL dans votre application vers laquelle vous souhaitez qu’Auth0 redirige les utilisateurs après leur authentification. Cela correspond à l’URL de rappel que vous avez configurée précédemment dans ce guide rapide. Cette valeur se trouve également dans Auth0 Dashboard, sous les paramètres de votre application, dans le champ URL de rappel. Assurez-vous que ce que vous saisissez dans votre code correspond à ce que vous avez configuré précédemment, au cas contraire, vos utilisateurs verront une erreur. + - `cookieSecret` : Valeur secrète longue utilisée pour chiffrer le témoin de session. Vous pouvez générer une chaîne appropriée en exécutant `openssl rand -hex 32` dans votre terminal. + + + ##### Point de contrôle + Votre trousse SDK Auth0 devrait maintenant être correctement configurée. Exécutez votre application pour vérifier que: + La trousse SDK s’initialise correctement. + Votre application ne génère aucune erreur liée à Auth0. + +
    + +
    + Installez maintenant une bibliothèque de routage, pour aider à diriger les requêtes entrantes vers votre application. Cette étape n’est pas obligatoire, mais elle simplifie la structure de l’application pour les besoins de ce guide rapide. + + ``` + composer require steampixel/simple-php-router + ``` + + Créez un nouveau fichier dans votre application, appelé `router.php`, pour définir nos routes, et copiez le code du panneau interactif à droite. +
    + +
    + À présent que vous avez configuré votre application Auth0 et la trousse SDK PHP Auth0, vous devez configurer la connexion pour votre projet. Pour ce faire, vous utiliserez la méthode `login()` de la trousse SDK pour créer un bouton de connexion qui redirige les utilisateurs vers la page de connexion universelle Auth0. Une fois un utilisateur authentifié avec succès, il est redirigé vers l’URL de rappel que vous avez configurée précédemment dans ce guide de démarrage rapide. + + Créez un nouveau fichier dans votre application, appelé `login.php`, pour gérer le processus de connexion, et copiez le code du panneau interactif à droite, qui contient la logique nécessaire à la connexion. + + + ##### Point de contrôle + Vous devez désormais pouvoir vous connecter ou vous inscrire en utilisant un nom d’utilisateur et un mot de passe. + + Cliquez sur le lien de connexion et vérifiez que: + - Votre application vous redirige vers la page de connexion universelle Auth0. + - Vous pouvez vous connecter ou vous inscrire. + - Auth0 vous redirige vers votre application en utilisant la valeur de `redirectUri` que vous avez utilisée pour configurer la trousse SDK. + +
    + +
    + Les utilisateurs qui se connectent à votre projet auront également besoin d’un moyen de se déconnecter. Nous allons gérer un bouton de déconnexion à l’aide de la méthode`logout()` de la trousse SDK. Lorsque les utilisateurs se déconnecteront, ils seront redirigés vers votre point de terminaison [Auth0 logout](https://auth0.com/docs/api/authentication?http#logout) qui par la suite les redirigera immédiatement vers l’URL de déconnexion que vous avez configurée précédemment dans ce guide de démarrage rapide. + + Créez un nouveau fichier dans votre application, appelé `logout.php`, pour gérer le processus, et copiez le code du panneau interactif, qui contient la logique nécessaire à la déconnexion. Ensuite, mettez à jour votre fichier `index.php` pour y intégrer le nouveau bouton de déconnexion. + + + ##### Point de contrôle + Exécutez votre application et cliquez sur le bouton de déconnexion, vérifiez que: + - Votre application vous redirige vers l’adresse que vous avez précisée comme l’une des URL de déconnexion autorisées dans les paramètres de votre application. + - Vous n’êtes plus connecté à votre application. + +
    + +
    + Vu que vos utilisateurs peuvent désormais se connecter et se déconnecter, vous voudrez probablement pouvoir récupérer les [informations de profil](https://auth0.com/docs/users/concepts/overview-user-profile) associées aux utilisateurs authentifiés. Par exemple, vous voudrez peut-être pouvoir afficher le nom ou la photo de profil d’un utilisateur connecté dans votre projet. + + La trousse SDK PHP Auth0 fournit des informations sur les utilisateurs via la méthode `getCredentials()`. Examinez le code `profile.php` dans le panneau interactif pour voir un exemple de la façon de l’utiliser. + + Étant donné que la méthode contient des informations sensibles liées à l’identité de l’utilisateur, sa disponibilité dépend du statut d’authentification de l’utilisateur. Pour éviter les erreurs de rendu, vous devez toujours vérifier si la méthode `getCredentials()` renvoie un `object` ou `null` pour déterminer si Auth0 a authentifié l’utilisateur avant que votre application ne consomme les résultats. + + + ##### Point de contrôle + Vérifiez que: + - vous pouvez afficher le `nickname` ou toute autre propriété de l’utilisateur adéquatement, après vous être connecté. + +
    + + ## Étapes suivantes + + Beau travail! Si vous en êtes arrivé là, vous devriez avoir la connexion, la déconnexion et les informations de profil utilisateur actives dans votre application. + + Cela conclut notre tutoriel de démarrage rapide, mais il y a tellement plus à explorer. Pour en savoir plus sur ce que vous pouvez faire avec Auth0, consultez : + + * [Auth0 Dashboard](https://manage.auth0.com/#) : apprenez à configurer et gérer votre locataire et vos applications Auth0 + * [Trousse SDK Auth0-PHP](https://github.com/auth0/auth0-php) : explorez en détail la trousse SDK utilisée dans ce tutoriel + * [Auth0 Marketplace](https://marketplace.auth0.com/) : découvrez des intégrations que vous pouvez activer pour étendre les fonctionnalités d’Auth0 +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    diff --git a/main/docs/fr-ca/quickstart/webapp/python/interactive.mdx b/main/docs/fr-ca/quickstart/webapp/python/interactive.mdx index 385f22821..bcfe2f350 100644 --- a/main/docs/fr-ca/quickstart/webapp/python/interactive.mdx +++ b/main/docs/fr-ca/quickstart/webapp/python/interactive.mdx @@ -1,180 +1,182 @@ ---- -title: "Ajouter une fonctionnalité de connexion à votre application Python Flask" -permalink: "interactive" -'description': "Ce guide explique comment intégrer Auth0 à une application PythonºFlask, à l’aide de la trousse SDK Authlib." -'og:title': "Ajouter une fonctionnalité de connexion à votre application Python Flask" -'og:description': "Ce guide explique comment intégrer Auth0 à une application PythonºFlask, à l’aide de la trousse SDK Authlib." -'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/python.png" -'twitter:title': "Ajouter une fonctionnalité de connexion à votre application Python Flask" -'twitter:description': "Ce guide explique comment intégrer Auth0 à une application PythonºFlask, à l’aide de la trousse SDK Authlib." -sidebarTitle: Python ---- - -import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; -import { LoggedInForm } from "/snippets/Login.jsx"; -import Server from "/snippets/quickstart/webapp/python/server.py.mdx"; -import Home from "/snippets/quickstart/webapp/python/home.html.mdx"; - -export const sections = [ - { id: "configuration-d-auth0", title: "Configuration d’Auth0" }, - { id: "installer-les-dépendances", title: "Installer les dépendances" }, - { id: "configurez-votre-fichier-env", title: "Configurez votre fichier .env" }, - { id: "configurez-votre-application", title: "Configurez votre application" }, - { id: "configurez-vos-routes", title: "Configurez vos routes" }, - { id: "ajouter-des-modèles", title: "Ajouter des modèles" }, - { id: "exécuter-votre-application", title: "Exécuter votre application" } -] - - - - Auth0 vous permet d’ajouter l’authentification et de pouvoir accéder aux informations relatives au profil de l’utilisateur dans votre application. Ce guide explique comment intégrer Auth0 à une application Python [Flask](https://flask.palletsprojects.com/), à l’aide de la trousse SDK [Authlib](https://authlib.org/). - -
    - Pour utiliser les services Auth0, vous devez avoir une application installée dans Auth0 Dashboard. L’application Auth0 est l’endroit où vous allez configurer le fonctionnement de l’authentification pour le projet que vous développez. - - ### Configurer une application - - Utilisez le sélecteur interactif pour créer une nouvelle application Auth0 ou sélectionner une application existante qui représente le projet avec lequel vous souhaitez effectuer l’intégration. Dans Auth0, chaque application se voit attribuer un identifiant client unique alphanumérique que votre code d’application utilisera pour appeler les API Auth0 via la trousse SDK. - - Tous les paramètres que vous configurez à l’aide de ce guide de démarrage rapide seront automatiquement mis à jour pour votre application dans le [Tableau de bord](https://manage.auth0.com/#/), qui est l’endroit où vous pourrez gérer vos applications à l’avenir. - - Si vous préférez explorer une configuration complète, consultez plutôt un exemple d’application. - - ### Configurer les URL de rappel - - Une URL de rappel est une URL intégrée dans votre application vers laquelle vous souhaitez qu’Auth0 redirige les utilisateurs après leur authentification. Si elle n’est pas définie, les utilisateurs ne seront pas redirigés vers votre application après s’être connectés. - - - Si vous suivez notre projet à titre d’exemple, définissez ceci sur `http://localhost:3000/callback`. - - - ### Configuration des URL de déconnexion - - Une URL de déconnexion est une URL intégrée dans votre application vers laquelle vous souhaitez qu’Auth0 redirige les utilisateurs après leur déconnexion. Si elle n’est pas définie, les utilisateurs ne pourront pas se déconnecter de votre application et recevront un message d’erreur. - - - Si vous suivez notre projet à titre d’exemple, définissez ceci sur `http://localhost:3000`. - -
    - -
    - Créez un fichier `requirements.txt` dans le répertoire de votre projet : - - ``` - # 📁 requirements.txt ----- - flask>=2.0.3 - python-dotenv>=0.19.2 - authlib>=1.0 - requests>=2.27.1 - ``` - - Exécutez la commande suivante depuis votre shell pour activer les dépendances suivantes dans votre projet : - - ```bash - pip install -r requirements.txt - ``` -
    - -
    - Ensuite, créez un fichier `.env` dans votre répertoire de projet. Ce fichier contiendra les clés de vos clients et d’autres détails de configuration. - - ``` - # 📁 .env ----- - AUTH0_CLIENT_ID={yourClientId} - AUTH0_CLIENT_SECRET={yourClientSecret} - AUTH0_DOMAIN={yourDomain} - APP_SECRET_KEY= - ``` - - - Générez une chaîne pour `APP_SECRET_KEY` en utilisant `openssl rand -hex 32` depuis votre shell. -
    - -
    - Ensuite, configurez votre application. Créez un fichier `server.py` dans le répertoire de votre projet; ce fichier contiendra la logique de votre application. - - Importez toutes les bibliothèques nécessaires à votre application. - - Chargez le fichier de configuration `.env` que vous avez créé à l’étape précédente. - - Configurez Authlib pour gérer l’authentification de votre application avec Auth0. Apprenez-en davantage sur les options de configuration possibles pour la méthode `register()` d’Authlib OAuth dans [leur documentation.](https://docs.authlib.org/en/latest/client/frameworks.html#using-oauth-2-0-to-log-in) -
    - -
    - Dans cet exemple, vous ajouterez quatre routes à l’application : connexion, callback, déconnexion et accueil. - - Lorsque les visiteurs de votre application se rendent sur la route `/login`, votre application les dirige vers la page de connexion Auth0. - - Une fois vos utilisateurs connectés avec Auth0, votre application les dirige vers la route `/callback`. Cette route enregistre la session de l’utilisateur et permet de ne plus avoir à se reconnecter lorsqu’il revient. - - La route `/logout` permet aux utilisateurs de se déconnecter de votre application. Cette route efface la session de l’utilisateur dans votre application et redirige vers le point de terminaison de déconnexion d’Auth0 pour s’assurer que la session n’est plus enregistrée. Ensuite, l’application redirige l’utilisateur vers votre route d’accueil. - - Votre route `/home` affiche les détails d’un utilisateur authentifié ou permet aux visiteurs de s’identifier. -
    - -
    - Créez ensuite le fichier de modèle utilisé dans la route d’accueil (lors des appels `render_template()`). - - Créez un nouveau sous-répertoire dans le dossier de votre projet, nommé `templates`, et créez `home.html` dans ce répertoire. Collez le contenu à droite dans ce fichier. -
    - -
    - Pour exécuter votre application, naviguez jusqu’à la racine du répertoire de votre projet et ouvrez un terminal. Exécutez la commande suivante : - - ``` - python3 server.py - ``` - - - ##### Point de contrôle - Visitez [http://localhost:3000](http://localhost:3000/) pour des raisons de vérification. Un bouton de connexion devrait vous permettre de vous connecter à Auth0, puis de revenir à votre application pour consulter les informations relatives à votre profil. - -
    - -## Étapes suivantes - -Beau travail! Si vous en êtes arrivé là, vous devriez avoir la connexion, la déconnexion et les informations de profil utilisateur actives dans votre application. - -Cela conclut notre tutoriel de démarrage rapide, mais il y a tellement plus à explorer. Pour en savoir plus sur ce que vous pouvez faire avec Auth0, consultez : - -* [Auth0 Dashboard](https://manage.auth0.com/#) : apprenez à configurer et gérer votre locataire et vos applications Auth0 -* [Trousse SDK auth0-python](https://github.com/auth0/auth0-python) : explorez en détail la trousse SDK utilisée dans ce tutoriel -* [Auth0 Marketplace](https://marketplace.auth0.com/) : découvrez des intégrations que vous pouvez activer pour étendre les fonctionnalités d’Auth0 -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    +--- +title: "Ajouter une fonctionnalité de connexion à votre application Python Flask" +permalink: "interactive" +'description': "Ce guide explique comment intégrer Auth0 à une application PythonºFlask, à l’aide de la trousse SDK Authlib." +'og:title': "Ajouter une fonctionnalité de connexion à votre application Python Flask" +'og:description': "Ce guide explique comment intégrer Auth0 à une application PythonºFlask, à l’aide de la trousse SDK Authlib." +'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/python.png" +'twitter:title': "Ajouter une fonctionnalité de connexion à votre application Python Flask" +'twitter:description': "Ce guide explique comment intégrer Auth0 à une application PythonºFlask, à l’aide de la trousse SDK Authlib." +sidebarTitle: Python +--- + +import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; +import { LoggedInForm } from "/snippets/Login.jsx"; +import Server from "/snippets/quickstart/webapp/python/server.py.mdx"; +import Home from "/snippets/quickstart/webapp/python/home.html.mdx"; + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + +export const sections = [ + { id: "configuration-d-auth0", title: "Configuration d’Auth0" }, + { id: "installer-les-dépendances", title: "Installer les dépendances" }, + { id: "configurez-votre-fichier-env", title: "Configurez votre fichier .env" }, + { id: "configurez-votre-application", title: "Configurez votre application" }, + { id: "configurez-vos-routes", title: "Configurez vos routes" }, + { id: "ajouter-des-modèles", title: "Ajouter des modèles" }, + { id: "exécuter-votre-application", title: "Exécuter votre application" } +] + + + + Auth0 vous permet d’ajouter l’authentification et de pouvoir accéder aux informations relatives au profil de l’utilisateur dans votre application. Ce guide explique comment intégrer Auth0 à une application Python [Flask](https://flask.palletsprojects.com/), à l’aide de la trousse SDK [Authlib](https://authlib.org/). + +
    + Pour utiliser les services Auth0, vous devez avoir une application installée dans Auth0 Dashboard. L’application Auth0 est l’endroit où vous allez configurer le fonctionnement de l’authentification pour le projet que vous développez. + + ### Configurer une application + + Utilisez le sélecteur interactif pour créer une nouvelle application Auth0 ou sélectionner une application existante qui représente le projet avec lequel vous souhaitez effectuer l’intégration. Dans Auth0, chaque application se voit attribuer un identifiant client unique alphanumérique que votre code d’application utilisera pour appeler les API Auth0 via la trousse SDK. + + Tous les paramètres que vous configurez à l’aide de ce guide de démarrage rapide seront automatiquement mis à jour pour votre application dans le [Tableau de bord](https://manage.auth0.com/#/), qui est l’endroit où vous pourrez gérer vos applications à l’avenir. + + Si vous préférez explorer une configuration complète, consultez plutôt un exemple d’application. + + ### Configurer les URL de rappel + + Une URL de rappel est une URL intégrée dans votre application vers laquelle vous souhaitez qu’Auth0 redirige les utilisateurs après leur authentification. Si elle n’est pas définie, les utilisateurs ne seront pas redirigés vers votre application après s’être connectés. + + + Si vous suivez notre projet à titre d’exemple, définissez ceci sur `http://localhost:3000/callback`. + + + ### Configuration des URL de déconnexion + + Une URL de déconnexion est une URL intégrée dans votre application vers laquelle vous souhaitez qu’Auth0 redirige les utilisateurs après leur déconnexion. Si elle n’est pas définie, les utilisateurs ne pourront pas se déconnecter de votre application et recevront un message d’erreur. + + + Si vous suivez notre projet à titre d’exemple, définissez ceci sur `http://localhost:3000`. + +
    + +
    + Créez un fichier `requirements.txt` dans le répertoire de votre projet : + + ``` + # 📁 requirements.txt ----- + flask>=2.0.3 + python-dotenv>=0.19.2 + authlib>=1.0 + requests>=2.27.1 + ``` + + Exécutez la commande suivante depuis votre shell pour activer les dépendances suivantes dans votre projet : + + ```bash + pip install -r requirements.txt + ``` +
    + +
    + Ensuite, créez un fichier `.env` dans votre répertoire de projet. Ce fichier contiendra les clés de vos clients et d’autres détails de configuration. + + ``` + # 📁 .env ----- + AUTH0_CLIENT_ID={yourClientId} + AUTH0_CLIENT_SECRET={yourClientSecret} + AUTH0_DOMAIN={yourDomain} + APP_SECRET_KEY= + ``` + + - Générez une chaîne pour `APP_SECRET_KEY` en utilisant `openssl rand -hex 32` depuis votre shell. +
    + +
    + Ensuite, configurez votre application. Créez un fichier `server.py` dans le répertoire de votre projet; ce fichier contiendra la logique de votre application. + + Importez toutes les bibliothèques nécessaires à votre application. + + Chargez le fichier de configuration `.env` que vous avez créé à l’étape précédente. + + Configurez Authlib pour gérer l’authentification de votre application avec Auth0. Apprenez-en davantage sur les options de configuration possibles pour la méthode `register()` d’Authlib OAuth dans [leur documentation.](https://docs.authlib.org/en/latest/client/frameworks.html#using-oauth-2-0-to-log-in) +
    + +
    + Dans cet exemple, vous ajouterez quatre routes à l’application : connexion, callback, déconnexion et accueil. + + Lorsque les visiteurs de votre application se rendent sur la route `/login`, votre application les dirige vers la page de connexion Auth0. + + Une fois vos utilisateurs connectés avec Auth0, votre application les dirige vers la route `/callback`. Cette route enregistre la session de l’utilisateur et permet de ne plus avoir à se reconnecter lorsqu’il revient. + + La route `/logout` permet aux utilisateurs de se déconnecter de votre application. Cette route efface la session de l’utilisateur dans votre application et redirige vers le point de terminaison de déconnexion d’Auth0 pour s’assurer que la session n’est plus enregistrée. Ensuite, l’application redirige l’utilisateur vers votre route d’accueil. + + Votre route `/home` affiche les détails d’un utilisateur authentifié ou permet aux visiteurs de s’identifier. +
    + +
    + Créez ensuite le fichier de modèle utilisé dans la route d’accueil (lors des appels `render_template()`). + + Créez un nouveau sous-répertoire dans le dossier de votre projet, nommé `templates`, et créez `home.html` dans ce répertoire. Collez le contenu à droite dans ce fichier. +
    + +
    + Pour exécuter votre application, naviguez jusqu’à la racine du répertoire de votre projet et ouvrez un terminal. Exécutez la commande suivante : + + ``` + python3 server.py + ``` + + + ##### Point de contrôle + Visitez [http://localhost:3000](http://localhost:3000/) pour des raisons de vérification. Un bouton de connexion devrait vous permettre de vous connecter à Auth0, puis de revenir à votre application pour consulter les informations relatives à votre profil. + +
    + +## Étapes suivantes + +Beau travail! Si vous en êtes arrivé là, vous devriez avoir la connexion, la déconnexion et les informations de profil utilisateur actives dans votre application. + +Cela conclut notre tutoriel de démarrage rapide, mais il y a tellement plus à explorer. Pour en savoir plus sur ce que vous pouvez faire avec Auth0, consultez : + +* [Auth0 Dashboard](https://manage.auth0.com/#) : apprenez à configurer et gérer votre locataire et vos applications Auth0 +* [Trousse SDK auth0-python](https://github.com/auth0/auth0-python) : explorez en détail la trousse SDK utilisée dans ce tutoriel +* [Auth0 Marketplace](https://marketplace.auth0.com/) : découvrez des intégrations que vous pouvez activer pour étendre les fonctionnalités d’Auth0 +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    diff --git a/main/docs/fr-ca/quickstart/webapp/rails/interactive.mdx b/main/docs/fr-ca/quickstart/webapp/rails/interactive.mdx index fe812bae9..50eaef1d9 100644 --- a/main/docs/fr-ca/quickstart/webapp/rails/interactive.mdx +++ b/main/docs/fr-ca/quickstart/webapp/rails/interactive.mdx @@ -1,260 +1,262 @@ ---- -title: "Ajouter une connexion à votre application Ruby on Rails" -permalink: "interactive" -'description': "Ce tutoriel explique comment ajouter la connexion utilisateur à une application Ruby on Rails." -'og:title': "Ajouter une connexion à votre application Ruby on Rails" -'og:description': "Ce tutoriel explique comment ajouter la connexion utilisateur à une application Ruby on Rails." -'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/rails.png" -'twitter:title': "Ajouter une connexion à votre application Ruby on Rails" -'twitter:description': "Ce tutoriel explique comment ajouter la connexion utilisateur à une application Ruby on Rails." -sidebarTitle: Ruby on Rails ---- - -import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; -import { LoggedInForm } from "/snippets/Login.jsx"; -import Auth0Yml from "/snippets/quickstart/webapp/rails/auth0.yml.mdx"; -import Auth0 from "/snippets/quickstart/webapp/rails/auth0.rb.mdx"; -import Auth0Controller from "/snippets/quickstart/webapp/rails/auth0_controller.rb.mdx"; -import Routes from "/snippets/quickstart/webapp/rails/routes.rb.mdx"; -import Secured from "/snippets/quickstart/webapp/rails/secured.rb.mdx"; - -export const sections = [ - { id: "configuration-d-auth0", title: "Configuration d’Auth0" }, - { id: "ajouter-des-dépendances", title: "Ajouter des dépendances" }, - { id: "configuration-de-la-trousse-sdk", title: "Configuration de la trousse SDK" }, - { id: "configurer-l-intergiciel-omniauth", title: "Configurer l’intergiciel OmniAuth" }, - { id: "ajouter-un-contrôleur-auth0", title: "Ajouter un contrôleur Auth0" }, - { id: "configurer-les-routes", title: "Configurer les routes" }, - { id: "ajouter-une-fonctionnalité-de-connexion-à-votre-application", title: "Ajouter une fonctionnalité de connexion à votre application" }, - { id: "ajoutez-une-fonctionnalité-de-déconnexion-à-votre-application", title: "Ajoutez une fonctionnalité de déconnexion à votre application" }, - { id: "afficher-les-informations-du-profil-utilisateur", title: "Afficher les informations du profil utilisateur" } -] - - - -
    - Pour utiliser les services Auth0, vous devez avoir une application installée dans Auth0 Dashboard. L’application Auth0 est l’endroit où vous allez configurer le fonctionnement de l’authentification pour le projet que vous développez. - - ### Configurer une application - - Utilisez le sélecteur interactif pour créer une nouvelle application Auth0 ou sélectionner une application existante qui représente le projet avec lequel vous souhaitez effectuer l’intégration. Dans Auth0, il est attribué à chaque application un identifiant client unique alphanumérique que votre code d’application utilisera pour appeler les API Auth0 via la trousse SDK. - - Tous les paramètres que vous configurez à l’aide de ce guide rapide seront automatiquement mis à jour pour votre application dans le [Dashboard](https://manage.auth0.com/#/), qui est l’endroit où vous pourrez gérer vos applications à l’avenir. - - Si vous préférez explorer une configuration complète, consultez plutôt un exemple d’application. - - ### Configurer les URL de rappel - - Une URL de rappel est une URL intégrée dans votre application vers laquelle vous souhaitez qu’Auth0 redirige les utilisateurs après leur authentification. Si elle n’est pas définie, les utilisateurs ne seront pas redirigés vers votre application après s’être connectés. - - - Si vous suivez notre exemple de projet, définissez cette URL comme suit : `http://localhost:3000/auth/auth0/callback`. - - - ### Configuration des URL de déconnexion - - Une URL de déconnexion est une URL intégrée dans votre application vers laquelle vous souhaitez qu’Auth0 redirige les utilisateurs après leur déconnexion. Si elle n’est pas définie, les utilisateurs ne pourront pas se déconnecter de votre application et recevront un message d’erreur. - - - Si vous suivez notre exemple de projet, définissez cette URL comme suit : `http://localhost:3000`. - - - ### Configurer les origines Web autorisées - - Une origine Web autorisée est une URL que vous souhaitez autoriser à accéder à votre flux d’authentification. Elle doit contenir l’URL de votre projet. Si elle n’est pas configurée adéquatement, votre projet ne pourra pas actualiser silencieusement les jetons d’authentification, ce qui entraînera la déconnexion de vos utilisateurs lorsque prochainement ils visiteront votre application ou lors de l’actualisation d’une page. - - - Si vous suivez notre exemple de projet, définissez cette URL comme suit : `http://localhost:3000`. - -
    - -
    - Utilisez `omniauth-auth0`, une [stratégie OmniAuth](https://github.com/intridea/omniauth#omniauth-standardized-multi-provider-authentication) personnalisée, pour gérer le flux d’authentification. - - Ajoutez les dépendances suivantes à votre `Gemfile` : - - ``` - gem 'omniauth-auth0', '~> 3.0' - gem 'omniauth-rails_csrf_protection', '~> 1.0' # prevents forged authentication requests - ``` - - Une fois vos gems ajoutés, installez-les avec la commande `bundle install`. -
    - -
    - Créez un fichier de configuration `./config/auth0.yml` pour préciser votre domaine Auth0, votre identifiant client et vos valeurs de secret client situées dans votre Auth0 Dashboard sous les **paramètres** de l’application. -
    - -
    - Créez le fichier d’initialisation suivant `./config/initializers/auth0.rb` et [configurez](https://github.com/auth0/omniauth-auth0/blob/master/EXAMPLES.md#send-additional-authentication-parameters) l’intergiciel **OmniAuth** avec le fichier de configuration que vous avez créé à l’étape précédente. - - Assurez-vous que `callback_path` correspond à la valeur donnée dans le paramètre des URL de rappel autorisées de votre application Auth0. -
    - -
    - Créez un contrôleur Auth0 pour gérer le rappel d’authentification, l’action `logout` et les méthodes pour créer l’URL de déconnexion. - - Exécutez la commande `rails generate controller auth0 callback failure logout --skip-assets --skip-helper --skip-routes --skip-template-engine`. - - Dans la méthode de rappel, assignez le hachage des informations utilisateur, renvoyé en tant que `request.env[’omniauth.auth’]` à la session active. - - Pour configurer la déconnexion, effacez tous les objets stockés dans la session en appelant la méthode `reset_session` dans l’action `logout`. Ensuite, redirigez vers le point de terminaison de déconnexion Auth0. Pour en savoir plus sur `reset_session`, consultez [Documentation relative au ActionController Ruby on Rails](http://api.rubyonrails.org/classes/ActionController/Base.html#M000668). -
    - -
    - Ajoutez ces routes à votre fichier `./config/routes.rb`. - - Les routes doivent être en place afin que Rails sache comment diriger les différentes URL de rappel Auth0 vers le contrôleur Auth0 que vous avez créé à l’étape précédente. - - - ##### Point de contrôle - Exécutez votre application pour vérifier qu’elle fonctionne toujours comme prévu et que vous ne recevez aucun message d’erreur lié à Auth0. - -
    - -
    - Un utilisateur peut maintenant se connecter à votre application en visitant le point de terminaison `/auth/auth0`. - - - Pour [prévenir les requêtes d’authentification falsifiées](https://github.com/cookpad/omniauth-rails\_csrf\_protection), utilisez les méthodes d’assistance `link\_to` ou `button\_to` avec la méthode `:post`. - - - ```html - - <%= button_to 'Login', '/auth/auth0', method: :post %> - ``` - - - ##### Point de contrôle - Ajoutez un bouton à votre application qui redirige l’utilisateur vers le point de terminaison `/auth/auth0` lorsqu’il est sélectionné. Observez si vous êtes redirigé vers Auth0 pour vous connecter, puis renvoyé vers votre application après une authentification réussie. - -
    - -
    - Maintenant que vous pouvez vous connecter à votre application Rails, vous avez besoin d’un moyen de vous déconnecter. Déconnectez un utilisateur en le redirigeant vers l’action `auth/logout` qui le redirige vers le point de terminaison de déconnexion d’Auth0. - - - Pour tester cela après l’étape précédente, vous devez peut-être effacer votre session, puis rediriger l’utilisateur vers le point de terminaison de déconnexion d’Auth0. - - - ```html - - <%= button_to 'Logout', 'auth/logout', method: :get %> - ``` - - - ##### Point de contrôle - Ajoutez un bouton à votre application qui redirige l’utilisateur vers le point de terminaison `/auth/logout` lorsqu’il est sélectionné. Vérifiez que vous êtes redirigé vers Auth0, puis renvoyé rapidement vers votre application, et que vous n’êtes plus connecté. - -
    - -
    - Pour afficher le profil utilisateur, votre application doit fournir une route protégée. Vous pouvez utiliser une [préoccupation](https://guides.rubyonrails.org/getting_started.html#using-concerns) pour contrôler l’accès aux routes qui peuvent être partagées entre plusieurs contrôleurs. La préoccupation devrait rediriger automatiquement vers Auth0 lorsque l’utilisateur n’est pas authentifié. Au cas contraire, la préoccupation devrait renvoyer le profil utilisateur actuel. - - Une fois que vous avez une préoccupation, incluez-la dans tout contrôleur qui nécessite un utilisateur connecté. Vous pouvez ensuite accéder à l’utilisateur à partir de la session `session[:userinfo]` comme dans l’exemple suivant : - - ``` - class DashboardController < ApplicationController - include Secured - def show - @user = session[:userinfo] - - end - end - ``` - - Une fois que l’utilisateur a chargé la session, utilisez-la pour afficher des informations dans votre système frontal : - - ```html -
    -

    Normalized User Profile:<%= JSON.pretty_generate(@user[:info])%>

    -

    Full User Profile:<%= JSON.pretty_generate(@user[:extra][:raw_info])%>

    -
    - ``` - - - ##### Point de contrôle - Ajoutez le concern `Secured` à votre application, puis incluez-le dans le contrôleur qui nécessite un utilisateur authentifié pour y accéder. Vérifiez qu’un utilisateur authentifié a accès aux actions de ce contrôleur et que les utilisateurs non authentifiés sont redirigés vers Auth0 pour l’authentification. - -
    - - ## Étapes suivantes - - Beau travail! Si vous en êtes arrivé là, vous devriez avoir la connexion, la déconnexion et les informations de profil utilisateur actives dans votre application. - - Cela conclut notre tutoriel de démarrage rapide, mais il y a tellement plus à explorer. Pour en savoir plus sur ce que vous pouvez faire avec Auth0, consultez : - - * [Auth0 Dashboard](https://manage.auth0.com/#) : apprenez à configurer et gérer votre locataire et vos applications Auth0 - * [Trousse SDK omniauth-auth0](https://github.com/auth0/omniauth-auth0) : explorez en détail la trousse SDK utilisée dans ce tutoriel - * [Auth0 Marketplace](https://marketplace.auth0.com/) : découvrez des intégrations que vous pouvez activer pour étendre les fonctionnalités d’Auth0 -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    +--- +title: "Ajouter une connexion à votre application Ruby on Rails" +permalink: "interactive" +'description': "Ce tutoriel explique comment ajouter la connexion utilisateur à une application Ruby on Rails." +'og:title': "Ajouter une connexion à votre application Ruby on Rails" +'og:description': "Ce tutoriel explique comment ajouter la connexion utilisateur à une application Ruby on Rails." +'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/rails.png" +'twitter:title': "Ajouter une connexion à votre application Ruby on Rails" +'twitter:description': "Ce tutoriel explique comment ajouter la connexion utilisateur à une application Ruby on Rails." +sidebarTitle: Ruby on Rails +--- + +import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; +import { LoggedInForm } from "/snippets/Login.jsx"; +import Auth0Yml from "/snippets/quickstart/webapp/rails/auth0.yml.mdx"; +import Auth0 from "/snippets/quickstart/webapp/rails/auth0.rb.mdx"; +import Auth0Controller from "/snippets/quickstart/webapp/rails/auth0_controller.rb.mdx"; +import Routes from "/snippets/quickstart/webapp/rails/routes.rb.mdx"; +import Secured from "/snippets/quickstart/webapp/rails/secured.rb.mdx"; + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + +export const sections = [ + { id: "configuration-d-auth0", title: "Configuration d’Auth0" }, + { id: "ajouter-des-dépendances", title: "Ajouter des dépendances" }, + { id: "configuration-de-la-trousse-sdk", title: "Configuration de la trousse SDK" }, + { id: "configurer-l-intergiciel-omniauth", title: "Configurer l’intergiciel OmniAuth" }, + { id: "ajouter-un-contrôleur-auth0", title: "Ajouter un contrôleur Auth0" }, + { id: "configurer-les-routes", title: "Configurer les routes" }, + { id: "ajouter-une-fonctionnalité-de-connexion-à-votre-application", title: "Ajouter une fonctionnalité de connexion à votre application" }, + { id: "ajoutez-une-fonctionnalité-de-déconnexion-à-votre-application", title: "Ajoutez une fonctionnalité de déconnexion à votre application" }, + { id: "afficher-les-informations-du-profil-utilisateur", title: "Afficher les informations du profil utilisateur" } +] + + + +
    + Pour utiliser les services Auth0, vous devez avoir une application installée dans Auth0 Dashboard. L’application Auth0 est l’endroit où vous allez configurer le fonctionnement de l’authentification pour le projet que vous développez. + + ### Configurer une application + + Utilisez le sélecteur interactif pour créer une nouvelle application Auth0 ou sélectionner une application existante qui représente le projet avec lequel vous souhaitez effectuer l’intégration. Dans Auth0, il est attribué à chaque application un identifiant client unique alphanumérique que votre code d’application utilisera pour appeler les API Auth0 via la trousse SDK. + + Tous les paramètres que vous configurez à l’aide de ce guide rapide seront automatiquement mis à jour pour votre application dans le [Dashboard](https://manage.auth0.com/#/), qui est l’endroit où vous pourrez gérer vos applications à l’avenir. + + Si vous préférez explorer une configuration complète, consultez plutôt un exemple d’application. + + ### Configurer les URL de rappel + + Une URL de rappel est une URL intégrée dans votre application vers laquelle vous souhaitez qu’Auth0 redirige les utilisateurs après leur authentification. Si elle n’est pas définie, les utilisateurs ne seront pas redirigés vers votre application après s’être connectés. + + + Si vous suivez notre exemple de projet, définissez cette URL comme suit : `http://localhost:3000/auth/auth0/callback`. + + + ### Configuration des URL de déconnexion + + Une URL de déconnexion est une URL intégrée dans votre application vers laquelle vous souhaitez qu’Auth0 redirige les utilisateurs après leur déconnexion. Si elle n’est pas définie, les utilisateurs ne pourront pas se déconnecter de votre application et recevront un message d’erreur. + + + Si vous suivez notre exemple de projet, définissez cette URL comme suit : `http://localhost:3000`. + + + ### Configurer les origines Web autorisées + + Une origine Web autorisée est une URL que vous souhaitez autoriser à accéder à votre flux d’authentification. Elle doit contenir l’URL de votre projet. Si elle n’est pas configurée adéquatement, votre projet ne pourra pas actualiser silencieusement les jetons d’authentification, ce qui entraînera la déconnexion de vos utilisateurs lorsque prochainement ils visiteront votre application ou lors de l’actualisation d’une page. + + + Si vous suivez notre exemple de projet, définissez cette URL comme suit : `http://localhost:3000`. + +
    + +
    + Utilisez `omniauth-auth0`, une [stratégie OmniAuth](https://github.com/intridea/omniauth#omniauth-standardized-multi-provider-authentication) personnalisée, pour gérer le flux d’authentification. + + Ajoutez les dépendances suivantes à votre `Gemfile` : + + ``` + gem 'omniauth-auth0', '~> 3.0' + gem 'omniauth-rails_csrf_protection', '~> 1.0' # prevents forged authentication requests + ``` + + Une fois vos gems ajoutés, installez-les avec la commande `bundle install`. +
    + +
    + Créez un fichier de configuration `./config/auth0.yml` pour préciser votre domaine Auth0, votre identifiant client et vos valeurs de secret client situées dans votre Auth0 Dashboard sous les **paramètres** de l’application. +
    + +
    + Créez le fichier d’initialisation suivant `./config/initializers/auth0.rb` et [configurez](https://github.com/auth0/omniauth-auth0/blob/master/EXAMPLES.md#send-additional-authentication-parameters) l’intergiciel **OmniAuth** avec le fichier de configuration que vous avez créé à l’étape précédente. + + Assurez-vous que `callback_path` correspond à la valeur donnée dans le paramètre des URL de rappel autorisées de votre application Auth0. +
    + +
    + Créez un contrôleur Auth0 pour gérer le rappel d’authentification, l’action `logout` et les méthodes pour créer l’URL de déconnexion. + + Exécutez la commande `rails generate controller auth0 callback failure logout --skip-assets --skip-helper --skip-routes --skip-template-engine`. + + Dans la méthode de rappel, assignez le hachage des informations utilisateur, renvoyé en tant que `request.env[’omniauth.auth’]` à la session active. + + Pour configurer la déconnexion, effacez tous les objets stockés dans la session en appelant la méthode `reset_session` dans l’action `logout`. Ensuite, redirigez vers le point de terminaison de déconnexion Auth0. Pour en savoir plus sur `reset_session`, consultez [Documentation relative au ActionController Ruby on Rails](http://api.rubyonrails.org/classes/ActionController/Base.html#M000668). +
    + +
    + Ajoutez ces routes à votre fichier `./config/routes.rb`. + + Les routes doivent être en place afin que Rails sache comment diriger les différentes URL de rappel Auth0 vers le contrôleur Auth0 que vous avez créé à l’étape précédente. + + + ##### Point de contrôle + Exécutez votre application pour vérifier qu’elle fonctionne toujours comme prévu et que vous ne recevez aucun message d’erreur lié à Auth0. + +
    + +
    + Un utilisateur peut maintenant se connecter à votre application en visitant le point de terminaison `/auth/auth0`. + + + Pour [prévenir les requêtes d’authentification falsifiées](https://github.com/cookpad/omniauth-rails\_csrf\_protection), utilisez les méthodes d’assistance `link\_to` ou `button\_to` avec la méthode `:post`. + + + ```html + + <%= button_to 'Login', '/auth/auth0', method: :post %> + ``` + + + ##### Point de contrôle + Ajoutez un bouton à votre application qui redirige l’utilisateur vers le point de terminaison `/auth/auth0` lorsqu’il est sélectionné. Observez si vous êtes redirigé vers Auth0 pour vous connecter, puis renvoyé vers votre application après une authentification réussie. + +
    + +
    + Maintenant que vous pouvez vous connecter à votre application Rails, vous avez besoin d’un moyen de vous déconnecter. Déconnectez un utilisateur en le redirigeant vers l’action `auth/logout` qui le redirige vers le point de terminaison de déconnexion d’Auth0. + + + Pour tester cela après l’étape précédente, vous devez peut-être effacer votre session, puis rediriger l’utilisateur vers le point de terminaison de déconnexion d’Auth0. + + + ```html + + <%= button_to 'Logout', 'auth/logout', method: :get %> + ``` + + + ##### Point de contrôle + Ajoutez un bouton à votre application qui redirige l’utilisateur vers le point de terminaison `/auth/logout` lorsqu’il est sélectionné. Vérifiez que vous êtes redirigé vers Auth0, puis renvoyé rapidement vers votre application, et que vous n’êtes plus connecté. + +
    + +
    + Pour afficher le profil utilisateur, votre application doit fournir une route protégée. Vous pouvez utiliser une [préoccupation](https://guides.rubyonrails.org/getting_started.html#using-concerns) pour contrôler l’accès aux routes qui peuvent être partagées entre plusieurs contrôleurs. La préoccupation devrait rediriger automatiquement vers Auth0 lorsque l’utilisateur n’est pas authentifié. Au cas contraire, la préoccupation devrait renvoyer le profil utilisateur actuel. + + Une fois que vous avez une préoccupation, incluez-la dans tout contrôleur qui nécessite un utilisateur connecté. Vous pouvez ensuite accéder à l’utilisateur à partir de la session `session[:userinfo]` comme dans l’exemple suivant : + + ``` + class DashboardController < ApplicationController + include Secured + def show + @user = session[:userinfo] + + end + end + ``` + + Une fois que l’utilisateur a chargé la session, utilisez-la pour afficher des informations dans votre système frontal : + + ```html +
    +

    Normalized User Profile:<%= JSON.pretty_generate(@user[:info])%>

    +

    Full User Profile:<%= JSON.pretty_generate(@user[:extra][:raw_info])%>

    +
    + ``` + + + ##### Point de contrôle + Ajoutez le concern `Secured` à votre application, puis incluez-le dans le contrôleur qui nécessite un utilisateur authentifié pour y accéder. Vérifiez qu’un utilisateur authentifié a accès aux actions de ce contrôleur et que les utilisateurs non authentifiés sont redirigés vers Auth0 pour l’authentification. + +
    + + ## Étapes suivantes + + Beau travail! Si vous en êtes arrivé là, vous devriez avoir la connexion, la déconnexion et les informations de profil utilisateur actives dans votre application. + + Cela conclut notre tutoriel de démarrage rapide, mais il y a tellement plus à explorer. Pour en savoir plus sur ce que vous pouvez faire avec Auth0, consultez : + + * [Auth0 Dashboard](https://manage.auth0.com/#) : apprenez à configurer et gérer votre locataire et vos applications Auth0 + * [Trousse SDK omniauth-auth0](https://github.com/auth0/omniauth-auth0) : explorez en détail la trousse SDK utilisée dans ce tutoriel + * [Auth0 Marketplace](https://marketplace.auth0.com/) : découvrez des intégrations que vous pouvez activer pour étendre les fonctionnalités d’Auth0 +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    diff --git a/main/docs/fr-ca/secure/data-privacy-and-compliance/gdpr/gdpr-conditions-for-consent.mdx b/main/docs/fr-ca/secure/data-privacy-and-compliance/gdpr/gdpr-conditions-for-consent.mdx index 294050be4..1536da5ee 100644 --- a/main/docs/fr-ca/secure/data-privacy-and-compliance/gdpr/gdpr-conditions-for-consent.mdx +++ b/main/docs/fr-ca/secure/data-privacy-and-compliance/gdpr/gdpr-conditions-for-consent.mdx @@ -10,6 +10,7 @@ permalink: "gdpr-conditions-for-consent" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Conformément à l’article 7 du RGPD, vous devez demander aux utilisateurs de consentir au traitement de leurs données personnelles sous une forme claire et facilement accessible. Vous devez également montrer que l’utilisateur a consenti et lui fournir un moyen facile de retirer son consentement à tout moment. @@ -81,14 +82,20 @@ Définissez le paramètre de requête **fields** sur `user_metadata` afin de lim Exemple de demande : -export const codeExample1 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/users-by-email?email=USER_EMAIL_ADDRESS&fields=user_metadata' \ - --header 'authorization: Bearer YOUR_MGMT_API_ACCESS_TOKEN'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/users-by-email?email=USER_EMAIL_ADDRESS&fields=user_metadata"); + --header 'authorization: Bearer YOUR_MGMT_API_ACCESS_TOKEN' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users-by-email?email=USER_EMAIL_ADDRESS&fields=user_metadata"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer YOUR_MGMT_API_ACCESS_TOKEN"); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -112,11 +119,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/users-by-email?email=USER_EMAIL_ADDRESS&fields=user_metadata") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/users-by-email?email=USER_EMAIL_ADDRESS&fields=user_metadata") .header("authorization", "Bearer YOUR_MGMT_API_ACCESS_TOKEN") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -129,8 +140,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer YOUR_MGMT_API_ACCESS_TOKEN" }; @@ -150,8 +163,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users-by-email?email=USER_EMAIL_ADDRESS&fields=user_metadata", @@ -175,8 +190,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -187,8 +204,10 @@ conn.request("GET", "/{yourDomain}/api/v2/users-by-email?email=USER_EMAIL_ADDRES res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -202,8 +221,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer YOUR_MGMT_API_ACCESS_TOKEN' response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer YOUR_MGMT_API_ACCESS_TOKEN"] @@ -223,20 +244,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + Exemple de réponse : @@ -263,14 +273,20 @@ Définissez le paramètre de requête **fields** sur `user_metadata` afin de lim Exemple de demande : -export const codeExample11 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/users/%7ByourUserID%7D?fields=user_metadata' \ - --header 'authorization: Bearer {yourMgmtApiAccessToken}'`; -export const codeExample12 = `var client = new RestClient("https://{yourDomain}/api/v2/users/%7ByourUserID%7D?fields=user_metadata"); + --header 'authorization: Bearer {yourMgmtApiAccessToken}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users/%7ByourUserID%7D?fields=user_metadata"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer {yourMgmtApiAccessToken}"); -IRestResponse response = client.Execute(request);`; -export const codeExample13 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -294,11 +310,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample14 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/users/%7ByourUserID%7D?fields=user_metadata") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/users/%7ByourUserID%7D?fields=user_metadata") .header("authorization", "Bearer {yourMgmtApiAccessToken}") - .asString();`; -export const codeExample15 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -311,8 +331,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample16 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer {yourMgmtApiAccessToken}" }; @@ -332,8 +354,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users/%7ByourUserID%7D?fields=user_metadata", @@ -357,8 +381,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -369,8 +395,10 @@ conn.request("GET", "/{yourDomain}/api/v2/users/%7ByourUserID%7D?fields=user_met res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -384,8 +412,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer {yourMgmtApiAccessToken}' response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer {yourMgmtApiAccessToken}"] @@ -405,20 +435,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + Exemple de réponse : @@ -464,18 +483,24 @@ Si vos métadonnées sont stockées en tant que propriétés internes : Les mises à jour des propriétés de niveau racine sont fusionnées, il vous suffit donc d’envoyer la valeur du champ que vous souhaitez mettre à jour. Par exemple, supposons que nous voulions ajouter une date de consentement et la définir sur `2018-01-23`. -export const codeExample21 = `curl --request PATCH \ + +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/users/USER_ID' \ --header 'authorization: Bearer YOUR_MGMT_API_ACCESS_TOKEN' \ --header 'content-type: application/json' \ - --data '{"user_metadata":{"consentDate":"01/24/2018"}}'`; -export const codeExample22 = `var client = new RestClient("https://{yourDomain}/api/v2/users/USER_ID"); + --data '{"user_metadata":{"consentDate":"01/24/2018"}}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users/USER_ID"); var request = new RestRequest(Method.PATCH); request.AddHeader("authorization", "Bearer YOUR_MGMT_API_ACCESS_TOKEN"); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\"user_metadata\":{\"consentDate\":\"01/24/2018\"}}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample23 = `package main +request.AddParameter("application/json", "{"user_metadata":{"consentDate":"01/24/2018"}}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -488,7 +513,7 @@ func main() { url := "https://{yourDomain}/api/v2/users/USER_ID" - payload := strings.NewReader("{\"user_metadata\":{\"consentDate\":\"01/24/2018\"}}") + payload := strings.NewReader("{"user_metadata":{"consentDate":"01/24/2018"}}") req, _ := http.NewRequest("PATCH", url, payload) @@ -503,13 +528,17 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample24 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/users/USER_ID") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/users/USER_ID") .header("authorization", "Bearer YOUR_MGMT_API_ACCESS_TOKEN") .header("content-type", "application/json") - .body("{\"user_metadata\":{\"consentDate\":\"01/24/2018\"}}") - .asString();`; -export const codeExample25 = `var axios = require("axios").default; + .body("{"user_metadata":{"consentDate":"01/24/2018"}}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -525,8 +554,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample26 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer YOUR_MGMT_API_ACCESS_TOKEN", @"content-type": @"application/json" }; @@ -551,8 +582,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample27 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users/USER_ID", @@ -562,7 +595,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{\"user_metadata\":{\"consentDate\":\"01/24/2018\"}}", + CURLOPT_POSTFIELDS => "{"user_metadata":{"consentDate":"01/24/2018"}}", CURLOPT_HTTPHEADER => [ "authorization: Bearer YOUR_MGMT_API_ACCESS_TOKEN", "content-type: application/json" @@ -578,12 +611,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample28 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"user_metadata\":{\"consentDate\":\"01/24/2018\"}}" +payload = "{"user_metadata":{"consentDate":"01/24/2018"}}" headers = { 'authorization': "Bearer YOUR_MGMT_API_ACCESS_TOKEN", @@ -595,8 +630,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/users/USER_ID", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample29 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -609,11 +646,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Patch.new(url) request["authorization"] = 'Bearer YOUR_MGMT_API_ACCESS_TOKEN' request["content-type"] = 'application/json' -request.body = "{\"user_metadata\":{\"consentDate\":\"01/24/2018\"}}" +request.body = "{"user_metadata":{"consentDate":"01/24/2018"}}" response = http.request(request) -puts response.read_body`; -export const codeExample30 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "authorization": "Bearer YOUR_MGMT_API_ACCESS_TOKEN", @@ -640,20 +679,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + Ceci ajoutera une nouvelle propriété au profil utilisateur, **user_metadata.consentDate**, qui contiendra la date à laquelle le client a donné son consentement. La réponse sera le profil utilisateur complet. Les métadonnées mises à jour se présenteront comme suit : @@ -671,18 +699,24 @@ Pour mettre à jour une propriété interne, vous devez envoyer l’ensemble de Ajoutons une propriété interne pour la date de consentement et fixons-la à `2018-01-23`. -export const codeExample31 = `curl --request PATCH \ + +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/users/USER_ID' \ --header 'authorization: Bearer YOUR_MGMT_API_ACCESS_TOKEN' \ --header 'content-type: application/json' \ - --data '{"user_metadata":{"consent": {"given":true, "date":"01/23/2018", "text_details":"some-url"}}}'`; -export const codeExample32 = `var client = new RestClient("https://{yourDomain}/api/v2/users/USER_ID"); + --data '{"user_metadata":{"consent": {"given":true, "date":"01/23/2018", "text_details":"some-url"}}}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users/USER_ID"); var request = new RestRequest(Method.PATCH); request.AddHeader("authorization", "Bearer YOUR_MGMT_API_ACCESS_TOKEN"); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\"user_metadata\":{\"consent\": {\"given\":true, \"date\":\"01/23/2018\", \"text_details\":\"some-url\"}}}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample33 = `package main +request.AddParameter("application/json", "{"user_metadata":{"consent": {"given":true, "date":"01/23/2018", "text_details":"some-url"}}}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -695,7 +729,7 @@ func main() { url := "https://{yourDomain}/api/v2/users/USER_ID" - payload := strings.NewReader("{\"user_metadata\":{\"consent\": {\"given\":true, \"date\":\"01/23/2018\", \"text_details\":\"some-url\"}}}") + payload := strings.NewReader("{"user_metadata":{"consent": {"given":true, "date":"01/23/2018", "text_details":"some-url"}}}") req, _ := http.NewRequest("PATCH", url, payload) @@ -710,13 +744,17 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample34 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/users/USER_ID") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/users/USER_ID") .header("authorization", "Bearer YOUR_MGMT_API_ACCESS_TOKEN") .header("content-type", "application/json") - .body("{\"user_metadata\":{\"consent\": {\"given\":true, \"date\":\"01/23/2018\", \"text_details\":\"some-url\"}}}") - .asString();`; -export const codeExample35 = `var axios = require("axios").default; + .body("{"user_metadata":{"consent": {"given":true, "date":"01/23/2018", "text_details":"some-url"}}}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -734,8 +772,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample36 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer YOUR_MGMT_API_ACCESS_TOKEN", @"content-type": @"application/json" }; @@ -760,8 +800,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample37 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users/USER_ID", @@ -771,7 +813,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{\"user_metadata\":{\"consent\": {\"given\":true, \"date\":\"01/23/2018\", \"text_details\":\"some-url\"}}}", + CURLOPT_POSTFIELDS => "{"user_metadata":{"consent": {"given":true, "date":"01/23/2018", "text_details":"some-url"}}}", CURLOPT_HTTPHEADER => [ "authorization: Bearer YOUR_MGMT_API_ACCESS_TOKEN", "content-type: application/json" @@ -787,12 +829,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample38 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"user_metadata\":{\"consent\": {\"given\":true, \"date\":\"01/23/2018\", \"text_details\":\"some-url\"}}}" +payload = "{"user_metadata":{"consent": {"given":true, "date":"01/23/2018", "text_details":"some-url"}}}" headers = { 'authorization': "Bearer YOUR_MGMT_API_ACCESS_TOKEN", @@ -804,8 +848,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/users/USER_ID", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample39 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -818,11 +864,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Patch.new(url) request["authorization"] = 'Bearer YOUR_MGMT_API_ACCESS_TOKEN' request["content-type"] = 'application/json' -request.body = "{\"user_metadata\":{\"consent\": {\"given\":true, \"date\":\"01/23/2018\", \"text_details\":\"some-url\"}}}" +request.body = "{"user_metadata":{"consent": {"given":true, "date":"01/23/2018", "text_details":"some-url"}}}" response = http.request(request) -puts response.read_body`; -export const codeExample40 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "authorization": "Bearer YOUR_MGMT_API_ACCESS_TOKEN", @@ -853,20 +901,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + Ceci ajoutera une nouvelle propriété au profil utilisateur, **user_metadata.consent.date,**, qui contiendra la date à laquelle le client a donné son consentement. La réponse sera le profil utilisateur complet. Les métadonnées mises à jour se présenteront comme suit : @@ -895,14 +932,20 @@ Tout d’abord, vous devez décider comment vous allez gérer le retrait du cons Pour supprimer un utilisateur, utilisez le [point de terminaison **Supprimer un utilisateur**](/docs/fr-ca/api/management/v2#!/Users/delete_users_by_id). -export const codeExample41 = `curl --request DELETE \ + +```bash cURL +curl --request DELETE \ --url 'https://{yourDomain}/api/v2/users/USER_ID' \ - --header 'authorization: Bearer YOUR_MGMT_API_ACCESS_TOKEN'`; -export const codeExample42 = `var client = new RestClient("https://{yourDomain}/api/v2/users/USER_ID"); + --header 'authorization: Bearer YOUR_MGMT_API_ACCESS_TOKEN' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users/USER_ID"); var request = new RestRequest(Method.DELETE); request.AddHeader("authorization", "Bearer YOUR_MGMT_API_ACCESS_TOKEN"); -IRestResponse response = client.Execute(request);`; -export const codeExample43 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -926,11 +969,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample44 = `HttpResponse response = Unirest.delete("https://{yourDomain}/api/v2/users/USER_ID") +} +``` +```java Java +HttpResponse response = Unirest.delete("https://{yourDomain}/api/v2/users/USER_ID") .header("authorization", "Bearer YOUR_MGMT_API_ACCESS_TOKEN") - .asString();`; -export const codeExample45 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'DELETE', @@ -942,8 +989,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample46 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer YOUR_MGMT_API_ACCESS_TOKEN" }; @@ -963,8 +1012,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample47 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users/USER_ID", @@ -988,8 +1039,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample48 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -1000,8 +1053,10 @@ conn.request("DELETE", "/{yourDomain}/api/v2/users/USER_ID", headers=headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample49 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -1015,8 +1070,10 @@ request = Net::HTTP::Delete.new(url) request["authorization"] = 'Bearer YOUR_MGMT_API_ACCESS_TOKEN' response = http.request(request) -puts response.read_body`; -export const codeExample50 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer YOUR_MGMT_API_ACCESS_TOKEN"] @@ -1036,20 +1093,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + Le corps de la réponse de ce point de terminaison est vide. Ainsi, si vous souhaitez confirmer que l’utilisateur a été supprimé, essayez de récupérer l’utilisateur à l’aide de son adresse courriel. Si le point de terminaison renvoie une erreur, votre appel de suppression de l’utilisateur a réussi. @@ -1065,18 +1111,24 @@ Pour marquer un utilisateur comme supprimé, utilisez app_metadata. Dans l’exe Pour mettre à jour les métadonnées d’un utilisateur, utilisez le [point de terminaison **Mettre à jour un utilisateur**](/docs/fr-ca/api/management/v2#!/Users/patch_users_by_id). -export const codeExample51 = `curl --request PATCH \ + +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/users/USER_ID' \ --header 'authorization: Bearer YOUR_MGMT_API_ACCESS_TOKEN' \ --header 'content-type: application/json' \ - --data '{"app_metadata":{"deleted":true}}'`; -export const codeExample52 = `var client = new RestClient("https://{yourDomain}/api/v2/users/USER_ID"); + --data '{"app_metadata":{"deleted":true}}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users/USER_ID"); var request = new RestRequest(Method.PATCH); request.AddHeader("authorization", "Bearer YOUR_MGMT_API_ACCESS_TOKEN"); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\"app_metadata\":{\"deleted\":true}}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample53 = `package main +request.AddParameter("application/json", "{"app_metadata":{"deleted":true}}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -1089,7 +1141,7 @@ func main() { url := "https://{yourDomain}/api/v2/users/USER_ID" - payload := strings.NewReader("{\"app_metadata\":{\"deleted\":true}}") + payload := strings.NewReader("{"app_metadata":{"deleted":true}}") req, _ := http.NewRequest("PATCH", url, payload) @@ -1104,13 +1156,17 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample54 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/users/USER_ID") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/users/USER_ID") .header("authorization", "Bearer YOUR_MGMT_API_ACCESS_TOKEN") .header("content-type", "application/json") - .body("{\"app_metadata\":{\"deleted\":true}}") - .asString();`; -export const codeExample55 = `var axios = require("axios").default; + .body("{"app_metadata":{"deleted":true}}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -1126,8 +1182,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample56 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer YOUR_MGMT_API_ACCESS_TOKEN", @"content-type": @"application/json" }; @@ -1152,8 +1210,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample57 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users/USER_ID", @@ -1163,7 +1223,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{\"app_metadata\":{\"deleted\":true}}", + CURLOPT_POSTFIELDS => "{"app_metadata":{"deleted":true}}", CURLOPT_HTTPHEADER => [ "authorization: Bearer YOUR_MGMT_API_ACCESS_TOKEN", "content-type: application/json" @@ -1179,12 +1239,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample58 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"app_metadata\":{\"deleted\":true}}" +payload = "{"app_metadata":{"deleted":true}}" headers = { 'authorization': "Bearer YOUR_MGMT_API_ACCESS_TOKEN", @@ -1196,8 +1258,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/users/USER_ID", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample59 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -1210,11 +1274,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Patch.new(url) request["authorization"] = 'Bearer YOUR_MGMT_API_ACCESS_TOKEN' request["content-type"] = 'application/json' -request.body = "{\"app_metadata\":{\"deleted\":true}}" +request.body = "{"app_metadata":{"deleted":true}}" response = http.request(request) -puts response.read_body`; -export const codeExample60 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "authorization": "Bearer YOUR_MGMT_API_ACCESS_TOKEN", @@ -1241,20 +1307,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + #### Désactiver la connexion pour les utilisateurs marqués diff --git a/main/docs/fr-ca/secure/data-privacy-and-compliance/gdpr/gdpr-track-consent-with-custom-ui.mdx b/main/docs/fr-ca/secure/data-privacy-and-compliance/gdpr/gdpr-track-consent-with-custom-ui.mdx index c11915e1b..3e8f7f248 100644 --- a/main/docs/fr-ca/secure/data-privacy-and-compliance/gdpr/gdpr-track-consent-with-custom-ui.mdx +++ b/main/docs/fr-ca/secure/data-privacy-and-compliance/gdpr/gdpr-track-consent-with-custom-ui.mdx @@ -10,6 +10,7 @@ permalink: "gdpr-track-consent-with-custom-ui" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Dans ce tutoriel, nous allons expliquer comment utiliser auth0.js ou les API Auth0 pour obtenir des informations sur le consentement, puis enregistrer ces informations dans les métadonnées de l’utilisateur. Pour en savoir plus, lisez [Comprendre le fonctionnement des métadonnées dans les profils utilisateurs](/docs/fr-ca/manage-users/user-accounts/metadata). @@ -121,16 +122,22 @@ Si vous servez votre page de connexion à partir de votre propre serveur, alors En ce qui concerne le même scénario dont nous avons discuté jusqu’à présent, une fois que vous inscrivez un nouvel utilisateur, vous pouvez utiliser le fragment de code suivant pour créer l’utilisateur dans Auth0 et définir les métadonnées. N’oubliez pas de remplacer la valeur du paramètre de requête `consentTimestamp` par la date/heure à laquelle l’utilisateur a donné son consentement. -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/dbconnections/signup' \ --header 'content-type: application/json' \ - --data '{"client_id": "{yourClientId}","email": "YOUR_USER_EMAIL","password": "YOUR_USER_PASSWORD","user_metadata": {"consentGiven": "true", "consentTimestamp": "1525101183" }}'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/dbconnections/signup"); + --data '{"client_id": "{yourClientId}","email": "YOUR_USER_EMAIL","password": "YOUR_USER_PASSWORD","user_metadata": {"consentGiven": "true", "consentTimestamp": "1525101183" }}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/dbconnections/signup"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\"client_id\": \"{yourClientId}\",\"email\": \"YOUR_USER_EMAIL\",\"password\": \"YOUR_USER_PASSWORD\",\"user_metadata\": {\"consentGiven\": \"true\", \"consentTimestamp\": \"1525101183\" }}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{"client_id": "{yourClientId}","email": "YOUR_USER_EMAIL","password": "YOUR_USER_PASSWORD","user_metadata": {"consentGiven": "true", "consentTimestamp": "1525101183" }}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -143,7 +150,7 @@ func main() { url := "https://{yourDomain}/dbconnections/signup" - payload := strings.NewReader("{\"client_id\": \"{yourClientId}\",\"email\": \"YOUR_USER_EMAIL\",\"password\": \"YOUR_USER_PASSWORD\",\"user_metadata\": {\"consentGiven\": \"true\", \"consentTimestamp\": \"1525101183\" }}") + payload := strings.NewReader("{"client_id": "{yourClientId}","email": "YOUR_USER_EMAIL","password": "YOUR_USER_PASSWORD","user_metadata": {"consentGiven": "true", "consentTimestamp": "1525101183" }}") req, _ := http.NewRequest("POST", url, payload) @@ -157,12 +164,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/dbconnections/signup") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/dbconnections/signup") .header("content-type", "application/json") - .body("{\"client_id\": \"{yourClientId}\",\"email\": \"YOUR_USER_EMAIL\",\"password\": \"YOUR_USER_PASSWORD\",\"user_metadata\": {\"consentGiven\": \"true\", \"consentTimestamp\": \"1525101183\" }}") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{"client_id": "{yourClientId}","email": "YOUR_USER_EMAIL","password": "YOUR_USER_PASSWORD","user_metadata": {"consentGiven": "true", "consentTimestamp": "1525101183" }}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -180,8 +191,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json" }; NSDictionary *parameters = @{ @"client_id": @"{yourClientId}", @@ -208,8 +221,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/dbconnections/signup", @@ -219,7 +234,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{\"client_id\": \"{yourClientId}\",\"email\": \"YOUR_USER_EMAIL\",\"password\": \"YOUR_USER_PASSWORD\",\"user_metadata\": {\"consentGiven\": \"true\", \"consentTimestamp\": \"1525101183\" }}", + CURLOPT_POSTFIELDS => "{"client_id": "{yourClientId}","email": "YOUR_USER_EMAIL","password": "YOUR_USER_PASSWORD","user_metadata": {"consentGiven": "true", "consentTimestamp": "1525101183" }}", CURLOPT_HTTPHEADER => [ "content-type: application/json" ], @@ -234,12 +249,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"client_id\": \"{yourClientId}\",\"email\": \"YOUR_USER_EMAIL\",\"password\": \"YOUR_USER_PASSWORD\",\"user_metadata\": {\"consentGiven\": \"true\", \"consentTimestamp\": \"1525101183\" }}" +payload = "{"client_id": "{yourClientId}","email": "YOUR_USER_EMAIL","password": "YOUR_USER_PASSWORD","user_metadata": {"consentGiven": "true", "consentTimestamp": "1525101183" }}" headers = { 'content-type': "application/json" } @@ -248,8 +265,10 @@ conn.request("POST", "/{yourDomain}/dbconnections/signup", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -261,11 +280,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["content-type"] = 'application/json' -request.body = "{\"client_id\": \"{yourClientId}\",\"email\": \"YOUR_USER_EMAIL\",\"password\": \"YOUR_USER_PASSWORD\",\"user_metadata\": {\"consentGiven\": \"true\", \"consentTimestamp\": \"1525101183\" }}" +request.body = "{"client_id": "{yourClientId}","email": "YOUR_USER_EMAIL","password": "YOUR_USER_PASSWORD","user_metadata": {"consentGiven": "true", "consentTimestamp": "1525101183" }}" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/json"] let parameters = [ @@ -297,20 +318,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + Notez que nous définissons la valeur des métadonnées sur une chaîne avec la valeur `true` et non sur une valeur booléenne en raison de la restriction d’API qui admet les chaînes comme valeurs et pas les booléens. @@ -331,18 +341,24 @@ Définissez le paramètre de requête ** +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer YOUR_ACCESS_TOKEN", @"content-type": @"application/json" }; @@ -415,8 +437,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users/%7BUSER_ID%7D", @@ -426,7 +450,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{\"user_metadata\": {\"consentGiven\":true, \"consentTimestamp\": \"1525101183\"}}", + CURLOPT_POSTFIELDS => "{"user_metadata": {"consentGiven":true, "consentTimestamp": "1525101183"}}", CURLOPT_HTTPHEADER => [ "authorization: Bearer YOUR_ACCESS_TOKEN", "content-type: application/json" @@ -442,12 +466,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"user_metadata\": {\"consentGiven\":true, \"consentTimestamp\": \"1525101183\"}}" +payload = "{"user_metadata": {"consentGiven":true, "consentTimestamp": "1525101183"}}" headers = { 'authorization': "Bearer YOUR_ACCESS_TOKEN", @@ -459,8 +485,10 @@ conn.request("POST", "/{yourDomain}/api/v2/users/%7BUSER_ID%7D", payload, header res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -473,11 +501,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["authorization"] = 'Bearer YOUR_ACCESS_TOKEN' request["content-type"] = 'application/json' -request.body = "{\"user_metadata\": {\"consentGiven\":true, \"consentTimestamp\": \"1525101183\"}}" +request.body = "{"user_metadata": {"consentGiven":true, "consentTimestamp": "1525101183"}}" response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "authorization": "Bearer YOUR_ACCESS_TOKEN", @@ -507,20 +537,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + Notez que pour effectuer cet appel, vous devez connaître l’`user_id` unique. Vous pouvez le récupérer à partir de la demande `sub` du jeton d’ID, si vous en avez reçue une dans la réponse. Pour en savoir plus, lisez [Jetons d’ID](/docs/fr-ca/secure/tokens/id-tokens). Si vous ne disposez que de l’adresse courriel, vous pouvez récupérer l’ID en appelant un autre point de terminaison de Management API. Pour en savoir plus, lisez [Meilleures pratiques de recherche d’utilisateurs](/docs/fr-ca/manage-users/user-search/user-search-best-practices). diff --git a/main/docs/fr-ca/secure/mdl-verification/create-mdl-api.mdx b/main/docs/fr-ca/secure/mdl-verification/create-mdl-api.mdx index 3de62be97..ac75141eb 100644 --- a/main/docs/fr-ca/secure/mdl-verification/create-mdl-api.mdx +++ b/main/docs/fr-ca/secure/mdl-verification/create-mdl-api.mdx @@ -10,6 +10,7 @@ permalink: "create-mdl-api" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; @@ -42,7 +43,7 @@ Once you've been approved to join the EA, you can create the mDL Verification AP 3. Choose the application you want to use with Verification API. 4. Select the **APIs** tab. 5. Enable Verification API. -](/docs/images/ + ![Auth0 Dashboard > Applications > APIs Auth0 Dashboard > Applications > Applications](/images/fr-ca/cdy7uua7fh8z/4mzN6voEXDUXkJjGXXe50Y/e84c8be48ce78289f950c62eaa4601cc/2025-03-11_14-42-35.png) @@ -56,18 +57,24 @@ Once you've been approved to join the EA, you can create the mDL Verification AP 1. Make a `POST` call to the [Create a Resource Server](https://auth0.com/docs/api/management/v2/resource-servers/post-resource-servers) endpoint. -export const codeExample1 = ` curl --request POST \ + +```bash cURL + curl --request POST \ --url 'https://{yourDomain}/api/v2/resource-servers/post-resource-servers' \ --header 'content-type: application/json' \ --data '{"name"}' -`; -export const codeExample2 = ` var client = new RestClient("https://{yourDomain}/api/v2/resource-servers/post-resource-servers"); + +``` +```csharp C# + var client = new RestClient("https://{yourDomain}/api/v2/resource-servers/post-resource-servers"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\"name\"}", ParameterType.RequestBody); +request.AddParameter("application/json", "{"name"}", ParameterType.RequestBody); IRestResponse response = client.Execute(request); -`; -export const codeExample3 = ` package main + +``` +```go Go + package main import ( "fmt" @@ -80,7 +87,7 @@ func main() { url := "https://{yourDomain}/api/v2/resource-servers/post-resource-servers" - payload := strings.NewReader("{\"name\"}") + payload := strings.NewReader("{"name"}") req, _ := http.NewRequest("POST", url, payload) @@ -95,13 +102,17 @@ func main() { fmt.Println(string(body)) } -`; -export const codeExample4 = ` HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/resource-servers/post-resource-servers") + +``` +```java Java + HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/resource-servers/post-resource-servers") .header("content-type", "application/json") - .body("{\"name\"}") + .body("{"name"}") .asString(); -`; -export const codeExample5 = ` var axios = require("axios").default; + +``` +```javascript Node.JS + var axios = require("axios").default; var options = { method: 'POST', @@ -115,8 +126,10 @@ axios.request(options).then(function (response) { }).catch(function (error) { console.error(error); }); -`; -export const codeExample6 = ` #import + +``` +```obj-c Obj-C + #import NSDictionary *headers = @{ @"content-type": @"application/json" }; @@ -140,8 +153,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request } }]; [dataTask resume]; -`; -export const codeExample7 = ` $curl = curl_init(); + +``` +```php PHP + $curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/resource-servers/post-resource-servers", @@ -151,7 +166,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{\"name\"}", + CURLOPT_POSTFIELDS => "{"name"}", CURLOPT_HTTPHEADER => [ "content-type: application/json" ], @@ -167,12 +182,14 @@ if ($err) { } else { echo $response; } -`; -export const codeExample8 = ` import http.client + +``` +```python Python + import http.client conn = http.client.HTTPSConnection("") -payload = "{\"name\"}" +payload = "{"name"}" headers = { 'content-type': "application/json" } @@ -182,12 +199,14 @@ res = conn.getresponse() data = res.read() print(data.decode("utf-8")) -`; -export const codeExample9 = ` import http.client + +``` +```ruby Ruby + import http.client conn = http.client.HTTPSConnection("") -payload = "{\"name\"}" +payload = "{"name"}" headers = { 'content-type': "application/json" } @@ -197,8 +216,10 @@ res = conn.getresponse() data = res.read() print(data.decode("utf-8")) -`; -export const codeExample10 = ` import Foundation + +``` +```swift Swift + import Foundation let headers = ["content-type": "application/json"] @@ -220,20 +241,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: print(httpResponse) } }) -`; - - - - - - - - - - - - - + +``` + 2. Enable the permissions by following instructions for [Management API](https://auth0.com/docs/get-started/apis/add-api-permissions#use-the-management-api). diff --git a/main/docs/fr-ca/secure/multi-factor-authentication/authenticate-using-ropg-flow-with-mfa.mdx b/main/docs/fr-ca/secure/multi-factor-authentication/authenticate-using-ropg-flow-with-mfa.mdx index 31197d2ec..d4df20a78 100644 --- a/main/docs/fr-ca/secure/multi-factor-authentication/authenticate-using-ropg-flow-with-mfa.mdx +++ b/main/docs/fr-ca/secure/multi-factor-authentication/authenticate-using-ropg-flow-with-mfa.mdx @@ -10,6 +10,7 @@ permalink: "authenticate-using-ropg-flow-with-mfa" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Vous pouvez utiliser [l’API Auth0 pour l’authentification multifacteur (MFA)](/docs/fr-ca/api/authentication#multi-factor-authentication) pour compléter le flux d’authentification à l’aide du [Flux de mot de passe du propriétaire de ressource](/docs/fr-ca/get-started/authentication-and-authorization-flow/resource-owner-password-flow) (parfois appelé Autorisation de mot de passe du propriétaire des ressources ou ROPG lorsque MFA est activée. @@ -22,7 +23,9 @@ Avant de pouvoir utiliser les API MFA, vous devrez activer le type d’autorisat Lorsque vous utilisez le Flux de mot de passe du propriétaire de ressource pour l’authentification, vous appelez le point de terminaison `/oauth/token` avec le nom d’utilisateur et le mot de passe de l’utilisateur. -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=password \ @@ -31,13 +34,17 @@ export const codeExample1 = `curl --request POST \ --data 'client_id={yourClientId}' \ --data 'client_secret={yourClientSecret}' \ --data audience=https://someapi.com/api \ - --data 'scope=openid profile read:sample'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data 'scope=openid profile read:sample' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=password&username=user%40example.com&password=pwd&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&audience=https%3A%2F%2Fsomeapi.com%2Fapi&scope=openid%20profile%20read%3Asample", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -64,12 +71,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=password&username=user%40example.com&password=pwd&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&audience=https%3A%2F%2Fsomeapi.com%2Fapi&scope=openid%20profile%20read%3Asample") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -90,8 +101,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -120,8 +133,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -146,8 +161,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -160,8 +177,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -176,8 +195,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=password&username=user%40example.com&password=pwd&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&audience=https%3A%2F%2Fsomeapi.com%2Fapi&scope=openid%20profile%20read%3Asample" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -206,20 +227,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + Lorsque MFA est activé, la réponse comprend une erreur `mfa_required` et un jeton `mfa_token`. diff --git a/main/docs/fr-ca/secure/multi-factor-authentication/authenticate-using-ropg-flow-with-mfa/challenge-with-recovery-codes.mdx b/main/docs/fr-ca/secure/multi-factor-authentication/authenticate-using-ropg-flow-with-mfa/challenge-with-recovery-codes.mdx index 643efd8b2..f2d576c66 100644 --- a/main/docs/fr-ca/secure/multi-factor-authentication/authenticate-using-ropg-flow-with-mfa/challenge-with-recovery-codes.mdx +++ b/main/docs/fr-ca/secure/multi-factor-authentication/authenticate-using-ropg-flow-with-mfa/challenge-with-recovery-codes.mdx @@ -10,6 +10,7 @@ permalink: "challenge-with-recovery-codes" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Lorsque les [codes de récupération sont activés](/docs/fr-ca/secure/multi-factor-authentication/configure-recovery-codes-for-mfa) pour votre locataire, Auth0 les génère automatiquement lorsqu’un utilisateur s’inscrit avec l’authentification multifacteur (MFA). L’utilisateur doit enregistrer le code de récupération. Ce code pourra être utilisé ultérieurement si l’utilisateur perd l’accès à l’appareil ou au compte utilisé pour la MFA. @@ -46,7 +47,9 @@ Vous pouvez autoriser les utilisateurs à s’authentifier avec un code de récu
    -export const codeExample1 = ` curl --request POST \ + +```bash cURL + curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=http://auth0.com/oauth/grant-type/mfa-recovery-code \ @@ -54,14 +57,18 @@ export const codeExample1 = ` curl --request POST \ --data 'client_secret={yourClientSecret}' \ --data 'mfa_token={mfaToken}' \ --data 'recovery_code={recoveryCode}' -`; -export const codeExample2 = ` var client = new RestClient("https://{yourDomain}/oauth/token"); + +``` +```csharp C# + var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=http%3A%2F%2Fauth0.com%2Foauth%2Fgrant-type%2Fmfa-recovery-code&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&mfa_token=%7BmfaToken%7D&recovery_code=%7BrecoveryCode%7D", ParameterType.RequestBody); IRestResponse response = client.Execute(request); -`; -export const codeExample3 = ` package main + +``` +```go Go + package main import ( "fmt" @@ -89,13 +96,17 @@ func main() { fmt.Println(string(body)) } -`; -export const codeExample4 = ` HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") + +``` +```java Java + HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=http%3A%2F%2Fauth0.com%2Foauth%2Fgrant-type%2Fmfa-recovery-code&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&mfa_token=%7BmfaToken%7D&recovery_code=%7BrecoveryCode%7D") .asString(); -`; -export const codeExample5 = ` var axios = require("axios").default; + +``` +```javascript Node.JS + var axios = require("axios").default; var options = { method: 'POST', @@ -115,8 +126,10 @@ console.log(response.data); }).catch(function (error) { console.error(error); }); -`; -export const codeExample6 = ` #import + +``` +```obj-c Obj-C + #import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -144,8 +157,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request } }]; [dataTask resume]; -`; -export const codeExample7 = ` $curl = curl_init(); + +``` +```php PHP + $curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -171,8 +186,10 @@ echo "cURL Error #:" . $err; } else { echo $response; } -`; -export const codeExample8 = ` import http.client + +``` +```python Python + import http.client conn = http.client.HTTPSConnection("") @@ -186,8 +203,10 @@ res = conn.getresponse() data = res.read() print(data.decode("utf-8")) -`; -export const codeExample9 = ` require 'uri' + +``` +```ruby Ruby + require 'uri' require 'net/http' require 'openssl' @@ -203,8 +222,10 @@ request.body = "grant_type=http%3A%2F%2Fauth0.com%2Foauth%2Fgrant-type%2Fmfa-rec response = http.request(request) puts response.read_body -`; -export const codeExample10 = ` import Foundation + +``` +```swift Swift + import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -232,20 +253,9 @@ if (error != nil) { }) dataTask.resume() -`; - - - - - - - - - - - - - + +``` + 3. Invitez l’utilisateur à recueillir le code de récupération. Si l’appel réussit, vous obtiendrez les jetons d’authentification et un nouveau code de récupération : diff --git a/main/docs/fr-ca/secure/multi-factor-authentication/authenticate-using-ropg-flow-with-mfa/enroll-and-challenge-email-authenticators.mdx b/main/docs/fr-ca/secure/multi-factor-authentication/authenticate-using-ropg-flow-with-mfa/enroll-and-challenge-email-authenticators.mdx index 923339cfc..e239636e2 100644 --- a/main/docs/fr-ca/secure/multi-factor-authentication/authenticate-using-ropg-flow-with-mfa/enroll-and-challenge-email-authenticators.mdx +++ b/main/docs/fr-ca/secure/multi-factor-authentication/authenticate-using-ropg-flow-with-mfa/enroll-and-challenge-email-authenticators.mdx @@ -10,6 +10,7 @@ permalink: "enroll-and-challenge-email-authenticators" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Auth0 offre un flux intégré d’enregistrement et d’authentification MFA en utilisant la [connexion universelle](/docs/fr-ca/authenticate/login/auth0-universal-login). Cependant, si vous souhaitez créer votre propre interface utilisateur, vous pouvez utiliser [l’API MFA](/docs/fr-ca/secure/multi-factor-authentication/multi-factor-authentication-developer-resources/mfa-api) pour ce faire. @@ -67,18 +68,24 @@ Utilisez les paramètres suivants : -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/mfa/associate' \ --header 'authorization: Bearer MFA_TOKEN' \ --header 'content-type: application/json' \ - --data '{ "authenticator_types": ["oob"], "oob_channels": ["email"], "email" : "email@address.com" }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/mfa/associate"); + --data '{ "authenticator_types": ["oob"], "oob_channels": ["email"], "email" : "email@address.com" }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/mfa/associate"); var request = new RestRequest(Method.POST); request.AddHeader("authorization", "Bearer MFA_TOKEN"); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{ \"authenticator_types\": [\"oob\"], \"oob_channels\": [\"email\"], \"email\" : \"email@address.com\" }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "authenticator_types": ["oob"], "oob_channels": ["email"], "email" : "email@address.com" }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -91,7 +98,7 @@ func main() { url := "https://{yourDomain}/mfa/associate" - payload := strings.NewReader("{ \"authenticator_types\": [\"oob\"], \"oob_channels\": [\"email\"], \"email\" : \"email@address.com\" }") + payload := strings.NewReader("{ "authenticator_types": ["oob"], "oob_channels": ["email"], "email" : "email@address.com" }") req, _ := http.NewRequest("POST", url, payload) @@ -106,13 +113,17 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/mfa/associate") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/mfa/associate") .header("authorization", "Bearer MFA_TOKEN") .header("content-type", "application/json") - .body("{ \"authenticator_types\": [\"oob\"], \"oob_channels\": [\"email\"], \"email\" : \"email@address.com\" }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "authenticator_types": ["oob"], "oob_channels": ["email"], "email" : "email@address.com" }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -129,8 +140,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MFA_TOKEN", @"content-type": @"application/json" }; @@ -157,8 +170,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/mfa/associate", @@ -168,7 +183,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{ \"authenticator_types\": [\"oob\"], \"oob_channels\": [\"email\"], \"email\" : \"email@address.com\" }", + CURLOPT_POSTFIELDS => "{ "authenticator_types": ["oob"], "oob_channels": ["email"], "email" : "email@address.com" }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MFA_TOKEN", "content-type: application/json" @@ -184,12 +199,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"authenticator_types\": [\"oob\"], \"oob_channels\": [\"email\"], \"email\" : \"email@address.com\" }" +payload = "{ "authenticator_types": ["oob"], "oob_channels": ["email"], "email" : "email@address.com" }" headers = { 'authorization': "Bearer MFA_TOKEN", @@ -201,8 +218,10 @@ conn.request("POST", "/{yourDomain}/mfa/associate", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -215,11 +234,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["authorization"] = 'Bearer MFA_TOKEN' request["content-type"] = 'application/json' -request.body = "{ \"authenticator_types\": [\"oob\"], \"oob_channels\": [\"email\"], \"email\" : \"email@address.com\" }" +request.body = "{ "authenticator_types": ["oob"], "oob_channels": ["email"], "email" : "email@address.com" }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "authorization": "Bearer MFA_TOKEN", @@ -250,20 +271,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + Si l’étape réussie, vous recevez une réponse comme celle-ci : @@ -287,19 +297,25 @@ L’utilisateur recevra un courriel contenant le code à six chiffres qu’il de Pour compléter l’inscription, réalisez une requête `POST` au [**`/oath/jeton`**](https://auth0.com/docs/api/authentication#get-token) du point de terminaison. Incluez le `oob_code` retourné dans la réponse précédente et le `binding_code` avec la valeur inscrite dans le courriel. -export const codeExample11 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --data grant_type=http://auth0.com/oauth/grant-type/mfa-oob \ --data 'mfa_token={mfaToken}' \ --data 'oob_code={oobCode}' \ --data 'binding_code={userEmailOtpCode}' \ --data 'client_id={yourClientId}' \ - --data 'client_secret={yourClientSecret}'`; -export const codeExample12 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data 'client_secret={yourClientSecret}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddParameter("undefined", "grant_type=http%3A%2F%2Fauth0.com%2Foauth%2Fgrant-type%2Fmfa-oob&mfa_token=%7BmfaToken%7D&oob_code=%7BoobCode%7D&binding_code=%7BuserEmailOtpCode%7D&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample13 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -324,11 +340,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample14 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .body("grant_type=http%3A%2F%2Fauth0.com%2Foauth%2Fgrant-type%2Fmfa-oob&mfa_token=%7BmfaToken%7D&oob_code=%7BoobCode%7D&binding_code=%7BuserEmailOtpCode%7D&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D") - .asString();`; -export const codeExample15 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -347,8 +367,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample16 = `#import +}); +``` +```obj-c Obj-C +#import NSMutableData *postData = [[NSMutableData alloc] initWithData:[@"grant_type=http://auth0.com/oauth/grant-type/mfa-oob" dataUsingEncoding:NSUTF8StringEncoding]]; [postData appendData:[@"&mfa_token={mfaToken}" dataUsingEncoding:NSUTF8StringEncoding]]; @@ -373,8 +395,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -396,8 +420,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -408,8 +434,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -423,8 +451,10 @@ request = Net::HTTP::Post.new(url) request.body = "grant_type=http%3A%2F%2Fauth0.com%2Foauth%2Fgrant-type%2Fmfa-oob&mfa_token=%7BmfaToken%7D&oob_code=%7BoobCode%7D&binding_code=%7BuserEmailOtpCode%7D&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D" response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let postData = NSMutableData(data: "grant_type=http://auth0.com/oauth/grant-type/mfa-oob".data(using: String.Encoding.utf8)!) postData.append("&mfa_token={mfaToken}".data(using: String.Encoding.utf8)!) @@ -449,20 +479,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + Si l’appel ne réussi pas, vous recevrez une réponse dans le format suivant, contenant le jeton d’accès : @@ -492,16 +511,22 @@ Obtenez un jeton MFA en suivant les étapes décrites dans [Authentification ave Pour effectuer le défi-réponse avec l’utilisateur, vous aurez besoin de l’`authenticator_id` pour le facteur que vous désirez utiliser. Vous pouvez énumérer toutes les authentifications à l’aide du point de terminaison des facteurs d’authentification MFA : -export const codeExample21 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/mfa/authenticators' \ --header 'authorization: Bearer MFA_TOKEN' \ - --header 'content-type: application/json'`; -export const codeExample22 = `var client = new RestClient("https://{yourDomain}/mfa/authenticators"); + --header 'content-type: application/json' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/mfa/authenticators"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer MFA_TOKEN"); request.AddHeader("content-type", "application/json"); -IRestResponse response = client.Execute(request);`; -export const codeExample23 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -526,12 +551,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample24 = `HttpResponse response = Unirest.get("https://{yourDomain}/mfa/authenticators") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/mfa/authenticators") .header("authorization", "Bearer MFA_TOKEN") .header("content-type", "application/json") - .asString();`; -export const codeExample25 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -543,8 +572,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample26 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MFA_TOKEN", @"content-type": @"application/json" }; @@ -565,8 +596,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample27 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/mfa/authenticators", @@ -591,8 +624,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample28 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -606,8 +641,10 @@ conn.request("GET", "/{yourDomain}/mfa/authenticators", headers=headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample29 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -622,8 +659,10 @@ request["authorization"] = 'Bearer MFA_TOKEN' request["content-type"] = 'application/json' response = http.request(request) -puts response.read_body`; -export const codeExample30 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "authorization": "Bearer MFA_TOKEN", @@ -646,33 +685,28 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ### Défi-réponse avec mot de passe à usage unique Pour déclencher un défi-réponse avec courriel, `POST` au point de terminaison du défi-réponse MFA à l’aide de l’`authenticator_id` correspondante et du `mfa_token`. -export const codeExample31 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/mfa/challenge' \ - --data '{ "client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "challenge_type": "oob", "authenticator_id": "email|dev_NU1Ofuw3Cw0XCt5x", "mfa_token": "{mfaToken}" }'`; -export const codeExample32 = `var client = new RestClient("https://{yourDomain}/mfa/challenge"); + --data '{ "client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "challenge_type": "oob", "authenticator_id": "email|dev_NU1Ofuw3Cw0XCt5x", "mfa_token": "{mfaToken}" }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/mfa/challenge"); var request = new RestRequest(Method.POST); -request.AddParameter("undefined", "{ \"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"challenge_type\": \"oob\", \"authenticator_id\": \"email|dev_NU1Ofuw3Cw0XCt5x\", \"mfa_token\": \"{mfaToken}\" }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample33 = `package main +request.AddParameter("undefined", "{ "client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "challenge_type": "oob", "authenticator_id": "email|dev_NU1Ofuw3Cw0XCt5x", "mfa_token": "{mfaToken}" }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -685,7 +719,7 @@ func main() { url := "https://{yourDomain}/mfa/challenge" - payload := strings.NewReader("{ \"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"challenge_type\": \"oob\", \"authenticator_id\": \"email|dev_NU1Ofuw3Cw0XCt5x\", \"mfa_token\": \"{mfaToken}\" }") + payload := strings.NewReader("{ "client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "challenge_type": "oob", "authenticator_id": "email|dev_NU1Ofuw3Cw0XCt5x", "mfa_token": "{mfaToken}" }") req, _ := http.NewRequest("POST", url, payload) @@ -697,11 +731,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample34 = `HttpResponse response = Unirest.post("https://{yourDomain}/mfa/challenge") - .body("{ \"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"challenge_type\": \"oob\", \"authenticator_id\": \"email|dev_NU1Ofuw3Cw0XCt5x\", \"mfa_token\": \"{mfaToken}\" }") - .asString();`; -export const codeExample35 = `var axios = require("axios").default; +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/mfa/challenge") + .body("{ "client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "challenge_type": "oob", "authenticator_id": "email|dev_NU1Ofuw3Cw0XCt5x", "mfa_token": "{mfaToken}" }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -719,8 +757,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample36 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *parameters = @{ @"client_id": @"{yourClientId}", @"client_secret": @"{yourClientSecret}", @"challenge_type": @"oob", @@ -745,8 +785,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample37 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/mfa/challenge", @@ -756,7 +798,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{ \"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"challenge_type\": \"oob\", \"authenticator_id\": \"email|dev_NU1Ofuw3Cw0XCt5x\", \"mfa_token\": \"{mfaToken}\" }", + CURLOPT_POSTFIELDS => "{ "client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "challenge_type": "oob", "authenticator_id": "email|dev_NU1Ofuw3Cw0XCt5x", "mfa_token": "{mfaToken}" }", ]); $response = curl_exec($curl); @@ -768,20 +810,24 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample38 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"challenge_type\": \"oob\", \"authenticator_id\": \"email|dev_NU1Ofuw3Cw0XCt5x\", \"mfa_token\": \"{mfaToken}\" }" +payload = "{ "client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "challenge_type": "oob", "authenticator_id": "email|dev_NU1Ofuw3Cw0XCt5x", "mfa_token": "{mfaToken}" }" conn.request("POST", "/{yourDomain}/mfa/challenge", payload) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample39 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -792,11 +838,13 @@ http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) -request.body = "{ \"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"challenge_type\": \"oob\", \"authenticator_id\": \"email|dev_NU1Ofuw3Cw0XCt5x\", \"mfa_token\": \"{mfaToken}\" }" +request.body = "{ "client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "challenge_type": "oob", "authenticator_id": "email|dev_NU1Ofuw3Cw0XCt5x", "mfa_token": "{mfaToken}" }" response = http.request(request) -puts response.read_body`; -export const codeExample40 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let parameters = [ "client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", @@ -823,20 +871,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ### Compléter l’authentification à l’aide du code reçu @@ -852,7 +889,9 @@ Si l’opération réussie, vous recevrez la réponse suivante : Votre application devrait inviter l’utilisateur à saisir un code et l’envoyer dans le cadre de la requête dans le paramètre `binding_code` dans l’appel suivant au point de terminaison du `oauth/token` : -export const codeExample41 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=http://auth0.com/oauth/grant-type/mfa-oob \ @@ -860,13 +899,17 @@ export const codeExample41 = `curl --request POST \ --data 'client_secret={yourClientSecret}' \ --data 'mfa_token={mfaToken}' \ --data 'oob_code={oobCode}' \ - --data 'binding_code={userEmailOtpCode}'`; -export const codeExample42 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data 'binding_code={userEmailOtpCode}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=http%3A%2F%2Fauth0.com%2Foauth%2Fgrant-type%2Fmfa-oob&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&mfa_token=%7BmfaToken%7D&oob_code=%7BoobCode%7D&binding_code=%7BuserEmailOtpCode%7D", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample43 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -893,12 +936,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample44 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=http%3A%2F%2Fauth0.com%2Foauth%2Fgrant-type%2Fmfa-oob&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&mfa_token=%7BmfaToken%7D&oob_code=%7BoobCode%7D&binding_code=%7BuserEmailOtpCode%7D") - .asString();`; -export const codeExample45 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -918,8 +965,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample46 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -947,8 +996,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample47 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -973,8 +1024,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample48 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -987,8 +1040,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample49 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -1003,8 +1058,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=http%3A%2F%2Fauth0.com%2Foauth%2Fgrant-type%2Fmfa-oob&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&mfa_token=%7BmfaToken%7D&oob_code=%7BoobCode%7D&binding_code=%7BuserEmailOtpCode%7D" response = http.request(request) -puts response.read_body`; -export const codeExample50 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -1032,20 +1089,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + Si l’appel réussi, vous recevrez une réponse dans le format ci-dessous, contenant le jeton d’accès : diff --git a/main/docs/fr-ca/secure/multi-factor-authentication/authenticate-using-ropg-flow-with-mfa/enroll-and-challenge-otp-authenticators.mdx b/main/docs/fr-ca/secure/multi-factor-authentication/authenticate-using-ropg-flow-with-mfa/enroll-and-challenge-otp-authenticators.mdx index 7d534ee63..2d681255f 100644 --- a/main/docs/fr-ca/secure/multi-factor-authentication/authenticate-using-ropg-flow-with-mfa/enroll-and-challenge-otp-authenticators.mdx +++ b/main/docs/fr-ca/secure/multi-factor-authentication/authenticate-using-ropg-flow-with-mfa/enroll-and-challenge-otp-authenticators.mdx @@ -10,6 +10,7 @@ permalink: "enroll-and-challenge-otp-authenticators" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Auth0 offre un flux intégré d’enregistrement et d’authentification MFA en utilisant la [connexion universelle](/docs/fr-ca/authenticate/login/auth0-universal-login). Cependant, si vous souhaitez créer votre propre interface utilisateur, vous pouvez utiliser [l’API MFA](/docs/fr-ca/secure/multi-factor-authentication/multi-factor-authentication-developer-resources/mfa-api) pour ce faire. @@ -35,18 +36,24 @@ Faites une demande `POST (PUBLIER)` au point de terminaison d’association MFA Pour vous inscrire avec OTP, définissez le paramètre `authenticator_types` sur `[otp]`. -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/mfa/associate' \ --header 'authorization: Bearer MFA_TOKEN' \ --header 'content-type: application/json' \ - --data '{ "authenticator_types": ["otp"] }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/mfa/associate"); + --data '{ "authenticator_types": ["otp"] }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/mfa/associate"); var request = new RestRequest(Method.POST); request.AddHeader("authorization", "Bearer MFA_TOKEN"); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{ \"authenticator_types\": [\"otp\"] }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "authenticator_types": ["otp"] }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -59,7 +66,7 @@ func main() { url := "https://{yourDomain}/mfa/associate" - payload := strings.NewReader("{ \"authenticator_types\": [\"otp\"] }") + payload := strings.NewReader("{ "authenticator_types": ["otp"] }") req, _ := http.NewRequest("POST", url, payload) @@ -74,13 +81,17 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/mfa/associate") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/mfa/associate") .header("authorization", "Bearer MFA_TOKEN") .header("content-type", "application/json") - .body("{ \"authenticator_types\": [\"otp\"] }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "authenticator_types": ["otp"] }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -93,8 +104,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MFA_TOKEN", @"content-type": @"application/json" }; @@ -119,8 +132,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/mfa/associate", @@ -130,7 +145,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{ \"authenticator_types\": [\"otp\"] }", + CURLOPT_POSTFIELDS => "{ "authenticator_types": ["otp"] }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MFA_TOKEN", "content-type: application/json" @@ -147,12 +162,14 @@ if ($err) { } else { echo $response; } -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"authenticator_types\": [\"otp\"] }" +payload = "{ "authenticator_types": ["otp"] }" headers = { 'authorization': "Bearer MFA_TOKEN", @@ -164,8 +181,10 @@ conn.request("POST", "/{yourDomain}/mfa/associate", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -178,11 +197,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["authorization"] = 'Bearer MFA_TOKEN' request["content-type"] = 'application/json' -request.body = "{ \"authenticator_types\": [\"otp\"] }" +request.body = "{ "authenticator_types": ["otp"] }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "authorization": "Bearer MFA_TOKEN", @@ -209,20 +230,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + Si l’étape réussie, vous recevez une réponse comme celle-ci : @@ -246,20 +256,26 @@ Pour confirmer l’inscription, l’utilisateur final devra entrer le code secre Après que l’utilisateur a entré le code secret, l’application OTP affichera un code à 6 chiffres que l’utilisateur devra entrer dans votre application. L’application doit ensuite effectuer une requête `POST` vers le point de terminaison du jeton OAuth, en incluant cette valeur `otp`. -export const codeExample11 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=http://auth0.com/oauth/grant-type/mfa-otp \ --data 'client_id={yourClientId}' \ --data 'mfa_token={mfaToken}' \ --data 'client_secret={yourClientSecret}' \ - --data 'otp={userOtpCode}'`; -export const codeExample12 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data 'otp={userOtpCode}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=http%3A%2F%2Fauth0.com%2Foauth%2Fgrant-type%2Fmfa-otp&client_id={yourClientId}&mfa_token=%7BmfaToken%7D&client_secret=%7ByourClientSecret%7D&otp=%7BuserOtpCode%7D", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample13 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -286,12 +302,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample14 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=http%3A%2F%2Fauth0.com%2Foauth%2Fgrant-type%2Fmfa-otp&client_id={yourClientId}&mfa_token=%7BmfaToken%7D&client_secret=%7ByourClientSecret%7D&otp=%7BuserOtpCode%7D") - .asString();`; -export const codeExample15 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -310,8 +330,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample16 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -338,8 +360,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -364,8 +388,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -378,8 +404,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -394,8 +422,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=http%3A%2F%2Fauth0.com%2Foauth%2Fgrant-type%2Fmfa-otp&client_id={yourClientId}&mfa_token=%7BmfaToken%7D&client_secret=%7ByourClientSecret%7D&otp=%7BuserOtpCode%7D" response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -422,20 +452,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + Si l’appel ne réussi pas, vous recevrez une réponse dans le format suivant, contenant le jeton d’accès : @@ -463,16 +482,22 @@ Obtenez un jeton MFA en suivant les étapes décrites dans [Autorisation par mot Vous pouvez énumérer toutes les authentifications à l’aide du point de terminaison des facteurs d’authentification MFA : -export const codeExample21 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/mfa/authenticators' \ --header 'authorization: Bearer MFA_TOKEN' \ - --header 'content-type: application/json'`; -export const codeExample22 = `var client = new RestClient("https://{yourDomain}/mfa/authenticators"); + --header 'content-type: application/json' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/mfa/authenticators"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer MFA_TOKEN"); request.AddHeader("content-type", "application/json"); -IRestResponse response = client.Execute(request);`; -export const codeExample23 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -497,12 +522,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample24 = `HttpResponse response = Unirest.get("https://{yourDomain}/mfa/authenticators") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/mfa/authenticators") .header("authorization", "Bearer MFA_TOKEN") .header("content-type", "application/json") - .asString();`; -export const codeExample25 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -514,8 +543,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample26 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MFA_TOKEN", @"content-type": @"application/json" }; @@ -536,8 +567,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample27 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/mfa/authenticators", @@ -562,8 +595,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample28 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -577,8 +612,10 @@ conn.request("GET", "/{yourDomain}/mfa/authenticators", headers=headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample29 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -593,8 +630,10 @@ request["authorization"] = 'Bearer MFA_TOKEN' request["content-type"] = 'application/json' response = http.request(request) -puts response.read_body`; -export const codeExample30 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "authorization": "Bearer MFA_TOKEN", @@ -617,20 +656,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + Vous obtiendrez une liste de facteurs d’authentification avec le format suivant : @@ -655,20 +683,26 @@ L’utilisateur obtiendra un mot de passe à usage unique, que vous récupérere Vous pouvez vérifier le code et obtenir des jetons d’authentification en utilisant le point de terminaison du jeton Oauth0, tout en précisant le mot de passe à usage unique dans le paramètre `otp`. -export const codeExample31 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=http://auth0.com/oauth/grant-type/mfa-otp \ --data 'client_id={yourClientId}' \ --data 'client_secret={yourClientSecret}' \ --data 'mfa_token={mfaToken}' \ - --data 'otp={userOtpCode}'`; -export const codeExample32 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data 'otp={userOtpCode}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=http%3A%2F%2Fauth0.com%2Foauth%2Fgrant-type%2Fmfa-otp&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&mfa_token=%7BmfaToken%7D&otp=%7BuserOtpCode%7D", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample33 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -695,12 +729,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample34 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=http%3A%2F%2Fauth0.com%2Foauth%2Fgrant-type%2Fmfa-otp&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&mfa_token=%7BmfaToken%7D&otp=%7BuserOtpCode%7D") - .asString();`; -export const codeExample35 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -719,8 +757,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample36 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -747,8 +787,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample37 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -773,8 +815,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample38 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -787,8 +831,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample39 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -803,8 +849,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=http%3A%2F%2Fauth0.com%2Foauth%2Fgrant-type%2Fmfa-otp&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&mfa_token=%7BmfaToken%7D&otp=%7BuserOtpCode%7D" response = http.request(request) -puts response.read_body`; -export const codeExample40 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -831,20 +879,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + Si l’appel réussi, vous recevrez une réponse dans le format ci-dessous, contenant le jeton d’accès : diff --git a/main/docs/fr-ca/secure/multi-factor-authentication/authenticate-using-ropg-flow-with-mfa/enroll-and-challenge-push-authenticators.mdx b/main/docs/fr-ca/secure/multi-factor-authentication/authenticate-using-ropg-flow-with-mfa/enroll-and-challenge-push-authenticators.mdx index e10935291..d7808ee01 100644 --- a/main/docs/fr-ca/secure/multi-factor-authentication/authenticate-using-ropg-flow-with-mfa/enroll-and-challenge-push-authenticators.mdx +++ b/main/docs/fr-ca/secure/multi-factor-authentication/authenticate-using-ropg-flow-with-mfa/enroll-and-challenge-push-authenticators.mdx @@ -10,6 +10,7 @@ permalink: "enroll-and-challenge-push-authenticators" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Auth0 offre un flux intégré d’enregistrement et d’authentification MFA en utilisant la [connexion universelle](/docs/fr-ca/authenticate/login/auth0-universal-login). Cependant, si vous souhaitez créer votre propre interface utilisateur, vous pouvez utiliser [l’API MFA](/docs/fr-ca/secure/multi-factor-authentication/multi-factor-authentication-developer-resources/mfa-api) pour ce faire. @@ -37,18 +38,24 @@ Faites une demande `POST (PUBLIER)` au point de terminaison d’association MFA Pour inscrire avec Push, définissez le paramètre `authenticator_types` sur `[oob]` et le paramètre `oob_channels` sur `[auth0]`. -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/mfa/associate' \ --header 'authorization: Bearer MFA_TOKEN' \ --header 'content-type: application/json' \ - --data '{ "authenticator_types": ["oob"], "oob_channels": ["auth0"] }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/mfa/associate"); + --data '{ "authenticator_types": ["oob"], "oob_channels": ["auth0"] }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/mfa/associate"); var request = new RestRequest(Method.POST); request.AddHeader("authorization", "Bearer MFA_TOKEN"); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{ \"authenticator_types\": [\"oob\"], \"oob_channels\": [\"auth0\"] }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "authenticator_types": ["oob"], "oob_channels": ["auth0"] }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -61,7 +68,7 @@ func main() { url := "https://{yourDomain}/mfa/associate" - payload := strings.NewReader("{ \"authenticator_types\": [\"oob\"], \"oob_channels\": [\"auth0\"] }") + payload := strings.NewReader("{ "authenticator_types": ["oob"], "oob_channels": ["auth0"] }") req, _ := http.NewRequest("POST", url, payload) @@ -76,13 +83,17 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/mfa/associate") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/mfa/associate") .header("authorization", "Bearer MFA_TOKEN") .header("content-type", "application/json") - .body("{ \"authenticator_types\": [\"oob\"], \"oob_channels\": [\"auth0\"] }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "authenticator_types": ["oob"], "oob_channels": ["auth0"] }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -95,8 +106,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MFA_TOKEN", @"content-type": @"application/json" }; @@ -122,8 +135,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/mfa/associate", @@ -133,7 +148,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{ \"authenticator_types\": [\"oob\"], \"oob_channels\": [\"auth0\"] }", + CURLOPT_POSTFIELDS => "{ "authenticator_types": ["oob"], "oob_channels": ["auth0"] }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MFA_TOKEN", "content-type: application/json" @@ -149,12 +164,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"authenticator_types\": [\"oob\"], \"oob_channels\": [\"auth0\"] }" +payload = "{ "authenticator_types": ["oob"], "oob_channels": ["auth0"] }" headers = { 'authorization': "Bearer MFA_TOKEN", @@ -166,8 +183,10 @@ conn.request("POST", "/{yourDomain}/mfa/associate", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -180,11 +199,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["authorization"] = 'Bearer MFA_TOKEN' request["content-type"] = 'application/json' -request.body = "{ \"authenticator_types\": [\"oob\"], \"oob_channels\": [\"auth0\"] }" +request.body = "{ "authenticator_types": ["oob"], "oob_channels": ["auth0"] }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "authorization": "Bearer MFA_TOKEN", @@ -214,20 +235,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + Si l’étape réussie, vous recevez une réponse comme celle-ci : @@ -253,7 +263,9 @@ Pour confirmer l’inscription, l’utilisateur final devra balayer un code QR a Ensuite, l’application Guardian application informera Auth0 que l’utilisateur a bien été inscrit. Pour savoir si cela s'est produit, interrogez le point de terminaison des jetons Auth0 avec le code `oob_code` renvoyé par l’appel au point de terminaison MFA Associate. -export const codeExample11 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'authorization: Bearer {mfaToken}' \ --header 'content-type: application/x-www-form-urlencoded' \ @@ -261,14 +273,18 @@ export const codeExample11 = `curl --request POST \ --data 'client_id={yourClientId}' \ --data 'client_secret={yourClientSecret}' \ --data 'mfa_token={mfaToken}' \ - --data 'oob_code={oobCode}'`; -export const codeExample12 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data 'oob_code={oobCode}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("authorization", "Bearer {mfaToken}"); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=http%3A%2F%2Fauth0.com%2Foauth%2Fgrant-type%2Fmfa-oob&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&mfa_token=%7BmfaToken%7D&oob_code=%7BoobCode%7D", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample13 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -296,13 +312,17 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample14 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("authorization", "Bearer {mfaToken}") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=http%3A%2F%2Fauth0.com%2Foauth%2Fgrant-type%2Fmfa-oob&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&mfa_token=%7BmfaToken%7D&oob_code=%7BoobCode%7D") - .asString();`; -export const codeExample15 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -324,8 +344,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample16 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer {mfaToken}", @"content-type": @"application/x-www-form-urlencoded" }; @@ -353,8 +375,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -380,8 +404,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -397,8 +423,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -414,8 +442,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=http%3A%2F%2Fauth0.com%2Foauth%2Fgrant-type%2Fmfa-oob&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&mfa_token=%7BmfaToken%7D&oob_code=%7BoobCode%7D" response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "authorization": "Bearer {mfaToken}", @@ -445,20 +475,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + Si l’utilisateur n’a pas balayé le code, une réponse `authorization_pending` sera renvoyée, indiquant que vous devez appeler de nouveau `oauth_token` dans quelques secondes : @@ -495,16 +514,22 @@ Obtenez un jeton MFA en suivant les étapes décrites dans [Authentification ave Pour effectuer le défi-réponse avec l’utilisateur, vous aurez besoin de l’`authenticator_id` pour le facteur que vous désirez utiliser. Vous pouvez énumérer toutes les authentifications à l’aide du point de terminaison des facteurs d’authentification multifacteur : -export const codeExample21 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/mfa/authenticators' \ --header 'authorization: Bearer MFA_TOKEN' \ - --header 'content-type: application/json'`; -export const codeExample22 = `var client = new RestClient("https://{yourDomain}/mfa/authenticators"); + --header 'content-type: application/json' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/mfa/authenticators"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer MFA_TOKEN"); request.AddHeader("content-type", "application/json"); -IRestResponse response = client.Execute(request);`; -export const codeExample23 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -529,12 +554,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample24 = `HttpResponse response = Unirest.get("https://{yourDomain}/mfa/authenticators") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/mfa/authenticators") .header("authorization", "Bearer MFA_TOKEN") .header("content-type", "application/json") - .asString();`; -export const codeExample25 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -546,8 +575,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample26 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MFA_TOKEN", @"content-type": @"application/json" }; @@ -568,8 +599,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample27 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/mfa/authenticators", @@ -594,8 +627,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample28 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -609,8 +644,10 @@ conn.request("GET", "/{yourDomain}/mfa/authenticators", headers=headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample29 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -625,8 +662,10 @@ request["authorization"] = 'Bearer MFA_TOKEN' request["content-type"] = 'application/json' response = http.request(request) -puts response.read_body`; -export const codeExample30 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "authorization": "Bearer MFA_TOKEN", @@ -649,20 +688,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + Vous obtiendrez une liste de facteurs d’authentification avec le format suivant : @@ -694,14 +722,20 @@ Lorsque les utilisateurs s’inscrivent avec Push, ils sont également inscrits Pour déclencher un défi-réponse avec courriel, `POST` au point de terminaison du défi-réponse d’AMF à l’aide de l’ `authenticator_id` correspondante et du `mfa_token`. -export const codeExample31 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/mfa/challenge' \ - --data '{ "client_id": "{yourClientId}", "client_secret": "{yourClientSecret", "challenge_type": "oob", "authenticator_id": "push|dev_ZUla9SQ6tAIHSz6y", "mfa_token": "{mfaToken}" }'`; -export const codeExample32 = `var client = new RestClient("https://{yourDomain}/mfa/challenge"); + --data '{ "client_id": "{yourClientId}", "client_secret": "{yourClientSecret", "challenge_type": "oob", "authenticator_id": "push|dev_ZUla9SQ6tAIHSz6y", "mfa_token": "{mfaToken}" }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/mfa/challenge"); var request = new RestRequest(Method.POST); -request.AddParameter("undefined", "{ \"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret\", \"challenge_type\": \"oob\", \"authenticator_id\": \"push|dev_ZUla9SQ6tAIHSz6y\", \"mfa_token\": \"{mfaToken}\" }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample33 = `package main +request.AddParameter("undefined", "{ "client_id": "{yourClientId}", "client_secret": "{yourClientSecret", "challenge_type": "oob", "authenticator_id": "push|dev_ZUla9SQ6tAIHSz6y", "mfa_token": "{mfaToken}" }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -714,7 +748,7 @@ func main() { url := "https://{yourDomain}/mfa/challenge" - payload := strings.NewReader("{ \"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret\", \"challenge_type\": \"oob\", \"authenticator_id\": \"push|dev_ZUla9SQ6tAIHSz6y\", \"mfa_token\": \"{mfaToken}\" }") + payload := strings.NewReader("{ "client_id": "{yourClientId}", "client_secret": "{yourClientSecret", "challenge_type": "oob", "authenticator_id": "push|dev_ZUla9SQ6tAIHSz6y", "mfa_token": "{mfaToken}" }") req, _ := http.NewRequest("POST", url, payload) @@ -726,11 +760,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample34 = `HttpResponse response = Unirest.post("https://{yourDomain}/mfa/challenge") - .body("{ \"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret\", \"challenge_type\": \"oob\", \"authenticator_id\": \"push|dev_ZUla9SQ6tAIHSz6y\", \"mfa_token\": \"{mfaToken}\" }") - .asString();`; -export const codeExample35 = `var axios = require("axios").default; +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/mfa/challenge") + .body("{ "client_id": "{yourClientId}", "client_secret": "{yourClientSecret", "challenge_type": "oob", "authenticator_id": "push|dev_ZUla9SQ6tAIHSz6y", "mfa_token": "{mfaToken}" }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -748,8 +786,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample36 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *parameters = @{ @"client_id": @"{yourClientId}", @"client_secret": @"{yourClientSecret", @"challenge_type": @"oob", @@ -774,8 +814,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample37 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/mfa/challenge", @@ -785,7 +827,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{ \"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret\", \"challenge_type\": \"oob\", \"authenticator_id\": \"push|dev_ZUla9SQ6tAIHSz6y\", \"mfa_token\": \"{mfaToken}\" }", + CURLOPT_POSTFIELDS => "{ "client_id": "{yourClientId}", "client_secret": "{yourClientSecret", "challenge_type": "oob", "authenticator_id": "push|dev_ZUla9SQ6tAIHSz6y", "mfa_token": "{mfaToken}" }", ]); $response = curl_exec($curl); @@ -797,20 +839,24 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample38 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret\", \"challenge_type\": \"oob\", \"authenticator_id\": \"push|dev_ZUla9SQ6tAIHSz6y\", \"mfa_token\": \"{mfaToken}\" }" +payload = "{ "client_id": "{yourClientId}", "client_secret": "{yourClientSecret", "challenge_type": "oob", "authenticator_id": "push|dev_ZUla9SQ6tAIHSz6y", "mfa_token": "{mfaToken}" }" conn.request("POST", "/{yourDomain}/mfa/challenge", payload) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample39 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -821,11 +867,13 @@ http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) -request.body = "{ \"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret\", \"challenge_type\": \"oob\", \"authenticator_id\": \"push|dev_ZUla9SQ6tAIHSz6y\", \"mfa_token\": \"{mfaToken}\" }" +request.body = "{ "client_id": "{yourClientId}", "client_secret": "{yourClientSecret", "challenge_type": "oob", "authenticator_id": "push|dev_ZUla9SQ6tAIHSz6y", "mfa_token": "{mfaToken}" }" response = http.request(request) -puts response.read_body`; -export const codeExample40 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let parameters = [ "client_id": "{yourClientId}", "client_secret": "{yourClientSecret", @@ -852,20 +900,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ### Compléter l’authentification à l’aide du code reçu @@ -880,20 +917,26 @@ Si l’opération réussit, vous recevrez la réponse suivante : Votre application doit commencer à interroger le point de terminaison OAuth0 Token jusqu’à ce que l’utilisateur accepte la notification poussée. -export const codeExample41 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=http://auth0.com/oauth/grant-type/mfa-oob \ --data 'client_id={yourClientId}' \ --data 'client_secret={yourClientSecret}' \ --data 'mfa_token={mfaToken}' \ - --data 'oob_code={oobCode}'`; -export const codeExample42 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data 'oob_code={oobCode}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=http%3A%2F%2Fauth0.com%2Foauth%2Fgrant-type%2Fmfa-oob&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&mfa_token=%7BmfaToken%7D&oob_code=%7BoobCode%7D", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample43 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -920,12 +963,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample44 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=http%3A%2F%2Fauth0.com%2Foauth%2Fgrant-type%2Fmfa-oob&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&mfa_token=%7BmfaToken%7D&oob_code=%7BoobCode%7D") - .asString();`; -export const codeExample45 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -944,8 +991,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample46 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -972,8 +1021,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample47 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -998,8 +1049,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample48 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -1012,8 +1065,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample49 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -1028,8 +1083,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=http%3A%2F%2Fauth0.com%2Foauth%2Fgrant-type%2Fmfa-oob&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&mfa_token=%7BmfaToken%7D&oob_code=%7BoobCode%7D" response = http.request(request) -puts response.read_body`; -export const codeExample50 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -1056,20 +1113,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + L’appel peut renvoyer un des résultats suivants : diff --git a/main/docs/fr-ca/secure/multi-factor-authentication/authenticate-using-ropg-flow-with-mfa/enroll-challenge-sms-voice-authenticators.mdx b/main/docs/fr-ca/secure/multi-factor-authentication/authenticate-using-ropg-flow-with-mfa/enroll-challenge-sms-voice-authenticators.mdx index ca79f3afd..0bd3bef53 100644 --- a/main/docs/fr-ca/secure/multi-factor-authentication/authenticate-using-ropg-flow-with-mfa/enroll-challenge-sms-voice-authenticators.mdx +++ b/main/docs/fr-ca/secure/multi-factor-authentication/authenticate-using-ropg-flow-with-mfa/enroll-challenge-sms-voice-authenticators.mdx @@ -10,6 +10,7 @@ permalink: "enroll-challenge-sms-voice-authenticators" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Auth0 offre un flux intégré d’enregistrement et d’authentification MFA en utilisant la [connexion universelle](/docs/fr-ca/authenticate/login/auth0-universal-login). Cependant, si vous souhaitez créer votre propre interface utilisateur, vous pouvez utiliser [l’API MFA](/docs/fr-ca/secure/multi-factor-authentication/multi-factor-authentication-developer-resources/mfa-api) pour ce faire. @@ -35,18 +36,24 @@ Faites une demande `POST (PUBLIER)` au point de terminaison d’association MFA Pour s’inscrire par SMS ou par la voix, ils s’inscrivent avec un numéro de téléphone, soit par SMS, soit par la voix. Spécifiez les paramètres ci-dessous pour appeler le point de terminaison. Le paramètre `oob_channels` indique comment vous souhaitez envoyer le code à l’utilisateur (SMS ou voix). -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/mfa/associate' \ --header 'authorization: Bearer {mfaToken}' \ --header 'content-type: application/json' \ - --data '{ "authenticator_types": ["oob"], "oob_channels": ["sms"], "phone_number": "+11...9" }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/mfa/associate"); + --data '{ "authenticator_types": ["oob"], "oob_channels": ["sms"], "phone_number": "+11...9" }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/mfa/associate"); var request = new RestRequest(Method.POST); request.AddHeader("authorization", "Bearer {mfaToken}"); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{ \"authenticator_types\": [\"oob\"], \"oob_channels\": [\"sms\"], \"phone_number\": \"+11...9\" }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "authenticator_types": ["oob"], "oob_channels": ["sms"], "phone_number": "+11...9" }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -59,7 +66,7 @@ func main() { url := "https://{yourDomain}/mfa/associate" - payload := strings.NewReader("{ \"authenticator_types\": [\"oob\"], \"oob_channels\": [\"sms\"], \"phone_number\": \"+11...9\" }") + payload := strings.NewReader("{ "authenticator_types": ["oob"], "oob_channels": ["sms"], "phone_number": "+11...9" }") req, _ := http.NewRequest("POST", url, payload) @@ -74,13 +81,17 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/mfa/associate") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/mfa/associate") .header("authorization", "Bearer {mfaToken}") .header("content-type", "application/json") - .body("{ \"authenticator_types\": [\"oob\"], \"oob_channels\": [\"sms\"], \"phone_number\": \"+11...9\" }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "authenticator_types": ["oob"], "oob_channels": ["sms"], "phone_number": "+11...9" }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -93,8 +104,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer {mfaToken}", @"content-type": @"application/json" }; @@ -121,8 +134,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/mfa/associate", @@ -132,7 +147,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{ \"authenticator_types\": [\"oob\"], \"oob_channels\": [\"sms\"], \"phone_number\": \"+11...9\" }", + CURLOPT_POSTFIELDS => "{ "authenticator_types": ["oob"], "oob_channels": ["sms"], "phone_number": "+11...9" }", CURLOPT_HTTPHEADER => [ "authorization: Bearer {mfaToken}", "content-type: application/json" @@ -148,12 +163,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"authenticator_types\": [\"oob\"], \"oob_channels\": [\"sms\"], \"phone_number\": \"+11...9\" }" +payload = "{ "authenticator_types": ["oob"], "oob_channels": ["sms"], "phone_number": "+11...9" }" headers = { 'authorization': "Bearer {mfaToken}", @@ -165,8 +182,10 @@ conn.request("POST", "/{yourDomain}/mfa/associate", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -179,11 +198,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["authorization"] = 'Bearer {mfaToken}' request["content-type"] = 'application/json' -request.body = "{ \"authenticator_types\": [\"oob\"], \"oob_channels\": [\"sms\"], \"phone_number\": \"+11...9\" }" +request.body = "{ "authenticator_types": ["oob"], "oob_channels": ["sms"], "phone_number": "+11...9" }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "authorization": "Bearer {mfaToken}", @@ -214,20 +235,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + @@ -275,7 +285,9 @@ Les utilisateurs recevront un courriel contenant un code à six chiffres qu’il Pour compléter l’inscription, réalisez une requête `POST` au point de terminaison OAuth Token. Vous devez inclure le `oob_code` retourné dans la réponse précédente et le `binding_code` avec la valeur reçue dans le message. -export const codeExample11 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'authorization: Bearer {mfaToken}' \ --header 'content-type: application/x-www-form-urlencoded' \ @@ -284,14 +296,18 @@ export const codeExample11 = `curl --request POST \ --data 'client_secret={yourClientSecret}' \ --data 'mfa_token={mfaToken}' \ --data 'oob_code={oobCode}' \ - --data 'binding_code={userOtpCode}'`; -export const codeExample12 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data 'binding_code={userOtpCode}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("authorization", "Bearer {mfaToken}"); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=http%3A%2F%2Fauth0.com%2Foauth%2Fgrant-type%2Fmfa-oob&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&mfa_token=%7BmfaToken%7D&oob_code=%7BoobCode%7D&binding_code=%7BuserOtpCode%7D", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample13 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -319,13 +335,17 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample14 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("authorization", "Bearer {mfaToken}") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=http%3A%2F%2Fauth0.com%2Foauth%2Fgrant-type%2Fmfa-oob&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&mfa_token=%7BmfaToken%7D&oob_code=%7BoobCode%7D&binding_code=%7BuserOtpCode%7D") - .asString();`; -export const codeExample15 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -348,8 +368,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample16 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer {mfaToken}", @"content-type": @"application/x-www-form-urlencoded" }; @@ -378,8 +400,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -405,8 +429,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -422,8 +448,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -439,8 +467,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=http%3A%2F%2Fauth0.com%2Foauth%2Fgrant-type%2Fmfa-oob&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&mfa_token=%7BmfaToken%7D&oob_code=%7BoobCode%7D&binding_code=%7BuserOtpCode%7D" response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "authorization": "Bearer {mfaToken}", @@ -471,20 +501,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + Si l’appel ne réussi pas, vous recevrez une réponse dans le format suivant, contenant le jeton d’accès : @@ -508,16 +527,22 @@ Obtenez un jeton MFA en suivant les étapes décrites dans [Autorisation par mot Pour effectuer le défi-réponse avec l’utilisateur, vous aurez besoin de l’`authenticator_id` pour le facteur que vous désirez utiliser. Vous pouvez énumérer toutes les authentifications à l’aide du point de terminaison des facteurs d’authentification MFA : -export const codeExample21 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/mfa/authenticators' \ --header 'authorization: Bearer MFA_TOKEN' \ - --header 'content-type: application/json'`; -export const codeExample22 = `var client = new RestClient("https://{yourDomain}/mfa/authenticators"); + --header 'content-type: application/json' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/mfa/authenticators"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer MFA_TOKEN"); request.AddHeader("content-type", "application/json"); -IRestResponse response = client.Execute(request);`; -export const codeExample23 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -542,12 +567,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample24 = `HttpResponse response = Unirest.get("https://{yourDomain}/mfa/authenticators") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/mfa/authenticators") .header("authorization", "Bearer MFA_TOKEN") .header("content-type", "application/json") - .asString();`; -export const codeExample25 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -559,8 +588,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample26 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MFA_TOKEN", @"content-type": @"application/json" }; @@ -581,8 +612,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample27 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/mfa/authenticators", @@ -607,8 +640,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample28 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -622,8 +657,10 @@ conn.request("GET", "/{yourDomain}/mfa/authenticators", headers=headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample29 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -638,8 +675,10 @@ request["authorization"] = 'Bearer MFA_TOKEN' request["content-type"] = 'application/json' response = http.request(request) -puts response.read_body`; -export const codeExample30 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "authorization": "Bearer MFA_TOKEN", @@ -662,20 +701,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + Vous obtiendrez une liste de facteurs d’authentification avec le format suivant : @@ -707,16 +735,22 @@ Vous obtiendrez une liste de facteurs d’authentification avec le format suivan Pour déclencher un défi-réponse `POST` au point de terminaison du défi-réponse de MFA à l’aide de l’`authenticator_id` correspondante et du `mfa_token`. -export const codeExample31 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/mfa/challenge' \ --header 'content-type: application/json' \ - --data '{ "client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "challenge_type": "oob", "authenticator_id": "sms|dev_NU1Ofuw3Cw0XCt5x", "mfa_token": "{mfaToken}" }'`; -export const codeExample32 = `var client = new RestClient("https://{yourDomain}/mfa/challenge"); + --data '{ "client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "challenge_type": "oob", "authenticator_id": "sms|dev_NU1Ofuw3Cw0XCt5x", "mfa_token": "{mfaToken}" }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/mfa/challenge"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{ \"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"challenge_type\": \"oob\", \"authenticator_id\": \"sms|dev_NU1Ofuw3Cw0XCt5x\", \"mfa_token\": \"{mfaToken}\" }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample33 = `package main +request.AddParameter("application/json", "{ "client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "challenge_type": "oob", "authenticator_id": "sms|dev_NU1Ofuw3Cw0XCt5x", "mfa_token": "{mfaToken}" }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -729,7 +763,7 @@ func main() { url := "https://{yourDomain}/mfa/challenge" - payload := strings.NewReader("{ \"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"challenge_type\": \"oob\", \"authenticator_id\": \"sms|dev_NU1Ofuw3Cw0XCt5x\", \"mfa_token\": \"{mfaToken}\" }") + payload := strings.NewReader("{ "client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "challenge_type": "oob", "authenticator_id": "sms|dev_NU1Ofuw3Cw0XCt5x", "mfa_token": "{mfaToken}" }") req, _ := http.NewRequest("POST", url, payload) @@ -743,12 +777,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample34 = `HttpResponse response = Unirest.post("https://{yourDomain}/mfa/challenge") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/mfa/challenge") .header("content-type", "application/json") - .body("{ \"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"challenge_type\": \"oob\", \"authenticator_id\": \"sms|dev_NU1Ofuw3Cw0XCt5x\", \"mfa_token\": \"{mfaToken}\" }") - .asString();`; -export const codeExample35 = `var axios = require("axios").default; + .body("{ "client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "challenge_type": "oob", "authenticator_id": "sms|dev_NU1Ofuw3Cw0XCt5x", "mfa_token": "{mfaToken}" }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -767,8 +805,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample36 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json" }; NSDictionary *parameters = @{ @"client_id": @"{yourClientId}", @@ -796,8 +836,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample37 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/mfa/challenge", @@ -807,7 +849,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{ \"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"challenge_type\": \"oob\", \"authenticator_id\": \"sms|dev_NU1Ofuw3Cw0XCt5x\", \"mfa_token\": \"{mfaToken}\" }", + CURLOPT_POSTFIELDS => "{ "client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "challenge_type": "oob", "authenticator_id": "sms|dev_NU1Ofuw3Cw0XCt5x", "mfa_token": "{mfaToken}" }", CURLOPT_HTTPHEADER => [ "content-type: application/json" ], @@ -822,12 +864,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample38 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"challenge_type\": \"oob\", \"authenticator_id\": \"sms|dev_NU1Ofuw3Cw0XCt5x\", \"mfa_token\": \"{mfaToken}\" }" +payload = "{ "client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "challenge_type": "oob", "authenticator_id": "sms|dev_NU1Ofuw3Cw0XCt5x", "mfa_token": "{mfaToken}" }" headers = { 'content-type': "application/json" } @@ -836,8 +880,10 @@ conn.request("POST", "/{yourDomain}/mfa/challenge", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample39 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -849,11 +895,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["content-type"] = 'application/json' -request.body = "{ \"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"challenge_type\": \"oob\", \"authenticator_id\": \"sms|dev_NU1Ofuw3Cw0XCt5x\", \"mfa_token\": \"{mfaToken}\" }" +request.body = "{ "client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "challenge_type": "oob", "authenticator_id": "sms|dev_NU1Ofuw3Cw0XCt5x", "mfa_token": "{mfaToken}" }" response = http.request(request) -puts response.read_body`; -export const codeExample40 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/json"] let parameters = [ @@ -883,20 +931,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ### Compléter l’authentification à l’aide du code reçu @@ -912,7 +949,9 @@ Si l’opération réussit, vous recevrez la réponse suivante : Votre application doit demander à l’utilisateur le code à 6 chiffres envoyé dans le message et doit être défini dans le paramètre `binding_code`. Vous pouvez vérifier le code et obtenir des jetons d’authentification à l’aide du point de terminaison du jeton OAuth0, en spécifiant le `binding_code` et le `oob_code` renvoyés par l’appel précédent : -export const codeExample41 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=http://auth0.com/oauth/grant-type/mfa-oob \ @@ -920,13 +959,17 @@ export const codeExample41 = `curl --request POST \ --data 'client_secret={yourClientSecret}' \ --data 'mfa_token={mfaToken}' \ --data 'oob_code={oobCode}' \ - --data binding_code=USER_OTP_CODE`; -export const codeExample42 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data binding_code=USER_OTP_CODE +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=http%3A%2F%2Fauth0.com%2Foauth%2Fgrant-type%2Fmfa-oob&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&mfa_token=%7BmfaToken%7D&oob_code=%7BoobCode%7D&binding_code=USER_OTP_CODE", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample43 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -953,12 +996,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample44 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=http%3A%2F%2Fauth0.com%2Foauth%2Fgrant-type%2Fmfa-oob&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&mfa_token=%7BmfaToken%7D&oob_code=%7BoobCode%7D&binding_code=USER_OTP_CODE") - .asString();`; -export const codeExample45 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -978,8 +1025,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample46 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -1007,8 +1056,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample47 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -1033,8 +1084,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample48 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -1047,8 +1100,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample49 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -1063,8 +1118,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=http%3A%2F%2Fauth0.com%2Foauth%2Fgrant-type%2Fmfa-oob&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&mfa_token=%7BmfaToken%7D&oob_code=%7BoobCode%7D&binding_code=USER_OTP_CODE" response = http.request(request) -puts response.read_body`; -export const codeExample50 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -1092,20 +1149,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + Si l’appel ne réussit pas, vous recevrez une réponse dans le format ci-dessous, contenant le jeton d’accès : diff --git a/main/docs/fr-ca/secure/multi-factor-authentication/manage-mfa-auth0-apis/manage-authentication-methods-with-management-api.mdx b/main/docs/fr-ca/secure/multi-factor-authentication/manage-mfa-auth0-apis/manage-authentication-methods-with-management-api.mdx index 7c6ea72c5..ca27067f6 100644 --- a/main/docs/fr-ca/secure/multi-factor-authentication/manage-mfa-auth0-apis/manage-authentication-methods-with-management-api.mdx +++ b/main/docs/fr-ca/secure/multi-factor-authentication/manage-mfa-auth0-apis/manage-authentication-methods-with-management-api.mdx @@ -10,6 +10,7 @@ permalink: "manage-authentication-methods-with-management-api" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; @@ -37,7 +38,7 @@ Ce point de terminaison requiert la permission : `read:authentication_methods`. La requête suivante renvoie une liste de toutes les méthodes d’authentification pour un utilisateur donné. - + ```bash cURL lines curl --request GET \ --url https://%7ByourDomain%7D/api/v2/users/%7BuserId%7D/authentication-methods \ @@ -204,7 +205,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + ### Réponse @@ -232,7 +233,7 @@ Ce point de terminaison requiert la permission : `read:authentication_methods`. La requête suivante renvoie une seule méthode d’authentification pour un utilisateur sur la base de l’ID de la méthode d’authentification indiquée. - + ```bash cURL lines curl --request GET \ --url https://%7ByourDomain%7D/api/v2/users/%7BuserId%7D/authentication-methods/%7BauthenticationMethodId%7D \ @@ -399,7 +400,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + ### Réponse @@ -435,7 +436,7 @@ Envoyer aux utilisateurs un OTP par SMS, que l’utilisateur est ensuite invit La demande suivante crée une méthode d’authentification par SMS pour un utilisateur. - + ```bash cURL lines curl --request POST \ --url https://%7ByourDomain%7D/api/v2/users/%7BuserId%7D/authentication-methods \ @@ -627,7 +628,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + #### Réponse @@ -651,7 +652,7 @@ Envoyer aux utilisateurs un OTP par courriel, que l’utilisateur est ensuite i La requête suivante crée une méthode d’authentification par courriel pour un utilisateur. - + ```bash cURL lines curl --request POST \ --url https://%7ByourDomain%7D/api/v2/users/%7BuserId%7D/authentication-methods \ @@ -843,7 +844,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + #### Réponse @@ -867,16 +868,22 @@ Autoriser les utilisateurs à utiliser une application d’authentification, tel La demande suivante crée une méthode d’authentification OTP pour un utilisateur. -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url https://%7ByourDomain%7D/api/v2/users/%7BuserId%7D/authentication-methods \ --header 'authorization: Bearer {yourMgmtApiAccessToken}' \ - --data '{ "type": "totp", "name": "OTP Application", "totp_secret": "{yourSecret}" }'`; -export const codeExample2 = `var client = new RestClient("https://%7ByourDomain%7D/api/v2/users/%7BuserId%7D/authentication-methods"); + --data '{ "type": "totp", "name": "OTP Application", "totp_secret": "{yourSecret}" }' +``` +```csharp C# +var client = new RestClient("https://%7ByourDomain%7D/api/v2/users/%7BuserId%7D/authentication-methods"); var request = new RestRequest(Method.POST); request.AddHeader("authorization", "Bearer {yourMgmtApiAccessToken}"); -request.AddParameter("undefined", "{ \"type\": \"totp\", \"name\": \"OTP Application\", \"totp_secret\": \"{yourSecret}\" }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("undefined", "{ "type": "totp", "name": "OTP Application", "totp_secret": "{yourSecret}" }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -889,7 +896,7 @@ func main() { url := "https://%7ByourDomain%7D/api/v2/users/%7BuserId%7D/authentication-methods" - payload := strings.NewReader("{ \"type\": \"totp\", \"name\": \"OTP Application\", \"totp_secret\": \"{yourSecret}\" }") + payload := strings.NewReader("{ "type": "totp", "name": "OTP Application", "totp_secret": "{yourSecret}" }") req, _ := http.NewRequest("POST", url, payload) @@ -903,12 +910,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://%7ByourDomain%7D/api/v2/users/%7BuserId%7D/authentication-methods") +} +``` +```java Java +HttpResponse response = Unirest.post("https://%7ByourDomain%7D/api/v2/users/%7BuserId%7D/authentication-methods") .header("authorization", "Bearer {yourMgmtApiAccessToken}") - .body("{ \"type\": \"totp\", \"name\": \"OTP Application\", \"totp_secret\": \"{yourSecret}\" }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "type": "totp", "name": "OTP Application", "totp_secret": "{yourSecret}" }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -921,8 +932,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer {yourMgmtApiAccessToken}" }; NSDictionary *parameters = @{ @"type": @"totp", @@ -948,8 +961,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://%7ByourDomain%7D/api/v2/users/%7BuserId%7D/authentication-methods", @@ -959,7 +974,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{ \"type\": \"totp\", \"name\": \"OTP Application\", \"totp_secret\": \"{yourSecret}\" }", + CURLOPT_POSTFIELDS => "{ "type": "totp", "name": "OTP Application", "totp_secret": "{yourSecret}" }", CURLOPT_HTTPHEADER => [ "authorization: Bearer {yourMgmtApiAccessToken}" ], @@ -974,12 +989,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"type\": \"totp\", \"name\": \"OTP Application\", \"totp_secret\": \"{yourSecret}\" }" +payload = "{ "type": "totp", "name": "OTP Application", "totp_secret": "{yourSecret}" }" headers = { 'authorization': "Bearer {yourMgmtApiAccessToken}" } @@ -988,8 +1005,10 @@ conn.request("POST", "%7ByourDomain%7D/api/v2/users/%7BuserId%7D/authentication- res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -1001,11 +1020,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["authorization"] = 'Bearer {yourMgmtApiAccessToken}' -request.body = "{ \"type\": \"totp\", \"name\": \"OTP Application\", \"totp_secret\": \"{yourSecret}\" }" +request.body = "{ "type": "totp", "name": "OTP Application", "totp_secret": "{yourSecret}" }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer {yourMgmtApiAccessToken}"] let parameters = [ @@ -1033,20 +1054,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + #### Réponse @@ -1070,16 +1080,22 @@ Permettre aux utilisateurs d’utiliser des clés de sécurité conformes à FID La requête suivante crée une méthode d’authentification WebAuthn avec clés de sécurité pour un utilisateur. -export const codeExample11 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url https://%7ByourDomain%7D/api/v2/users/%7BuserId%7D/authentication-methods \ --header 'authorization: Bearer {yourMgmtApiAccessToken}' \ - --data '{ "type": "webauthn_roaming", "name": "WebAuthn with security keys", "public_key": "{yourPublicKey}", "key_id": "{yourKeyId}", "relying_party_identifier": "{yourDomain}" }'`; -export const codeExample12 = `var client = new RestClient("https://%7ByourDomain%7D/api/v2/users/%7BuserId%7D/authentication-methods"); + --data '{ "type": "webauthn_roaming", "name": "WebAuthn with security keys", "public_key": "{yourPublicKey}", "key_id": "{yourKeyId}", "relying_party_identifier": "{yourDomain}" }' +``` +```csharp C# +var client = new RestClient("https://%7ByourDomain%7D/api/v2/users/%7BuserId%7D/authentication-methods"); var request = new RestRequest(Method.POST); request.AddHeader("authorization", "Bearer {yourMgmtApiAccessToken}"); -request.AddParameter("undefined", "{ \"type\": \"webauthn_roaming\", \"name\": \"WebAuthn with security keys\", \"public_key\": \"{yourPublicKey}\", \"key_id\": \"{yourKeyId}\", \"relying_party_identifier\": \"{yourDomain}\" }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample13 = `package main +request.AddParameter("undefined", "{ "type": "webauthn_roaming", "name": "WebAuthn with security keys", "public_key": "{yourPublicKey}", "key_id": "{yourKeyId}", "relying_party_identifier": "{yourDomain}" }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -1092,7 +1108,7 @@ func main() { url := "https://%7ByourDomain%7D/api/v2/users/%7BuserId%7D/authentication-methods" - payload := strings.NewReader("{ \"type\": \"webauthn_roaming\", \"name\": \"WebAuthn with security keys\", \"public_key\": \"{yourPublicKey}\", \"key_id\": \"{yourKeyId}\", \"relying_party_identifier\": \"{yourDomain}\" }") + payload := strings.NewReader("{ "type": "webauthn_roaming", "name": "WebAuthn with security keys", "public_key": "{yourPublicKey}", "key_id": "{yourKeyId}", "relying_party_identifier": "{yourDomain}" }") req, _ := http.NewRequest("POST", url, payload) @@ -1106,12 +1122,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample14 = `HttpResponse response = Unirest.post("https://%7ByourDomain%7D/api/v2/users/%7BuserId%7D/authentication-methods") +} +``` +```java Java +HttpResponse response = Unirest.post("https://%7ByourDomain%7D/api/v2/users/%7BuserId%7D/authentication-methods") .header("authorization", "Bearer {yourMgmtApiAccessToken}") - .body("{ \"type\": \"webauthn_roaming\", \"name\": \"WebAuthn with security keys\", \"public_key\": \"{yourPublicKey}\", \"key_id\": \"{yourKeyId}\", \"relying_party_identifier\": \"{yourDomain}\" }") - .asString();`; -export const codeExample15 = `var axios = require("axios").default; + .body("{ "type": "webauthn_roaming", "name": "WebAuthn with security keys", "public_key": "{yourPublicKey}", "key_id": "{yourKeyId}", "relying_party_identifier": "{yourDomain}" }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -1130,8 +1150,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample16 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer {yourMgmtApiAccessToken}" }; NSDictionary *parameters = @{ @"type": @"webauthn_roaming", @@ -1159,8 +1181,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://%7ByourDomain%7D/api/v2/users/%7BuserId%7D/authentication-methods", @@ -1170,7 +1194,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{ \"type\": \"webauthn_roaming\", \"name\": \"WebAuthn with security keys\", \"public_key\": \"{yourPublicKey}\", \"key_id\": \"{yourKeyId}\", \"relying_party_identifier\": \"{yourDomain}\" }", + CURLOPT_POSTFIELDS => "{ "type": "webauthn_roaming", "name": "WebAuthn with security keys", "public_key": "{yourPublicKey}", "key_id": "{yourKeyId}", "relying_party_identifier": "{yourDomain}" }", CURLOPT_HTTPHEADER => [ "authorization: Bearer {yourMgmtApiAccessToken}" ], @@ -1185,12 +1209,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"type\": \"webauthn_roaming\", \"name\": \"WebAuthn with security keys\", \"public_key\": \"{yourPublicKey}\", \"key_id\": \"{yourKeyId}\", \"relying_party_identifier\": \"{yourDomain}\" }" +payload = "{ "type": "webauthn_roaming", "name": "WebAuthn with security keys", "public_key": "{yourPublicKey}", "key_id": "{yourKeyId}", "relying_party_identifier": "{yourDomain}" }" headers = { 'authorization': "Bearer {yourMgmtApiAccessToken}" } @@ -1199,8 +1225,10 @@ conn.request("POST", "%7ByourDomain%7D/api/v2/users/%7BuserId%7D/authentication- res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -1212,11 +1240,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["authorization"] = 'Bearer {yourMgmtApiAccessToken}' -request.body = "{ \"type\": \"webauthn_roaming\", \"name\": \"WebAuthn with security keys\", \"public_key\": \"{yourPublicKey}\", \"key_id\": \"{yourKeyId}\", \"relying_party_identifier\": \"{yourDomain}\" }" +request.body = "{ "type": "webauthn_roaming", "name": "WebAuthn with security keys", "public_key": "{yourPublicKey}", "key_id": "{yourKeyId}", "relying_party_identifier": "{yourDomain}" }" response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer {yourMgmtApiAccessToken}"] let parameters = [ @@ -1246,20 +1276,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + #### Réponse @@ -1287,7 +1306,7 @@ Ce point de terminaison nécessite la permission : `update:authentication_metho La requête suivante remplace toutes les méthodes d’authentification existantes pour un utilisateur. - + ```bash cURL lines curl --request PUT \ --url https://%7ByourDomain%7D/api/v2/users/%7BuserId%7D/authentication-methods \ @@ -1487,7 +1506,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + ### Réponse @@ -1522,7 +1541,7 @@ Ce point de terminaison nécessite la permission : `update:authentication_metho La requête suivante met à jour une méthode d’authentification unique pour un utilisateur sur la base de l’identifiant de la méthode d’authentification spécifique. - + ```bash cURL lines curl --request PATCH \ --url https://%7ByourDomain%7D/api/v2/users/%7BuserId%7D/authentication-methods/%7BauthenticationMethodId%7D \ @@ -1708,7 +1727,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + ### Réponse @@ -1742,7 +1761,7 @@ Ce point de terminaison nécessite la permission : `delete:authentication_metho La requête suivante supprime toutes les méthodes d’authentification pour un utilisateur. - + ```bash cURL lines curl --request DELETE \ --url https://%7ByourDomain%7D/api/v2/users/%7BuserId%7D/authentication-methods \ @@ -1909,7 +1928,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + ### Réponse @@ -1923,7 +1942,7 @@ Utilisez le point de terminaison [Supprime une méthode d’authentification par La requête suivante supprime une méthode d’authentification unique pour un utilisateur sur la base de l’ID de la méthode d’authentification indiquée. - + ```bash cURL lines curl --request DELETE \ --url https://%7ByourDomain%7D/api/v2/users/%7BuserId%7D/authentication-methods/%7BauthenticationMethodId%7D \ @@ -2090,7 +2109,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + ### Réponse diff --git a/main/docs/fr-ca/secure/multi-factor-authentication/manage-mfa-auth0-apis/manage-authenticator-factors-mfa-api.mdx b/main/docs/fr-ca/secure/multi-factor-authentication/manage-mfa-auth0-apis/manage-authenticator-factors-mfa-api.mdx index 0e9a96a1f..9eaafc14d 100644 --- a/main/docs/fr-ca/secure/multi-factor-authentication/manage-mfa-auth0-apis/manage-authenticator-factors-mfa-api.mdx +++ b/main/docs/fr-ca/secure/multi-factor-authentication/manage-mfa-auth0-apis/manage-authenticator-factors-mfa-api.mdx @@ -10,6 +10,7 @@ permalink: "manage-authenticator-factors-mfa-api" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; @@ -79,14 +80,20 @@ Lorsque vous demandez un jeton pour l'audience MFA, vous pouvez demander les per Pour obtenir une liste des authentifiants pour un utilisateur, vous pouvez appeler le point de terminaison des authentifiants MFA : -export const codeExample1 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/mfa/authenticators' \ - --header 'authorization: Bearer MFA_TOKEN'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/mfa/authenticators"); + --header 'authorization: Bearer MFA_TOKEN' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/mfa/authenticators"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer MFA_TOKEN"); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -110,11 +117,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.get("https://{yourDomain}/mfa/authenticators") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/mfa/authenticators") .header("authorization", "Bearer MFA_TOKEN") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -126,8 +137,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MFA_TOKEN" }; @@ -147,8 +160,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/mfa/authenticators", @@ -172,8 +187,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -184,8 +201,10 @@ conn.request("GET", "/{yourDomain}/mfa/authenticators", headers=headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -199,8 +218,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer MFA_TOKEN' response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer MFA_TOKEN"] @@ -220,20 +241,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + Dans la réponse, vous devriez recevoir des informations concernant le(s) type(s) d’authentifiants : @@ -302,14 +312,20 @@ Pour supprimer un authentifiant associé, envoyez une demande `DELETE` au point Si un `mfa_token` a été utilisé pour répertorier les authentifiants, les utilisateurs devront [compléter MFA pour obtenir un jeton d’accès](https://auth0.com/docs/fr-ca/api/authentication/muti-factor-authentication/verify-mfa-with-otp) avec une audience de `https://{yourDomain}/mfa/` afin de supprimer un authentifiant. -export const codeExample11 = `curl --request DELETE \ + +```bash cURL +curl --request DELETE \ --url 'https://{yourDomain}/mfa/authenticators/AUTHENTICATOR_ID' \ - --header 'authorization: Bearer ACCESS_TOKEN'`; -export const codeExample12 = `var client = new RestClient("https://{yourDomain}/mfa/authenticators/AUTHENTICATOR_ID"); + --header 'authorization: Bearer ACCESS_TOKEN' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/mfa/authenticators/AUTHENTICATOR_ID"); var request = new RestRequest(Method.DELETE); request.AddHeader("authorization", "Bearer ACCESS_TOKEN"); -IRestResponse response = client.Execute(request);`; -export const codeExample13 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -333,11 +349,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample14 = `HttpResponse response = Unirest.delete("https://{yourDomain}/mfa/authenticators/AUTHENTICATOR_ID") +} +``` +```java Java +HttpResponse response = Unirest.delete("https://{yourDomain}/mfa/authenticators/AUTHENTICATOR_ID") .header("authorization", "Bearer ACCESS_TOKEN") - .asString();`; -export const codeExample15 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'DELETE', @@ -349,8 +369,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample16 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer ACCESS_TOKEN" }; @@ -370,8 +392,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/mfa/authenticators/AUTHENTICATOR_ID", @@ -395,8 +419,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -407,8 +433,10 @@ conn.request("DELETE", "/{yourDomain}/mfa/authenticators/AUTHENTICATOR_ID", head res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -422,8 +450,10 @@ request = Net::HTTP::Delete.new(url) request["authorization"] = 'Bearer ACCESS_TOKEN' response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer ACCESS_TOKEN"] @@ -443,20 +473,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + Si l’authentifiant a été supprimé, une réponse 204 est renvoyée. @@ -469,14 +488,20 @@ Un produit permettant aux clients d’effectuer des tâches administratives." ct Pour supprimer un code de récupération et en générer un nouveau, obtenez un [Jeton d’accès à Management API](https://auth0.com/docs/api/management/v2/tokens) et utiliser le [point de terminaison de régénération](https://auth0.com/docs/api/management/v2/#!/Users/post_recovery_code_regeneration) Management API. -export const codeExample21 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/api/v2/users/USER_ID/recovery-code-regeneration' \ - --header 'authorization: Bearer MANAGEMENT_API_TOKEN'`; -export const codeExample22 = `var client = new RestClient("https://{yourDomain}/api/v2/users/USER_ID/recovery-code-regeneration"); + --header 'authorization: Bearer MANAGEMENT_API_TOKEN' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users/USER_ID/recovery-code-regeneration"); var request = new RestRequest(Method.POST); request.AddHeader("authorization", "Bearer MANAGEMENT_API_TOKEN"); -IRestResponse response = client.Execute(request);`; -export const codeExample23 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -500,11 +525,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample24 = `HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/users/USER_ID/recovery-code-regeneration") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/users/USER_ID/recovery-code-regeneration") .header("authorization", "Bearer MANAGEMENT_API_TOKEN") - .asString();`; -export const codeExample25 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -516,8 +545,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample26 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MANAGEMENT_API_TOKEN" }; @@ -537,8 +568,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample27 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users/USER_ID/recovery-code-regeneration", @@ -562,8 +595,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample28 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -574,8 +609,10 @@ conn.request("POST", "/{yourDomain}/api/v2/users/USER_ID/recovery-code-regenerat res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample29 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -589,8 +626,10 @@ request = Net::HTTP::Post.new(url) request["authorization"] = 'Bearer MANAGEMENT_API_TOKEN' response = http.request(request) -puts response.read_body`; -export const codeExample30 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer MANAGEMENT_API_TOKEN"] @@ -610,20 +649,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + Vous obtiendrez un nouveau code de récupération que l’utilisateur final devra enregistrer, par exemple : diff --git a/main/docs/fr-ca/secure/multi-factor-authentication/multi-factor-authentication-factors/configure-sms-voice-notifications-mfa.mdx b/main/docs/fr-ca/secure/multi-factor-authentication/multi-factor-authentication-factors/configure-sms-voice-notifications-mfa.mdx index edb95fa4c..9404a01f0 100644 --- a/main/docs/fr-ca/secure/multi-factor-authentication/multi-factor-authentication-factors/configure-sms-voice-notifications-mfa.mdx +++ b/main/docs/fr-ca/secure/multi-factor-authentication/multi-factor-authentication-factors/configure-sms-voice-notifications-mfa.mdx @@ -10,6 +10,7 @@ permalink: "configure-sms-voice-notifications-mfa" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; @@ -36,7 +37,7 @@ Lorsque les SMS et la voix sont activés, les utilisateurs ont ](/docs/images/li ![Configure SMS and Voice for MFA User Experience Voice](/images/fr-ca/cdy7uua7fh8z/2Q4BViGl71sdrytUDgNJ10/0594feaeff5f1bc25ce48f7498de6868/mfa-sms-voice.png) -Lorsque vous activez uniquement les SMS, le flux est plus si](/docs/images/ +Lorsque vous activez uniquement les SMS, le flux est plus si ![Configure SMS and Voice for MFA User Experience SMS](/images/fr-ca/cdy7uua7fh8z/64PgR0CO1Wjfie2Hxy1Ptw/4de524c5759f68ca30f8dfe11cfde158/mfa-sms.png) @@ -85,18 +86,24 @@ Vous pouvez personnaliser vos modèles de SMS et de messages vocaux. Pour en sa Vous pouvez utiliser Management API pour configurer les méthodes de livraison de messages activées à l’aide du point de terminaison `/api/v2/guardian/factors/phone/message-types`. Le paramètre `message_types` est un tableau qui peut contenir `["sms"]`, `["voice"]`, or `["sms", "voice"]`. Vous avez besoin d’un [Jeton d’accès à Management API)](/docs/fr-ca/secure/tokens/access-tokens/management-api-access-tokens) avec la permission `update:guardian_factors` en tant que jeton du porteur pour appeler l’API : -export const codeExample1 = `curl --request PUT \ + +```bash cURL +curl --request PUT \ --url 'https://{yourDomain}/api/v2/guardian/factors/phone/message-types' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'content-type: application/json' \ - --data '{ "message_types": ["sms", "voice"] }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/guardian/factors/phone/message-types"); + --data '{ "message_types": ["sms", "voice"] }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/guardian/factors/phone/message-types"); var request = new RestRequest(Method.PUT); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); -request.AddParameter("application/json", "{ \"message_types\": [\"sms\", \"voice\"] }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "message_types": ["sms", "voice"] }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -109,7 +116,7 @@ func main() { url := "https://{yourDomain}/api/v2/guardian/factors/phone/message-types" - payload := strings.NewReader("{ \"message_types\": [\"sms\", \"voice\"] }") + payload := strings.NewReader("{ "message_types": ["sms", "voice"] }") req, _ := http.NewRequest("PUT", url, payload) @@ -124,13 +131,17 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.put("https://{yourDomain}/api/v2/guardian/factors/phone/message-types") +} +``` +```java Java +HttpResponse response = Unirest.put("https://{yourDomain}/api/v2/guardian/factors/phone/message-types") .header("content-type", "application/json") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") - .body("{ \"message_types\": [\"sms\", \"voice\"] }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "message_types": ["sms", "voice"] }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PUT', @@ -146,8 +157,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN" }; @@ -172,8 +185,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/guardian/factors/phone/message-types", @@ -183,7 +198,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PUT", - CURLOPT_POSTFIELDS => "{ \"message_types\": [\"sms\", \"voice\"] }", + CURLOPT_POSTFIELDS => "{ "message_types": ["sms", "voice"] }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "content-type: application/json" @@ -199,12 +214,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"message_types\": [\"sms\", \"voice\"] }" +payload = "{ "message_types": ["sms", "voice"] }" headers = { 'content-type': "application/json", @@ -216,8 +233,10 @@ conn.request("PUT", "/{yourDomain}/api/v2/guardian/factors/phone/message-types", res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -230,11 +249,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Put.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' -request.body = "{ \"message_types\": [\"sms\", \"voice\"] }" +request.body = "{ "message_types": ["sms", "voice"] }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -261,20 +282,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ## Fournisseurs de messagerie SMS intégrés diff --git a/main/docs/fr-ca/secure/security-guidance/data-security/denylist.mdx b/main/docs/fr-ca/secure/security-guidance/data-security/denylist.mdx index 30f1f2f35..e30031d52 100644 --- a/main/docs/fr-ca/secure/security-guidance/data-security/denylist.mdx +++ b/main/docs/fr-ca/secure/security-guidance/data-security/denylist.mdx @@ -10,6 +10,7 @@ permalink: "denylist" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; S’il existe des champs utilisateur qui ne doivent pas être stockés dans les bases de données Auth0 pour des raisons de confidentialité, vous pouvez les ajouter à la liste rouge. Pour ajouter des attributs à la liste rouge, effectuez un appel `PATCH` au point de terminaison de connexion de mise à jour de Management API. @@ -17,20 +18,26 @@ Un produit permettant aux clients d’effectuer des tâches administratives." ct 1. Obtenez un jeton d’accès valide pour accéder au [point de terminaison](/docs/fr-ca/api/management/v2#!/Connections/patch_connections_by_id)`/patch_connections_by_id`. Le jeton doit inclure la permission `update:connections`. Pour plus de détails, veuillez consulter [Jetons d’accès à Management API](/docs/fr-ca/secure/tokens/access-tokens/management-api-access-tokens). 2. Avec le jeton d’accès et la liste des attributs à refuser, appelez l’API. Voici un exemple de requête HTTP qui refuse deux attributs : l’origine ethnique et le genre. Gardez à l’esprit que vous devez récupérer l’objet options et envoyer l’objet entier dans votre requête PATCH, car il n’y a pas de « fusion » si vous ne mettez à jour qu’une ou deux valeurs. -export const codeExample1 = ` curl --request PATCH \ + +```bash cURL + curl --request PATCH \ --url 'https://{yourDomain}/api/v2/connections/YOUR_CONNECTION_ID' \ --header 'authorization: Bearer YOUR_TOKEN' \ --header 'content-type: application/json' \ --data '{"options": {"non_persistent_attrs": ["ethnicity", "gender"]}}' -`; -export const codeExample2 = ` var client = new RestClient("https://{yourDomain}/api/v2/connections/YOUR_CONNECTION_ID"); + +``` +```csharp C# + var client = new RestClient("https://{yourDomain}/api/v2/connections/YOUR_CONNECTION_ID"); var request = new RestRequest(Method.PATCH); request.AddHeader("authorization", "Bearer YOUR_TOKEN"); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\"options\": {\"non_persistent_attrs\": [\"ethnicity\", \"gender\"]}}", ParameterType.RequestBody); +request.AddParameter("application/json", "{"options": {"non_persistent_attrs": ["ethnicity", "gender"]}}", ParameterType.RequestBody); IRestResponse response = client.Execute(request); -`; -export const codeExample3 = ` package main + +``` +```go Go + package main import ( "fmt" @@ -43,7 +50,7 @@ func main() { url := "https://{yourDomain}/api/v2/connections/YOUR_CONNECTION_ID" - payload := strings.NewReader("{\"options\": {\"non_persistent_attrs\": [\"ethnicity\", \"gender\"]}}") + payload := strings.NewReader("{"options": {"non_persistent_attrs": ["ethnicity", "gender"]}}") req, _ := http.NewRequest("PATCH", url, payload) @@ -59,14 +66,18 @@ func main() { fmt.Println(string(body)) } -`; -export const codeExample4 = ` HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/connections/YOUR_CONNECTION_ID") + +``` +```java Java + HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/connections/YOUR_CONNECTION_ID") .header("authorization", "Bearer YOUR_TOKEN") .header("content-type", "application/json") - .body("{\"options\": {\"non_persistent_attrs\": [\"ethnicity\", \"gender\"]}}") + .body("{"options": {"non_persistent_attrs": ["ethnicity", "gender"]}}") .asString(); -`; -export const codeExample5 = ` var axios = require("axios").default; + +``` +```javascript Node.JS + var axios = require("axios").default; var options = { method: 'PATCH', @@ -80,8 +91,10 @@ axios.request(options).then(function (response) { }).catch(function (error) { console.error(error); }); -`; -export const codeExample6 = ` #import + +``` +```obj-c Obj-C + #import NSDictionary *headers = @{ @"authorization": @"Bearer YOUR_TOKEN", @"content-type": @"application/json" }; @@ -107,8 +120,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request } }]; [dataTask resume]; -`; -export const codeExample7 = ` $curl = curl_init(); + +``` +```php PHP + $curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/connections/YOUR_CONNECTION_ID", @@ -118,7 +133,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{\"options\": {\"non_persistent_attrs\": [\"ethnicity\", \"gender\"]}}", + CURLOPT_POSTFIELDS => "{"options": {"non_persistent_attrs": ["ethnicity", "gender"]}}", CURLOPT_HTTPHEADER => [ "authorization: Bearer YOUR_TOKEN", "content-type: application/json" @@ -135,12 +150,14 @@ if ($err) { } else { echo $response; } -`; -export const codeExample8 = ` import http.client + +``` +```python Python + import http.client conn = http.client.HTTPSConnection("") -payload = "{\"options\": {\"non_persistent_attrs\": [\"ethnicity\", \"gender\"]}}" +payload = "{"options": {"non_persistent_attrs": ["ethnicity", "gender"]}}" headers = { 'authorization': "Bearer YOUR_TOKEN", @@ -153,8 +170,10 @@ res = conn.getresponse() data = res.read() print(data.decode("utf-8")) -`; -export const codeExample9 = ` require 'uri' + +``` +```ruby Ruby + require 'uri' require 'net/http' require 'openssl' @@ -167,12 +186,14 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Patch.new(url) request["authorization"] = 'Bearer YOUR_TOKEN' request["content-type"] = 'application/json' -request.body = "{\"options\": {\"non_persistent_attrs\": [\"ethnicity\", \"gender\"]}}" +request.body = "{"options": {"non_persistent_attrs": ["ethnicity", "gender"]}}" response = http.request(request) puts response.read_body -`; -export const codeExample10 = ` import Foundation + +``` +```swift Swift + import Foundation let headers = [ "authorization": "Bearer YOUR_TOKEN", @@ -200,20 +221,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: }) dataTask.resume() -`; - - - - - - - - - - - - - + +``` + Où : 1. `{yourConnectionId}` est [l’ID de connexion](/docs/fr-ca/authenticate/identity-providers/locate-the-connection-id) pour lequel ces attributs seront refusés. diff --git a/main/docs/fr-ca/secure/security-guidance/data-security/user-data-storage.mdx b/main/docs/fr-ca/secure/security-guidance/data-security/user-data-storage.mdx index b5df0223d..4d9d64f19 100644 --- a/main/docs/fr-ca/secure/security-guidance/data-security/user-data-storage.mdx +++ b/main/docs/fr-ca/secure/security-guidance/data-security/user-data-storage.mdx @@ -10,6 +10,7 @@ permalink: "user-data-storage" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Auth0 stocke les informations des utilisateurs de votre locataire dans une base de données hébergée dans le nuage, ou vous pouvez choisir de stocker les données des utilisateurs dans votre propre base de données externe personnalisée. @@ -73,14 +74,14 @@ function(user, context, callback){ } ``` -Voici un aperçu de l’écran que l’utilisateur utiliserait pour modifier son `displayName` :](/docs/images/ +Voici un aperçu de l’écran que l’utilisateur utiliserait pour modifier son `displayName` : ![Écran des paramètres de l'application iOS avec option de mise à jour du nom d'affichage.](/images/fr-ca/cdy7uua7fh8z/33YxGQKYztHY3OM6mxJ4jN/0a06103e6b6455c2e1962a1f738b663a/4-settings.png) pour enregistrer les modifications dans la base de données, l’application appelle le point de terminaison [Obtenir un utilisateur](/docs/fr-ca/api/management/v2#!/Users/get_users_by_id) de Management API pour identifier l’utilisateur approprié : - + ```bash cURL lines curl --request GET \ --url https://%7ByourAccount%7D.auth0.com/api/v2/users/user_id \ @@ -247,22 +248,28 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + cet appel est suivi d’un appel au point de terminaison [Mettre à jour un utilisateur](/docs/fr-ca/api/management/v2#!/Users/patch_users_by_id) pour mettre à jour le champ `user_metadata` : -export const codeExample1 = `curl --request PATCH \ + +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/users/user_id' \ --header 'authorization: Bearer {yourAccessToken}' \ --header 'content-type: application/json' \ - --data '{"user_metadata": {"displayName": "J-vald3z"}'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/users/user_id"); + --data '{"user_metadata": {"displayName": "J-vald3z"}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users/user_id"); var request = new RestRequest(Method.PATCH); request.AddHeader("authorization", "Bearer {yourAccessToken}"); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\"user_metadata\": {\"displayName\": \"J-vald3z\"}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{"user_metadata": {"displayName": "J-vald3z"}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -275,7 +282,7 @@ func main() { url := "https://{yourDomain}/api/v2/users/user_id" - payload := strings.NewReader("{\"user_metadata\": {\"displayName\": \"J-vald3z\"}") + payload := strings.NewReader("{"user_metadata": {"displayName": "J-vald3z"}") req, _ := http.NewRequest("PATCH", url, payload) @@ -290,13 +297,17 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/users/user_id") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/users/user_id") .header("authorization", "Bearer {yourAccessToken}") .header("content-type", "application/json") - .body("{\"user_metadata\": {\"displayName\": \"J-vald3z\"}") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{"user_metadata": {"displayName": "J-vald3z"}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -309,8 +320,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer {yourAccessToken}", @"content-type": @"application/json" }; @@ -334,8 +347,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users/user_id", @@ -345,7 +360,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{\"user_metadata\": {\"displayName\": \"J-vald3z\"}", + CURLOPT_POSTFIELDS => "{"user_metadata": {"displayName": "J-vald3z"}", CURLOPT_HTTPHEADER => [ "authorization: Bearer {yourAccessToken}", "content-type: application/json" @@ -361,12 +376,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"user_metadata\": {\"displayName\": \"J-vald3z\"}" +payload = "{"user_metadata": {"displayName": "J-vald3z"}" headers = { 'authorization': "Bearer {yourAccessToken}", @@ -378,8 +395,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/users/user_id", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -392,11 +411,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Patch.new(url) request["authorization"] = 'Bearer {yourAccessToken}' request["content-type"] = 'application/json' -request.body = "{\"user_metadata\": {\"displayName\": \"J-vald3z\"}" +request.body = "{"user_metadata": {"displayName": "J-vald3z"}" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "authorization": "Bearer {yourAccessToken}", @@ -422,20 +443,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + vous devez remplacer `{yourAccessToken}` par un [jeton d’accès à Management API](/docs/fr-ca/api/management/v2/concepts/tokens). @@ -540,7 +550,7 @@ L’identifiant unique de l’utilisateur est le `user_id`. Voici un exemple de
    -](/docs/images/ + diff --git a/main/docs/fr-ca/secure/tokens/access-tokens/get-access-tokens.mdx b/main/docs/fr-ca/secure/tokens/access-tokens/get-access-tokens.mdx index 317f66aab..6ac596d53 100644 --- a/main/docs/fr-ca/secure/tokens/access-tokens/get-access-tokens.mdx +++ b/main/docs/fr-ca/secure/tokens/access-tokens/get-access-tokens.mdx @@ -10,6 +10,7 @@ permalink: "get-access-tokens" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Pour accéder à votre API, vous devez demander un [jeton d’accès](/docs/fr-ca/secure/tokens/access-tokens) lors de l’authentification d’un utilisateur. @@ -26,19 +27,25 @@ Pour demander un jeton d’accès, effectuez une requête POST au jeton [URL](/d #### Exemple de requête POST au jeton URL -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=client_credentials \ --data client_id=YOUR_CLIENT_ID \ --data client_secret=YOUR_CLIENT_SECRET \ - --data audience=YOUR_API_IDENTIFIER`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data audience=YOUR_API_IDENTIFIER +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&audience=YOUR_API_IDENTIFIER", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -65,12 +72,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&audience=YOUR_API_IDENTIFIER") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -88,8 +99,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -115,8 +128,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -141,8 +156,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -155,8 +172,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -171,8 +190,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&audience=YOUR_API_IDENTIFIER" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -198,20 +219,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ##### Paramètres diff --git a/main/docs/fr-ca/secure/tokens/access-tokens/management-api-access-tokens/get-management-api-access-tokens-for-production.mdx b/main/docs/fr-ca/secure/tokens/access-tokens/management-api-access-tokens/get-management-api-access-tokens-for-production.mdx index 567d69f5d..135c5caf6 100644 --- a/main/docs/fr-ca/secure/tokens/access-tokens/management-api-access-tokens/get-management-api-access-tokens-for-production.mdx +++ b/main/docs/fr-ca/secure/tokens/access-tokens/management-api-access-tokens/get-management-api-access-tokens-for-production.mdx @@ -10,6 +10,7 @@ permalink: "get-management-api-access-tokens-for-production" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Pour lancer des appels fréquents et programmés dans un environnement de production, vous devez créer un processus au niveau de votre système dorsal, qui vous fournira automatiquement un jeton (et ainsi simuler un jeton permanent). @@ -24,19 +25,25 @@ Un produit permettant aux clients d’effectuer des tâches administratives." ct Les données doivent être au format suivant : -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=client_credentials \ --data 'client_id={yourClientId}' \ --data 'client_secret={yourClientSecret}' \ - --data 'audience=https://{yourDomain}/api/v2/'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data 'audience=https://{yourDomain}/api/v2/' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=client_credentials&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&audience=https%3A%2F%2F{yourDomain}%2Fapi%2Fv2%2F", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -63,12 +70,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=client_credentials&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&audience=https%3A%2F%2F{yourDomain}%2Fapi%2Fv2%2F") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -86,8 +97,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -113,8 +126,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -139,8 +154,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -153,8 +170,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -169,8 +188,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=client_credentials&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&audience=https%3A%2F%2F{yourDomain}%2Fapi%2Fv2%2F" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -196,20 +217,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + N’oubliez pas de mettre à jour ``{yourClientSecret}`` avec le secret du client dans l’[onglet Settings (Paramètres) de votre application](https://manage.auth0.com/#/applications/{yourClientId}/settings). @@ -268,7 +278,7 @@ Comme alternative aux appels HTTP, vous pouvez utiliser la bibliothèque [node-a Pour utiliser ce jeton, il faut l’inclure dans l’en-tête `Authorization` de votre demande. - + ```bash cURL lines curl --request POST \ --url http:///%7BmgmtApiEndpoint%7D \ @@ -448,20 +458,26 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + Par exemple, pour [obtenir toutes les applications](/docs/fr-ca/api/management/v2#!/Clients/get_clients) procédez comme suit : -export const codeExample11 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/clients' \ --header 'authorization: Bearer {yourAccessToken}' \ - --header 'content-type: application/json'`; -export const codeExample12 = `var client = new RestClient("https://{yourDomain}/api/v2/clients"); + --header 'content-type: application/json' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/clients"); var request = new RestRequest(Method.GET); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer {yourAccessToken}"); -IRestResponse response = client.Execute(request);`; -export const codeExample13 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -486,12 +502,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample14 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/clients") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/clients") .header("content-type", "application/json") .header("authorization", "Bearer {yourAccessToken}") - .asString();`; -export const codeExample15 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -503,8 +523,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample16 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer {yourAccessToken}" }; @@ -525,8 +547,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/clients", @@ -551,8 +575,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -566,8 +592,10 @@ conn.request("GET", "/{yourDomain}/api/v2/clients", headers=headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -582,8 +610,10 @@ request["content-type"] = 'application/json' request["authorization"] = 'Bearer {yourAccessToken}' response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -606,20 +636,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + diff --git a/main/docs/fr-ca/secure/tokens/refresh-tokens/configure-refresh-token-rotation.mdx b/main/docs/fr-ca/secure/tokens/refresh-tokens/configure-refresh-token-rotation.mdx index bb988b1e2..9d57d7749 100644 --- a/main/docs/fr-ca/secure/tokens/refresh-tokens/configure-refresh-token-rotation.mdx +++ b/main/docs/fr-ca/secure/tokens/refresh-tokens/configure-refresh-token-rotation.mdx @@ -25,7 +25,7 @@ Les scénarios de migration tiennent compte de la révocation automatique des je 1. Allez à [Dashboard > Applications](https://manage.auth0.com/#/applications). 2. Sélectionnez l’application que vous souhaitez configurer. 3. Allez dans l’onglet **Paramètres**. -4. Sous **Rotation des jetons d’actualisation**, activez **Autoriser la rotation des jetons d’actualisation**.](/docs/images/ +4. Sous **Rotation des jetons d’actualisation**, activez **Autoriser la rotation des jetons d’actualisation**. ![Dashboard (Tableau de bord) Applications Onglet Application Settings (Paramètres d’application) Refresh Token Rotation (Rotation du jeton d’actualisation)](/images/fr-ca/cdy7uua7fh8z/Rk6i8MUVWZG34P7K6aurb/f416d625f4aa157a89238d975736086a/2025-02-27_16-05-01.png) diff --git a/main/docs/fr-ca/secure/tokens/refresh-tokens/get-refresh-tokens.mdx b/main/docs/fr-ca/secure/tokens/refresh-tokens/get-refresh-tokens.mdx index cb01490ce..56678548f 100644 --- a/main/docs/fr-ca/secure/tokens/refresh-tokens/get-refresh-tokens.mdx +++ b/main/docs/fr-ca/secure/tokens/refresh-tokens/get-refresh-tokens.mdx @@ -10,6 +10,7 @@ permalink: "get-refresh-tokens" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Pour obtenir un jeton d’actualisation, vous devez inclure [la permission](/docs/fr-ca/get-started/apis/scopes)`offline_access` lorsque vous lancez une demande d’authentification via le point de terminaison `/autorize`. Assurez-vous d’initier l’accès hors ligne dans votre API. Pour en savoir plus, veuillez consulter [Paramètres de l’API](/docs/fr-ca/get-started/apis/api-settings). @@ -29,20 +30,26 @@ Le jeton d’actualisation est stocké dans la session. Ensuite, lorsque la sess Une fois que l’utilisateur a bien été authentifié, l’application sera redirigée vers le `redirect_uri`, avec un `code` dans le cadre de l'URL : `{https://yourApp/callback}?code=BPPLN3Z4qCTvSNOy`. Vous pouvez échanger ce code avec un jeton d’accès en utilisant le point de terminaison `/oauth/token`. -export const codeExample2 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=authorization_code \ --data 'client_id={yourClientId}' \ --data 'client_secret={yourClientSecret}' \ --data 'code={yourAuthorizationCode}' \ - --data 'redirect_uri={https://yourApp/callback}'`; -export const codeExample3 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data 'redirect_uri={https://yourApp/callback}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=authorization_code&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&code=%7ByourAuthorizationCode%7D&redirect_uri={https://yourApp/callback}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample4 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -69,12 +76,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample5 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=authorization_code&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&code=%7ByourAuthorizationCode%7D&redirect_uri={https://yourApp/callback}") - .asString();`; -export const codeExample6 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -93,8 +104,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample7 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -121,8 +134,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample8 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -147,8 +162,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample9 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -161,8 +178,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample10 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -177,8 +196,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=authorization_code&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&code=%7ByourAuthorizationCode%7D&redirect_uri={https://yourApp/callback}" response = http.request(request) -puts response.read_body`; -export const codeExample11 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -205,20 +226,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + La réponse doit contenir un jeton d’accès et un jeton d’actualisation. diff --git a/main/docs/fr-ca/secure/tokens/refresh-tokens/multi-resource-refresh-token/configure-and-implement-multi-resource-refresh-token.mdx b/main/docs/fr-ca/secure/tokens/refresh-tokens/multi-resource-refresh-token/configure-and-implement-multi-resource-refresh-token.mdx index f6520ac42..ee633a8ac 100644 --- a/main/docs/fr-ca/secure/tokens/refresh-tokens/multi-resource-refresh-token/configure-and-implement-multi-resource-refresh-token.mdx +++ b/main/docs/fr-ca/secure/tokens/refresh-tokens/multi-resource-refresh-token/configure-and-implement-multi-resource-refresh-token.mdx @@ -10,6 +10,7 @@ permalink: "configure-and-implement-multi-resource-refresh-token" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; @@ -53,7 +54,9 @@ The audience and scope properties must correspond to an existing application in For existing applications, make a PATCH call to the [Update a Client](/docs/fr-ca/api/management/v2/clients/patch-clients-by-id) endpoint. To create a new application, make a POST call to the [Create a Client](/docs/fr-ca/api/management/v2/clients/post-clients) endpoint: -export const codeExample1 = `curl --request PATCH \ + +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/clients//{yourClientId}' \ --header 'authorization: Bearer {yourMgmtApiAccessToken}' \ --header 'content-type: application/json' \ @@ -77,14 +80,38 @@ export const codeExample1 = `curl --request PATCH \ } ] } -}'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/clients//{yourClientId}"); +}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/clients//{yourClientId}"); var request = new RestRequest(Method.PATCH); request.AddHeader("authorization", "Bearer {yourMgmtApiAccessToken}"); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\n \"refresh_token\": {\n \"expiration_type\": \"expiring\",\n \"rotation_type\": \"rotating\",\n \"token_lifetime\": 31557600,\n \"idle_token_lifetime\": 2592000,\n \"leeway\": 0,\n \"infinite_token_lifetime\": false,\n \"infinite_idle_token_lifetime\": false,\n \"policies\": [\n {\n \"audience\": \"https://api.example.com\",\n \"scope\": [\"read:data\"]\n },\n {\n \"audience\": \"https://billing.example.com\",\n \"scope\": [\"read:billing\"]\n }\n ]\n }\n}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ + "refresh_token": { + "expiration_type": "expiring", + "rotation_type": "rotating", + "token_lifetime": 31557600, + "idle_token_lifetime": 2592000, + "leeway": 0, + "infinite_token_lifetime": false, + "infinite_idle_token_lifetime": false, + "policies": [ + { + "audience": "https://api.example.com", + "scope": ["read:data"] + }, + { + "audience": "https://billing.example.com", + "scope": ["read:billing"] + } + ] + } +}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -97,7 +124,27 @@ func main() { url := "https://{yourDomain}/api/v2/clients//{yourClientId}" - payload := strings.NewReader("{\n \"refresh_token\": {\n \"expiration_type\": \"expiring\",\n \"rotation_type\": \"rotating\",\n \"token_lifetime\": 31557600,\n \"idle_token_lifetime\": 2592000,\n \"leeway\": 0,\n \"infinite_token_lifetime\": false,\n \"infinite_idle_token_lifetime\": false,\n \"policies\": [\n {\n \"audience\": \"https://api.example.com\",\n \"scope\": [\"read:data\"]\n },\n {\n \"audience\": \"https://billing.example.com\",\n \"scope\": [\"read:billing\"]\n }\n ]\n }\n}") + payload := strings.NewReader("{ + "refresh_token": { + "expiration_type": "expiring", + "rotation_type": "rotating", + "token_lifetime": 31557600, + "idle_token_lifetime": 2592000, + "leeway": 0, + "infinite_token_lifetime": false, + "infinite_idle_token_lifetime": false, + "policies": [ + { + "audience": "https://api.example.com", + "scope": ["read:data"] + }, + { + "audience": "https://billing.example.com", + "scope": ["read:billing"] + } + ] + } +}") req, _ := http.NewRequest("PATCH", url, payload) @@ -112,13 +159,37 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/clients//{yourClientId}") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/clients//{yourClientId}") .header("authorization", "Bearer {yourMgmtApiAccessToken}") .header("content-type", "application/json") - .body("{\n \"refresh_token\": {\n \"expiration_type\": \"expiring\",\n \"rotation_type\": \"rotating\",\n \"token_lifetime\": 31557600,\n \"idle_token_lifetime\": 2592000,\n \"leeway\": 0,\n \"infinite_token_lifetime\": false,\n \"infinite_idle_token_lifetime\": false,\n \"policies\": [\n {\n \"audience\": \"https://api.example.com\",\n \"scope\": [\"read:data\"]\n },\n {\n \"audience\": \"https://billing.example.com\",\n \"scope\": [\"read:billing\"]\n }\n ]\n }\n}") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ + "refresh_token": { + "expiration_type": "expiring", + "rotation_type": "rotating", + "token_lifetime": 31557600, + "idle_token_lifetime": 2592000, + "leeway": 0, + "infinite_token_lifetime": false, + "infinite_idle_token_lifetime": false, + "policies": [ + { + "audience": "https://api.example.com", + "scope": ["read:data"] + }, + { + "audience": "https://billing.example.com", + "scope": ["read:billing"] + } + ] + } +}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -148,8 +219,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer {yourMgmtApiAccessToken}", @"content-type": @"application/json" }; @@ -174,8 +247,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/clients//{yourClientId}", @@ -185,7 +260,27 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{\n \"refresh_token\": {\n \"expiration_type\": \"expiring\",\n \"rotation_type\": \"rotating\",\n \"token_lifetime\": 31557600,\n \"idle_token_lifetime\": 2592000,\n \"leeway\": 0,\n \"infinite_token_lifetime\": false,\n \"infinite_idle_token_lifetime\": false,\n \"policies\": [\n {\n \"audience\": \"https://api.example.com\",\n \"scope\": [\"read:data\"]\n },\n {\n \"audience\": \"https://billing.example.com\",\n \"scope\": [\"read:billing\"]\n }\n ]\n }\n}", + CURLOPT_POSTFIELDS => "{ + "refresh_token": { + "expiration_type": "expiring", + "rotation_type": "rotating", + "token_lifetime": 31557600, + "idle_token_lifetime": 2592000, + "leeway": 0, + "infinite_token_lifetime": false, + "infinite_idle_token_lifetime": false, + "policies": [ + { + "audience": "https://api.example.com", + "scope": ["read:data"] + }, + { + "audience": "https://billing.example.com", + "scope": ["read:billing"] + } + ] + } +}", CURLOPT_HTTPHEADER => [ "authorization: Bearer {yourMgmtApiAccessToken}", "content-type: application/json" @@ -201,12 +296,34 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\n \"refresh_token\": {\n \"expiration_type\": \"expiring\",\n \"rotation_type\": \"rotating\",\n \"token_lifetime\": 31557600,\n \"idle_token_lifetime\": 2592000,\n \"leeway\": 0,\n \"infinite_token_lifetime\": false,\n \"infinite_idle_token_lifetime\": false,\n \"policies\": [\n {\n \"audience\": \"https://api.example.com\",\n \"scope\": [\"read:data\"]\n },\n {\n \"audience\": \"https://billing.example.com\",\n \"scope\": [\"read:billing\"]\n }\n ]\n }\n}" +payload = "{ + "refresh_token": { + "expiration_type": "expiring", + "rotation_type": "rotating", + "token_lifetime": 31557600, + "idle_token_lifetime": 2592000, + "leeway": 0, + "infinite_token_lifetime": false, + "infinite_idle_token_lifetime": false, + "policies": [ + { + "audience": "https://api.example.com", + "scope": ["read:data"] + }, + { + "audience": "https://billing.example.com", + "scope": ["read:billing"] + } + ] + } +}" headers = { 'authorization': "Bearer {yourMgmtApiAccessToken}", @@ -218,8 +335,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/clients//{yourClientId}", payload, h res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -232,11 +351,33 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Patch.new(url) request["authorization"] = 'Bearer {yourMgmtApiAccessToken}' request["content-type"] = 'application/json' -request.body = "{\n \"refresh_token\": {\n \"expiration_type\": \"expiring\",\n \"rotation_type\": \"rotating\",\n \"token_lifetime\": 31557600,\n \"idle_token_lifetime\": 2592000,\n \"leeway\": 0,\n \"infinite_token_lifetime\": false,\n \"infinite_idle_token_lifetime\": false,\n \"policies\": [\n {\n \"audience\": \"https://api.example.com\",\n \"scope\": [\"read:data\"]\n },\n {\n \"audience\": \"https://billing.example.com\",\n \"scope\": [\"read:billing\"]\n }\n ]\n }\n}" +request.body = "{ + "refresh_token": { + "expiration_type": "expiring", + "rotation_type": "rotating", + "token_lifetime": 31557600, + "idle_token_lifetime": 2592000, + "leeway": 0, + "infinite_token_lifetime": false, + "infinite_idle_token_lifetime": false, + "policies": [ + { + "audience": "https://api.example.com", + "scope": ["read:data"] + }, + { + "audience": "https://billing.example.com", + "scope": ["read:billing"] + } + ] + } +}" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "authorization": "Bearer {yourMgmtApiAccessToken}", @@ -281,20 +422,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + Sample response: @@ -342,7 +472,9 @@ If you do not receive a refresh token, confirm that: Once the refresh token is issued, you can request access tokens for any API and scopes defined in both the initial authentication and the MRRT policy. For example: -export const codeExample11 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/json' \ --data '{ @@ -351,13 +483,23 @@ export const codeExample11 = `curl --request POST \ "refresh_token": "${refreshToken}", "audience": "https://billing.example.com", "scope": "read:billing write:billing" -}'`; -export const codeExample12 = `var client = new RestClient("https://{yourDomain}/oauth/token"); +}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\n \"grant_type\": \"refresh_token\",\n \"client_id\": \"{yourClientId}\",\n \"refresh_token\": \"${refreshToken}\",\n \"audience\": \"https://billing.example.com\",\n \"scope\": \"read:billing write:billing\"\n}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample13 = `package main +request.AddParameter("application/json", "{ + "grant_type": "refresh_token", + "client_id": "{yourClientId}", + "refresh_token": "${refreshToken}", + "audience": "https://billing.example.com", + "scope": "read:billing write:billing" +}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -370,7 +512,13 @@ func main() { url := "https://{yourDomain}/oauth/token" - payload := strings.NewReader("{\n \"grant_type\": \"refresh_token\",\n \"client_id\": \"{yourClientId}\",\n \"refresh_token\": \"${refreshToken}\",\n \"audience\": \"https://billing.example.com\",\n \"scope\": \"read:billing write:billing\"\n}") + payload := strings.NewReader("{ + "grant_type": "refresh_token", + "client_id": "{yourClientId}", + "refresh_token": "${refreshToken}", + "audience": "https://billing.example.com", + "scope": "read:billing write:billing" +}") req, _ := http.NewRequest("POST", url, payload) @@ -384,12 +532,22 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample14 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/json") - .body("{\n \"grant_type\": \"refresh_token\",\n \"client_id\": \"{yourClientId}\",\n \"refresh_token\": \"${refreshToken}\",\n \"audience\": \"https://billing.example.com\",\n \"scope\": \"read:billing write:billing\"\n}") - .asString();`; -export const codeExample15 = `var axios = require("axios").default; + .body("{ + "grant_type": "refresh_token", + "client_id": "{yourClientId}", + "refresh_token": "${refreshToken}", + "audience": "https://billing.example.com", + "scope": "read:billing write:billing" +}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -408,8 +566,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample16 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json" }; NSDictionary *parameters = @{ @"grant_type": @"refresh_token", @@ -437,8 +597,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -448,7 +610,13 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{\n \"grant_type\": \"refresh_token\",\n \"client_id\": \"{yourClientId}\",\n \"refresh_token\": \"${refreshToken}\",\n \"audience\": \"https://billing.example.com\",\n \"scope\": \"read:billing write:billing\"\n}", + CURLOPT_POSTFIELDS => "{ + "grant_type": "refresh_token", + "client_id": "{yourClientId}", + "refresh_token": "${refreshToken}", + "audience": "https://billing.example.com", + "scope": "read:billing write:billing" +}", CURLOPT_HTTPHEADER => [ "content-type: application/json" ], @@ -463,12 +631,20 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\n \"grant_type\": \"refresh_token\",\n \"client_id\": \"{yourClientId}\",\n \"refresh_token\": \"${refreshToken}\",\n \"audience\": \"https://billing.example.com\",\n \"scope\": \"read:billing write:billing\"\n}" +payload = "{ + "grant_type": "refresh_token", + "client_id": "{yourClientId}", + "refresh_token": "${refreshToken}", + "audience": "https://billing.example.com", + "scope": "read:billing write:billing" +}" headers = { 'content-type': "application/json" } @@ -477,8 +653,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -490,11 +668,19 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["content-type"] = 'application/json' -request.body = "{\n \"grant_type\": \"refresh_token\",\n \"client_id\": \"{yourClientId}\",\n \"refresh_token\": \"${refreshToken}\",\n \"audience\": \"https://billing.example.com\",\n \"scope\": \"read:billing write:billing\"\n}" +request.body = "{ + "grant_type": "refresh_token", + "client_id": "{yourClientId}", + "refresh_token": "${refreshToken}", + "audience": "https://billing.example.com", + "scope": "read:billing write:billing" +}" response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/json"] let parameters = [ @@ -524,20 +710,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +  To learn more, read [Use Refresh tokens](/docs/fr-ca/secure/tokens/refresh-tokens/use-refresh-tokens). diff --git a/main/docs/fr-ca/secure/tokens/refresh-tokens/revoke-refresh-tokens.mdx b/main/docs/fr-ca/secure/tokens/refresh-tokens/revoke-refresh-tokens.mdx index 0b0696b92..1e50f8b5d 100644 --- a/main/docs/fr-ca/secure/tokens/refresh-tokens/revoke-refresh-tokens.mdx +++ b/main/docs/fr-ca/secure/tokens/refresh-tokens/revoke-refresh-tokens.mdx @@ -10,6 +10,7 @@ permalink: "revoke-refresh-tokens" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Vous pouvez révoquer les jetons d’actualisation si ceux-ci sont compromis. Auth0 s’occupe de révoquer les jetons comme s’ils avaient été potentiellement compromis par des entités malveillantes. @@ -56,16 +57,22 @@ Pour révoquer un jeton d’actualisation, envoyez une demande `POST` à `https: Le point de terminaison `/oauth/revoke` révoque toute l’autorisation, pas seulement un jeton en particulier. Utilisez le point de terminaison `/api/v2/device-credentials` pour révoquer les jetons d’actualisation. L’API valide d’abord les identifiants de l’application, puis vérifie si le jeton a été fourni à l’application qui fait la demande de révocation. Si cette validation échoue, la demande est refusée et l’application est informée de l’erreur. Ensuite, l’API invalide le jeton. L’invalidation a lieu immédiatement et le jeton ne peut plus être utilisé après la révocation. Chaque demande de révocation invalide tous les jetons qui ont été émis pour la même autorisation. -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/revoke' \ --header 'content-type: application/json' \ - --data '{ "client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "token": "{yourRefreshToken}" }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/oauth/revoke"); + --data '{ "client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "token": "{yourRefreshToken}" }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/revoke"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{ \"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"token\": \"{yourRefreshToken}\" }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "token": "{yourRefreshToken}" }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -78,7 +85,7 @@ func main() { url := "https://{yourDomain}/oauth/revoke" - payload := strings.NewReader("{ \"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"token\": \"{yourRefreshToken}\" }") + payload := strings.NewReader("{ "client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "token": "{yourRefreshToken}" }") req, _ := http.NewRequest("POST", url, payload) @@ -92,12 +99,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/revoke") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/revoke") .header("content-type", "application/json") - .body("{ \"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"token\": \"{yourRefreshToken}\" }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "token": "{yourRefreshToken}" }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -114,8 +125,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json" }; NSDictionary *parameters = @{ @"client_id": @"{yourClientId}", @@ -141,8 +154,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/revoke", @@ -152,7 +167,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{ \"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"token\": \"{yourRefreshToken}\" }", + CURLOPT_POSTFIELDS => "{ "client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "token": "{yourRefreshToken}" }", CURLOPT_HTTPHEADER => [ "content-type: application/json" ], @@ -167,12 +182,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"token\": \"{yourRefreshToken}\" }" +payload = "{ "client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "token": "{yourRefreshToken}" }" headers = { 'content-type': "application/json" } @@ -181,8 +198,10 @@ conn.request("POST", "/{yourDomain}/oauth/revoke", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -194,11 +213,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["content-type"] = 'application/json' -request.body = "{ \"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"token\": \"{yourRefreshToken}\" }" +request.body = "{ "client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "token": "{yourRefreshToken}" }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/json"] let parameters = [ @@ -226,20 +247,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + Où : diff --git a/main/docs/fr-ca/secure/tokens/refresh-tokens/use-refresh-tokens.mdx b/main/docs/fr-ca/secure/tokens/refresh-tokens/use-refresh-tokens.mdx index a62061551..88ddb1ebe 100644 --- a/main/docs/fr-ca/secure/tokens/refresh-tokens/use-refresh-tokens.mdx +++ b/main/docs/fr-ca/secure/tokens/refresh-tokens/use-refresh-tokens.mdx @@ -10,6 +10,7 @@ permalink: "use-refresh-tokens" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Les jetons d’actualisation sont utilisés pour demander un nouveau jeton d’accès et/ou un nouveau jeton d’ID pour un utilisateur sans qu’il soit nécessaire de se réauthentifier. @@ -25,20 +26,26 @@ Pour en savoir plus sur les méthodes d’authentification disponibles pour l’ ### Utiliser l’authentification Basic -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'authorization: Basic {yourApplicationCredentials}' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=refresh_token \ --data 'client_id={yourClientId}' \ - --data 'refresh_token={yourRefreshToken}'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data 'refresh_token={yourRefreshToken}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddHeader("authorization", "Basic {yourApplicationCredentials}"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=refresh_token&client_id={yourClientId}&refresh_token=%7ByourRefreshToken%7D", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -66,13 +73,17 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .header("authorization", "Basic {yourApplicationCredentials}") .body("grant_type=refresh_token&client_id={yourClientId}&refresh_token=%7ByourRefreshToken%7D") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -92,8 +103,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded", @"authorization": @"Basic {yourApplicationCredentials}" }; @@ -119,8 +132,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -146,8 +161,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -163,8 +180,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -180,8 +199,10 @@ request["authorization"] = 'Basic {yourApplicationCredentials}' request.body = "grant_type=refresh_token&client_id={yourClientId}&refresh_token=%7ByourRefreshToken%7D" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/x-www-form-urlencoded", @@ -209,36 +230,31 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ### Utiliser l’authentification Post -export const codeExample11 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=refresh_token \ --data 'client_id={yourClientId}' \ --data 'client_secret={yourClientSecret}' \ - --data 'refresh_token={yourRefreshToken}'`; -export const codeExample12 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data 'refresh_token={yourRefreshToken}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=refresh_token&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&refresh_token=%7ByourRefreshToken%7D", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample13 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -265,12 +281,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample14 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=refresh_token&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&refresh_token=%7ByourRefreshToken%7D") - .asString();`; -export const codeExample15 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -288,8 +308,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample16 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -315,8 +337,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -341,8 +365,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -355,8 +381,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -371,8 +399,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=refresh_token&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&refresh_token=%7ByourRefreshToken%7D" response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -398,20 +428,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ### Définition des paramètres diff --git a/main/docs/fr-ca/troubleshoot/product-lifecycle/past-migrations/link-user-accounts-with-access-tokens-migration.mdx b/main/docs/fr-ca/troubleshoot/product-lifecycle/past-migrations/link-user-accounts-with-access-tokens-migration.mdx index bdbe7d0fe..e83ffb909 100644 --- a/main/docs/fr-ca/troubleshoot/product-lifecycle/past-migrations/link-user-accounts-with-access-tokens-migration.mdx +++ b/main/docs/fr-ca/troubleshoot/product-lifecycle/past-migrations/link-user-accounts-with-access-tokens-migration.mdx @@ -10,6 +10,7 @@ permalink: "link-user-accounts-with-access-tokens-migration" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Auparavant, il était possible d’utiliser des jetons d’ID pour associer et désassocier des comptes d’utilisateurs dans certains cas d’utilisation. Auth0 supprime cette fonctionnalité. Vous devrez désormais utiliser des jetons d’accès dans tous les cas. @@ -221,7 +222,6 @@ export const codeExample4 = ` // get an ID Token - En utilisant la nouvelle méthode avec un jeton d’accès, votre code ressemblera à ceci : export const codeExample5 = ` // get an Access Token @@ -257,18 +257,24 @@ Si vous obtenez un jeton d’accès pour l’association de comptes qui contient Toutefois, cette nouvelle méthode offre une alternative. Vous utiliserez toujours un jeton d’accès contenant la permission `update:users` pour vous authentifier auprès de l’API, mais dans la charge utile de la demande, vous pouvez envoyer le jeton d’ID du compte secondaire (au lieu du `user_id` et du `provider`). -export const codeExample6 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/api/v2/users/PRIMARY_ACCOUNT_USER_ID/identities' \ --header 'authorization: Bearer ACCESS_TOKEN' \ --header 'content-type: application/json' \ - --data '{"link_with":"SECONDARY_ACCOUNT_ID_TOKEN"}'`; -export const codeExample7 = `var client = new RestClient("https://{yourDomain}/api/v2/users/PRIMARY_ACCOUNT_USER_ID/identities"); + --data '{"link_with":"SECONDARY_ACCOUNT_ID_TOKEN"}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users/PRIMARY_ACCOUNT_USER_ID/identities"); var request = new RestRequest(Method.POST); request.AddHeader("authorization", "Bearer ACCESS_TOKEN"); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\"link_with\":\"SECONDARY_ACCOUNT_ID_TOKEN\"}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample8 = `package main +request.AddParameter("application/json", "{"link_with":"SECONDARY_ACCOUNT_ID_TOKEN"}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -281,7 +287,7 @@ func main() { url := "https://{yourDomain}/api/v2/users/PRIMARY_ACCOUNT_USER_ID/identities" - payload := strings.NewReader("{\"link_with\":\"SECONDARY_ACCOUNT_ID_TOKEN\"}") + payload := strings.NewReader("{"link_with":"SECONDARY_ACCOUNT_ID_TOKEN"}") req, _ := http.NewRequest("POST", url, payload) @@ -296,13 +302,17 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample9 = `HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/users/PRIMARY_ACCOUNT_USER_ID/identities") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/users/PRIMARY_ACCOUNT_USER_ID/identities") .header("authorization", "Bearer ACCESS_TOKEN") .header("content-type", "application/json") - .body("{\"link_with\":\"SECONDARY_ACCOUNT_ID_TOKEN\"}") - .asString();`; -export const codeExample10 = `var axios = require("axios").default; + .body("{"link_with":"SECONDARY_ACCOUNT_ID_TOKEN"}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -315,8 +325,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample11 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer ACCESS_TOKEN", @"content-type": @"application/json" }; @@ -341,8 +353,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample12 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users/PRIMARY_ACCOUNT_USER_ID/identities", @@ -352,7 +366,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{\"link_with\":\"SECONDARY_ACCOUNT_ID_TOKEN\"}", + CURLOPT_POSTFIELDS => "{"link_with":"SECONDARY_ACCOUNT_ID_TOKEN"}", CURLOPT_HTTPHEADER => [ "authorization: Bearer ACCESS_TOKEN", "content-type: application/json" @@ -368,12 +382,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample13 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"link_with\":\"SECONDARY_ACCOUNT_ID_TOKEN\"}" +payload = "{"link_with":"SECONDARY_ACCOUNT_ID_TOKEN"}" headers = { 'authorization': "Bearer ACCESS_TOKEN", @@ -385,8 +401,10 @@ conn.request("POST", "/{yourDomain}/api/v2/users/PRIMARY_ACCOUNT_USER_ID/identit res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample14 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -399,11 +417,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["authorization"] = 'Bearer ACCESS_TOKEN' request["content-type"] = 'application/json' -request.body = "{\"link_with\":\"SECONDARY_ACCOUNT_ID_TOKEN\"}" +request.body = "{"link_with":"SECONDARY_ACCOUNT_ID_TOKEN"}" response = http.request(request) -puts response.read_body`; -export const codeExample15 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "authorization": "Bearer ACCESS_TOKEN", @@ -430,20 +450,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + Les conditions suivantes doivent être remplies : diff --git a/main/docs/get-started/apis/add-api-permissions.mdx b/main/docs/get-started/apis/add-api-permissions.mdx index 5151c1c7e..90ddbeac2 100644 --- a/main/docs/get-started/apis/add-api-permissions.mdx +++ b/main/docs/get-started/apis/add-api-permissions.mdx @@ -11,6 +11,8 @@ title: Add API Permissions --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + You can add permissions to an API using the Auth0 Dashboard or the Management API. @@ -39,20 +41,26 @@ Patching the permissions with an empty object removes the permissions completely Make a `PATCH` call to the [Update Resource Server endpoint](https://auth0.com/docs/api/management/v2/resource-servers/patch-resource-servers-by-id). Be sure to replace `API_ID`, `MGMT_API_ACCESS_TOKEN`, `PERMISSION_NAME`, and `PERMISSION_DESC` placeholder values with your API ID, Management API Access Token, permission name(s), and permission description(s), respectively. Be sure not to use any reserved permission names (see Reserved names section). -export const codeExample1 = `curl --request PATCH \ + +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/resource-servers/API_ID' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{ "scopes": [ { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" }, { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" } ] }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/resource-servers/API_ID"); + --data '{ "scopes": [ { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" }, { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" } ] }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/resource-servers/API_ID"); var request = new RestRequest(Method.PATCH); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{ \"scopes\": [ { \"value\": \"PERMISSION_NAME\", \"description\": \"PERMISSION_DESC\" }, { \"value\": \"PERMISSION_NAME\", \"description\": \"PERMISSION_DESC\" } ] }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "scopes": [ { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" }, { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" } ] }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -65,7 +73,7 @@ func main() { url := "https://{yourDomain}/api/v2/resource-servers/API_ID" - payload := strings.NewReader("{ \"scopes\": [ { \"value\": \"PERMISSION_NAME\", \"description\": \"PERMISSION_DESC\" }, { \"value\": \"PERMISSION_NAME\", \"description\": \"PERMISSION_DESC\" } ] }") + payload := strings.NewReader("{ "scopes": [ { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" }, { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" } ] }") req, _ := http.NewRequest("PATCH", url, payload) @@ -81,14 +89,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/resource-servers/API_ID") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/resource-servers/API_ID") .header("content-type", "application/json") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ \"scopes\": [ { \"value\": \"PERMISSION_NAME\", \"description\": \"PERMISSION_DESC\" }, { \"value\": \"PERMISSION_NAME\", \"description\": \"PERMISSION_DESC\" } ] }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "scopes": [ { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" }, { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" } ] }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -110,8 +122,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @@ -137,8 +151,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/resource-servers/API_ID", @@ -148,7 +164,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{ \"scopes\": [ { \"value\": \"PERMISSION_NAME\", \"description\": \"PERMISSION_DESC\" }, { \"value\": \"PERMISSION_NAME\", \"description\": \"PERMISSION_DESC\" } ] }", + CURLOPT_POSTFIELDS => "{ "scopes": [ { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" }, { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" } ] }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "cache-control: no-cache", @@ -165,12 +181,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"scopes\": [ { \"value\": \"PERMISSION_NAME\", \"description\": \"PERMISSION_DESC\" }, { \"value\": \"PERMISSION_NAME\", \"description\": \"PERMISSION_DESC\" } ] }" +payload = "{ "scopes": [ { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" }, { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" } ] }" headers = { 'content-type': "application/json", @@ -183,8 +201,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/resource-servers/API_ID", payload, h res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -198,11 +218,13 @@ request = Net::HTTP::Patch.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ \"scopes\": [ { \"value\": \"PERMISSION_NAME\", \"description\": \"PERMISSION_DESC\" }, { \"value\": \"PERMISSION_NAME\", \"description\": \"PERMISSION_DESC\" } ] }" +request.body = "{ "scopes": [ { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" }, { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" } ] }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -239,20 +261,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + diff --git a/main/docs/get-started/apis/delete-api-permissions.mdx b/main/docs/get-started/apis/delete-api-permissions.mdx index a6b9ba266..0a9ecdbd2 100644 --- a/main/docs/get-started/apis/delete-api-permissions.mdx +++ b/main/docs/get-started/apis/delete-api-permissions.mdx @@ -11,6 +11,8 @@ title: Delete API Permissions --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + You can delete permissions from an API using the Auth0 Dashboard or the Management API. ## Use the Dashboard @@ -26,20 +28,26 @@ You can delete permissions from an API using the Access Token, permission name(s), and permission description(s), respectively. -export const codeExample1 = `curl --request PATCH \ + +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/resource-servers/API_ID' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{ "scopes": [ { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" }, { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" } ] }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/resource-servers/API_ID"); + --data '{ "scopes": [ { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" }, { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" } ] }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/resource-servers/API_ID"); var request = new RestRequest(Method.PATCH); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{ \"scopes\": [ { \"value\": \"PERMISSION_NAME\", \"description\": \"PERMISSION_DESC\" }, { \"value\": \"PERMISSION_NAME\", \"description\": \"PERMISSION_DESC\" } ] }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "scopes": [ { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" }, { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" } ] }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -52,7 +60,7 @@ func main() { url := "https://{yourDomain}/api/v2/resource-servers/API_ID" - payload := strings.NewReader("{ \"scopes\": [ { \"value\": \"PERMISSION_NAME\", \"description\": \"PERMISSION_DESC\" }, { \"value\": \"PERMISSION_NAME\", \"description\": \"PERMISSION_DESC\" } ] }") + payload := strings.NewReader("{ "scopes": [ { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" }, { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" } ] }") req, _ := http.NewRequest("PATCH", url, payload) @@ -68,14 +76,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/resource-servers/API_ID") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/resource-servers/API_ID") .header("content-type", "application/json") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ \"scopes\": [ { \"value\": \"PERMISSION_NAME\", \"description\": \"PERMISSION_DESC\" }, { \"value\": \"PERMISSION_NAME\", \"description\": \"PERMISSION_DESC\" } ] }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "scopes": [ { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" }, { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" } ] }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -97,8 +109,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @@ -124,8 +138,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/resource-servers/API_ID", @@ -135,7 +151,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{ \"scopes\": [ { \"value\": \"PERMISSION_NAME\", \"description\": \"PERMISSION_DESC\" }, { \"value\": \"PERMISSION_NAME\", \"description\": \"PERMISSION_DESC\" } ] }", + CURLOPT_POSTFIELDS => "{ "scopes": [ { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" }, { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" } ] }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "cache-control: no-cache", @@ -152,12 +168,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"scopes\": [ { \"value\": \"PERMISSION_NAME\", \"description\": \"PERMISSION_DESC\" }, { \"value\": \"PERMISSION_NAME\", \"description\": \"PERMISSION_DESC\" } ] }" +payload = "{ "scopes": [ { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" }, { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" } ] }" headers = { 'content-type': "application/json", @@ -170,8 +188,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/resource-servers/API_ID", payload, h res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -185,11 +205,13 @@ request = Net::HTTP::Patch.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ \"scopes\": [ { \"value\": \"PERMISSION_NAME\", \"description\": \"PERMISSION_DESC\" }, { \"value\": \"PERMISSION_NAME\", \"description\": \"PERMISSION_DESC\" } ] }" +request.body = "{ "scopes": [ { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" }, { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" } ] }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -226,20 +248,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
    song_idsongnamesongname user_id
    diff --git a/main/docs/get-started/apis/enable-role-based-access-control-for-apis.mdx b/main/docs/get-started/apis/enable-role-based-access-control-for-apis.mdx index a8a7c03b8..38ab017a0 100644 --- a/main/docs/get-started/apis/enable-role-based-access-control-for-apis.mdx +++ b/main/docs/get-started/apis/enable-role-based-access-control-for-apis.mdx @@ -11,6 +11,8 @@ title: Enable Role-Based Access Control for APIs --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + You can enable [role-based access control (RBAC)](/docs/manage-users/access-control/rbac) using the Auth0 Dashboard or the Management API. This enables the API Authorization Core feature set. When RBAC is enabled, the `scope` claim of the access token includes an intersection of the requested permissions and the permissions assigned to the user, regardless of whether permissions are also included in the access token. When RBAC is disabled, an application can request any permission defined for the API, and the `scope` claim includes all requested permissions. @@ -41,20 +43,26 @@ If you configure any [Actions](/docs/customize/actions) that modify access token To enable RBAC using the Management API, make a PATCH request to the [Update a resource server endpoint](https://auth0.com/docs/api/management/v2/resource-servers/patch-resource-servers-by-id). In the PATCH request, set `enforce_policies` to `true`: -export const codeExample1 = `curl --request PATCH \ + +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/resource-servers/API_ID' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{ "enforce_policies": "true", "token_dialect": "TOKEN_DIALECT" }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/resource-servers/API_ID"); + --data '{ "enforce_policies": "true", "token_dialect": "TOKEN_DIALECT" }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/resource-servers/API_ID"); var request = new RestRequest(Method.PATCH); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{ \"enforce_policies\": \"true\", \"token_dialect\": \"TOKEN_DIALECT\" }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "enforce_policies": "true", "token_dialect": "TOKEN_DIALECT" }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -67,7 +75,7 @@ func main() { url := "https://{yourDomain}/api/v2/resource-servers/API_ID" - payload := strings.NewReader("{ \"enforce_policies\": \"true\", \"token_dialect\": \"TOKEN_DIALECT\" }") + payload := strings.NewReader("{ "enforce_policies": "true", "token_dialect": "TOKEN_DIALECT" }") req, _ := http.NewRequest("PATCH", url, payload) @@ -83,14 +91,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/resource-servers/API_ID") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/resource-servers/API_ID") .header("content-type", "application/json") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ \"enforce_policies\": \"true\", \"token_dialect\": \"TOKEN_DIALECT\" }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "enforce_policies": "true", "token_dialect": "TOKEN_DIALECT" }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -107,8 +119,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @@ -135,8 +149,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/resource-servers/API_ID", @@ -146,7 +162,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{ \"enforce_policies\": \"true\", \"token_dialect\": \"TOKEN_DIALECT\" }", + CURLOPT_POSTFIELDS => "{ "enforce_policies": "true", "token_dialect": "TOKEN_DIALECT" }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "cache-control: no-cache", @@ -163,12 +179,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"enforce_policies\": \"true\", \"token_dialect\": \"TOKEN_DIALECT\" }" +payload = "{ "enforce_policies": "true", "token_dialect": "TOKEN_DIALECT" }" headers = { 'content-type': "application/json", @@ -181,8 +199,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/resource-servers/API_ID", payload, h res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -196,11 +216,13 @@ request = Net::HTTP::Patch.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ \"enforce_policies\": \"true\", \"token_dialect\": \"TOKEN_DIALECT\" }" +request.body = "{ "enforce_policies": "true", "token_dialect": "TOKEN_DIALECT" }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -231,20 +253,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + Replace `API_ID`, `MGMT_API_ACCESS_TOKEN`, and `TOKEN_DIALECT` with their respective values, as shown in the following table: diff --git a/main/docs/get-started/applications/confidential-and-public-applications/update-application-ownership.mdx b/main/docs/get-started/applications/confidential-and-public-applications/update-application-ownership.mdx index 96ae5a984..d8b5817f2 100644 --- a/main/docs/get-started/applications/confidential-and-public-applications/update-application-ownership.mdx +++ b/main/docs/get-started/applications/confidential-and-public-applications/update-application-ownership.mdx @@ -14,24 +14,32 @@ title: Update Application Ownership --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + You can use Auth0's Management API to update application ownership, which allows you to specify whether an application is registered with Auth0 as a first-party or third-party application. Make a `PATCH` call to the [Update a Client endpoint](https://auth0.com/docs/api/management/v2#!/Clients/patch_clients_by_id). Be sure to replace `{yourClientId}`, `{yourMgmtApiAccessToken}`, and `{ownershipBoolean}` placeholder values with your client ID, Management API Access Token, and boolean representing the application's ownership, respectively. -export const codeExample1 = `curl --request PATCH \ + +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/clients/%7ByourClientId%7D' \ --header 'authorization: Bearer {yourMgmtApiAccessToken}' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{ "is_first_party": "{ownershipBoolean}" }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/clients/%7ByourClientId%7D"); + --data '{ "is_first_party": "{ownershipBoolean}" }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/clients/%7ByourClientId%7D"); var request = new RestRequest(Method.PATCH); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer {yourMgmtApiAccessToken}"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{ \"is_first_party\": \"{ownershipBoolean}\" }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "is_first_party": "{ownershipBoolean}" }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -44,7 +52,7 @@ func main() { url := "https://{yourDomain}/api/v2/clients/%7ByourClientId%7D" - payload := strings.NewReader("{ \"is_first_party\": \"{ownershipBoolean}\" }") + payload := strings.NewReader("{ "is_first_party": "{ownershipBoolean}" }") req, _ := http.NewRequest("PATCH", url, payload) @@ -60,14 +68,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/clients/%7ByourClientId%7D") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/clients/%7ByourClientId%7D") .header("content-type", "application/json") .header("authorization", "Bearer {yourMgmtApiAccessToken}") .header("cache-control", "no-cache") - .body("{ \"is_first_party\": \"{ownershipBoolean}\" }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "is_first_party": "{ownershipBoolean}" }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -84,8 +96,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer {yourMgmtApiAccessToken}", @@ -111,8 +125,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/clients/%7ByourClientId%7D", @@ -122,7 +138,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{ \"is_first_party\": \"{ownershipBoolean}\" }", + CURLOPT_POSTFIELDS => "{ "is_first_party": "{ownershipBoolean}" }", CURLOPT_HTTPHEADER => [ "authorization: Bearer {yourMgmtApiAccessToken}", "cache-control: no-cache", @@ -139,12 +155,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"is_first_party\": \"{ownershipBoolean}\" }" +payload = "{ "is_first_party": "{ownershipBoolean}" }" headers = { 'content-type': "application/json", @@ -157,8 +175,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/clients/%7ByourClientId%7D", payload res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -172,11 +192,13 @@ request = Net::HTTP::Patch.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer {yourMgmtApiAccessToken}' request["cache-control"] = 'no-cache' -request.body = "{ \"is_first_party\": \"{ownershipBoolean}\" }" +request.body = "{ "is_first_party": "{ownershipBoolean}" }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -204,20 +226,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
    diff --git a/main/docs/get-started/applications/confidential-and-public-applications/user-consent-and-third-party-applications.mdx b/main/docs/get-started/applications/confidential-and-public-applications/user-consent-and-third-party-applications.mdx index 3b1b5e498..272102470 100644 --- a/main/docs/get-started/applications/confidential-and-public-applications/user-consent-and-third-party-applications.mdx +++ b/main/docs/get-started/applications/confidential-and-public-applications/user-consent-and-third-party-applications.mdx @@ -11,6 +11,8 @@ title: User Consent and Third-Party Applications --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + The [OIDC](/docs/authenticate/protocols/openid-connect-protocol)-conformant authentication pipeline supports defining resource servers (such as APIs) as entities separate from applications. This lets you decouple APIs from the applications that consume them, and also lets you define [third-party applications](/docs/get-started/applications/confidential-and-public-applications/first-party-and-third-party-applications) that allow external parties to securely access protected resources behind your API. ## Consent dialog @@ -30,11 +32,6 @@ client_id=some_third_party_client &state=... ``` - - - - - Will result in this user consent dialog: ![Authorization - User consent and applications - consent-dialog](/docs/images/cdy7uua7fh8z/5Cz3aZKw8RRVlMkc5Zl6x7/62ac54cbc470286d5c2139d47c604ebc/2025-02-28_14-57-52.png) @@ -55,20 +52,26 @@ If you would like to display the **Description** field instead, you can do so by To set the **use_scope_descriptions_for_consent** flag, you will need to make the appropriate call to the API: -export const codeExample1 = `curl --request PATCH \ + +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/tenants/settings' \ --header 'authorization: Bearer API2_ACCESS_TOKEN' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{ "flags": { "use_scope_descriptions_for_consent": true } }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/tenants/settings"); + --data '{ "flags": { "use_scope_descriptions_for_consent": true } }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/tenants/settings"); var request = new RestRequest(Method.PATCH); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer API2_ACCESS_TOKEN"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{ \"flags\": { \"use_scope_descriptions_for_consent\": true } }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "flags": { "use_scope_descriptions_for_consent": true } }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -81,7 +84,7 @@ func main() { url := "https://{yourDomain}/api/v2/tenants/settings" - payload := strings.NewReader("{ \"flags\": { \"use_scope_descriptions_for_consent\": true } }") + payload := strings.NewReader("{ "flags": { "use_scope_descriptions_for_consent": true } }") req, _ := http.NewRequest("PATCH", url, payload) @@ -97,14 +100,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/tenants/settings") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/tenants/settings") .header("content-type", "application/json") .header("authorization", "Bearer API2_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ \"flags\": { \"use_scope_descriptions_for_consent\": true } }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "flags": { "use_scope_descriptions_for_consent": true } }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -121,8 +128,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer API2_ACCESS_TOKEN", @@ -148,8 +157,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/tenants/settings", @@ -159,7 +170,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{ \"flags\": { \"use_scope_descriptions_for_consent\": true } }", + CURLOPT_POSTFIELDS => "{ "flags": { "use_scope_descriptions_for_consent": true } }", CURLOPT_HTTPHEADER => [ "authorization: Bearer API2_ACCESS_TOKEN", "cache-control: no-cache", @@ -176,12 +187,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"flags\": { \"use_scope_descriptions_for_consent\": true } }" +payload = "{ "flags": { "use_scope_descriptions_for_consent": true } }" headers = { 'content-type': "application/json", @@ -194,8 +207,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/tenants/settings", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -209,11 +224,13 @@ request = Net::HTTP::Patch.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer API2_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ \"flags\": { \"use_scope_descriptions_for_consent\": true } }" +request.body = "{ "flags": { "use_scope_descriptions_for_consent": true } }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -241,20 +258,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ## Handle rejected permissions @@ -267,11 +273,6 @@ Location: https://fabrikam.com/contoso_social# &state=... ``` - - - - - ## Skip consent for first-party applications First-party applications can skip the consent dialog, but only if the API they are trying to access on behalf of the user has the **Allow Skipping User Consent** option enabled. diff --git a/main/docs/get-started/applications/confidential-and-public-applications/view-application-ownership.mdx b/main/docs/get-started/applications/confidential-and-public-applications/view-application-ownership.mdx index 2fed77591..39c7cf68b 100644 --- a/main/docs/get-started/applications/confidential-and-public-applications/view-application-ownership.mdx +++ b/main/docs/get-started/applications/confidential-and-public-applications/view-application-ownership.mdx @@ -12,19 +12,27 @@ title: View Application Ownership --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + You can use Auth0's Management API to check whether an application is registered with Auth0 as a first-party or third-party application. Make a `GET` call to the [Get a Client endpoint](https://auth0.com/docs/api/management/v2#!/Clients/get_clients_by_id). Be sure to replace `{yourClientId}` and `{yourMgmtApiAccessToken}` placeholder values with your client ID and Management API Access Token, respectively. -export const codeExample1 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/clients/%7ByourClientId%7D?fields=is_first_party&include_fields=true' \ - --header 'authorization: Bearer {yourMgmtApiAccessToken}'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/clients/%7ByourClientId%7D?fields=is_first_party&include_fields=true"); + --header 'authorization: Bearer {yourMgmtApiAccessToken}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/clients/%7ByourClientId%7D?fields=is_first_party&include_fields=true"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer {yourMgmtApiAccessToken}"); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -48,11 +56,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/clients/%7ByourClientId%7D?fields=is_first_party&include_fields=true") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/clients/%7ByourClientId%7D?fields=is_first_party&include_fields=true") .header("authorization", "Bearer {yourMgmtApiAccessToken}") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -65,8 +77,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer {yourMgmtApiAccessToken}" }; @@ -86,8 +100,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/clients/%7ByourClientId%7D?fields=is_first_party&include_fields=true", @@ -111,8 +127,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -123,8 +141,10 @@ conn.request("GET", "/{yourDomain}/api/v2/clients/%7ByourClientId%7D?fields=is_f res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -138,8 +158,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer {yourMgmtApiAccessToken}' response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer {yourMgmtApiAccessToken}"] @@ -159,20 +181,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
    diff --git a/main/docs/get-started/applications/dynamic-client-registration.mdx b/main/docs/get-started/applications/dynamic-client-registration.mdx index ce55c7b0b..6edf3034d 100644 --- a/main/docs/get-started/applications/dynamic-client-registration.mdx +++ b/main/docs/get-started/applications/dynamic-client-registration.mdx @@ -12,6 +12,8 @@ title: Dynamic Application Registration --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + You can dynamically register third-party applications for your tenant. This feature is based on the [OpenID Connect Dynamic Client Registration specification](https://openid.net/specs/openid-connect-registration-1_0.html). ## Enable dynamic client registration @@ -28,20 +30,26 @@ To do so, go to [Dashboard > Settings > Advanced](https://manage.auth0.com/#/ten Alternatively, you can update this flag using the Management API [`/Tenant/patch_settings`](https://auth0.com/docs/api/management/v2#!/Tenants/patch_settings) endpoint. -export const codeExample1 = `curl --request PATCH \ + +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/tenants/settings' \ --header 'authorization: Bearer API2_ACCESS_TOKEN' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{ "flags": { "enable_dynamic_client_registration": true } }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/tenants/settings"); + --data '{ "flags": { "enable_dynamic_client_registration": true } }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/tenants/settings"); var request = new RestRequest(Method.PATCH); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer API2_ACCESS_TOKEN"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{ \"flags\": { \"enable_dynamic_client_registration\": true } }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "flags": { "enable_dynamic_client_registration": true } }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -54,7 +62,7 @@ func main() { url := "https://{yourDomain}/api/v2/tenants/settings" - payload := strings.NewReader("{ \"flags\": { \"enable_dynamic_client_registration\": true } }") + payload := strings.NewReader("{ "flags": { "enable_dynamic_client_registration": true } }") req, _ := http.NewRequest("PATCH", url, payload) @@ -70,14 +78,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/tenants/settings") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/tenants/settings") .header("content-type", "application/json") .header("authorization", "Bearer API2_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ \"flags\": { \"enable_dynamic_client_registration\": true } }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "flags": { "enable_dynamic_client_registration": true } }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -94,8 +106,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer API2_ACCESS_TOKEN", @@ -121,8 +135,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/tenants/settings", @@ -132,7 +148,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{ \"flags\": { \"enable_dynamic_client_registration\": true } }", + CURLOPT_POSTFIELDS => "{ "flags": { "enable_dynamic_client_registration": true } }", CURLOPT_HTTPHEADER => [ "authorization: Bearer API2_ACCESS_TOKEN", "cache-control: no-cache", @@ -149,12 +165,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"flags\": { \"enable_dynamic_client_registration\": true } }" +payload = "{ "flags": { "enable_dynamic_client_registration": true } }" headers = { 'content-type': "application/json", @@ -167,8 +185,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/tenants/settings", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -182,11 +202,13 @@ request = Net::HTTP::Patch.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer API2_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ \"flags\": { \"enable_dynamic_client_registration\": true } }" +request.body = "{ "flags": { "enable_dynamic_client_registration": true } }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -214,20 +236,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + You need to update the `API2_ACCESS_TOKEN` with a valid token with the scope `update:tenant_settings`. To learn more, read [Management API Access Tokens](/docs/secure/tokens/access-tokens/management-api-access-tokens). @@ -241,16 +252,22 @@ To dynamically register an application with Auth0, you need to send an HTTP `POS To create an application with the name `My Dynamic application` and the callback URLs `https://application.example.com/callback` and `https://application.example.com/callback2`, use the following snippet: -export const codeExample11 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oidc/register' \ --header 'content-type: application/json' \ - --data '{"client_name":"My Dynamic Application","redirect_uris": ["https://application.example.com/callback", "https://application.example.com/callback2"]}'`; -export const codeExample12 = `var client = new RestClient("https://{yourDomain}/oidc/register"); + --data '{"client_name":"My Dynamic Application","redirect_uris": ["https://application.example.com/callback", "https://application.example.com/callback2"]}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oidc/register"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\"client_name\":\"My Dynamic Application\",\"redirect_uris\": [\"https://application.example.com/callback\", \"https://application.example.com/callback2\"]}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample13 = `package main +request.AddParameter("application/json", "{"client_name":"My Dynamic Application","redirect_uris": ["https://application.example.com/callback", "https://application.example.com/callback2"]}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -263,7 +280,7 @@ func main() { url := "https://{yourDomain}/oidc/register" - payload := strings.NewReader("{\"client_name\":\"My Dynamic Application\",\"redirect_uris\": [\"https://application.example.com/callback\", \"https://application.example.com/callback2\"]}") + payload := strings.NewReader("{"client_name":"My Dynamic Application","redirect_uris": ["https://application.example.com/callback", "https://application.example.com/callback2"]}") req, _ := http.NewRequest("POST", url, payload) @@ -277,12 +294,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample14 = `HttpResponse response = Unirest.post("https://{yourDomain}/oidc/register") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oidc/register") .header("content-type", "application/json") - .body("{\"client_name\":\"My Dynamic Application\",\"redirect_uris\": [\"https://application.example.com/callback\", \"https://application.example.com/callback2\"]}") - .asString();`; -export const codeExample15 = `var axios = require("axios").default; + .body("{"client_name":"My Dynamic Application","redirect_uris": ["https://application.example.com/callback", "https://application.example.com/callback2"]}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -301,8 +322,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample16 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json" }; NSDictionary *parameters = @{ @"client_name": @"My Dynamic Application", @@ -327,8 +350,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oidc/register", @@ -338,7 +363,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{\"client_name\":\"My Dynamic Application\",\"redirect_uris\": [\"https://application.example.com/callback\", \"https://application.example.com/callback2\"]}", + CURLOPT_POSTFIELDS => "{"client_name":"My Dynamic Application","redirect_uris": ["https://application.example.com/callback", "https://application.example.com/callback2"]}", CURLOPT_HTTPHEADER => [ "content-type: application/json" ], @@ -353,12 +378,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"client_name\":\"My Dynamic Application\",\"redirect_uris\": [\"https://application.example.com/callback\", \"https://application.example.com/callback2\"]}" +payload = "{"client_name":"My Dynamic Application","redirect_uris": ["https://application.example.com/callback", "https://application.example.com/callback2"]}" headers = { 'content-type': "application/json" } @@ -367,8 +394,10 @@ conn.request("POST", "/{yourDomain}/oidc/register", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -380,11 +409,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["content-type"] = 'application/json' -request.body = "{\"client_name\":\"My Dynamic Application\",\"redirect_uris\": [\"https://application.example.com/callback\", \"https://application.example.com/callback2\"]}" +request.body = "{"client_name":"My Dynamic Application","redirect_uris": ["https://application.example.com/callback", "https://application.example.com/callback2"]}" response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/json"] let parameters = [ @@ -411,20 +442,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + Where: @@ -450,11 +470,6 @@ Content-Type: application/json } ``` - - - - - Where: * **client_id**: Unique client identifier. This is the ID you will use while configuring your apps to use Auth0. It is generated by the system and it cannot be modified. @@ -484,11 +499,6 @@ export const codeExample21 = `https://{yourDomain}/authorize? - - - - - Where: * **audience** (optional): The target API for which the Application is requesting access on behalf of the user. Set this parameter if you need API access. @@ -507,11 +517,6 @@ export const codeExample22 = ` - - - - - This call will redirect the user to Auth0, and upon successful authentication, back to your application (specifically to the **redirect_uri**). If you need API access, then following the authentication, you need to extract the access token from the hash fragment of the URL, and use it to make calls to the API, by passing it as a `Bearer` token in the `Authorization` header of the HTTP request. diff --git a/main/docs/get-started/applications/remove-applications.mdx b/main/docs/get-started/applications/remove-applications.mdx index 033c5791e..3089b76c6 100644 --- a/main/docs/get-started/applications/remove-applications.mdx +++ b/main/docs/get-started/applications/remove-applications.mdx @@ -12,6 +12,8 @@ title: Remove Applications --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + You can remove an application using the Auth0 Dashboard or the Management API. Once confirmed, this operation cannot be undone. ## Use the Dashboard @@ -25,14 +27,20 @@ You can remove an application using the client ID and Management API access token, respectively. -export const codeExample1 = `curl --request DELETE \ + +```bash cURL +curl --request DELETE \ --url 'https://{yourDomain}/api/v2/clients/%7ByourClientId%7D' \ - --header 'authorization: Bearer {yourMgmtApiToken}'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/clients/%7ByourClientId%7D"); + --header 'authorization: Bearer {yourMgmtApiToken}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/clients/%7ByourClientId%7D"); var request = new RestRequest(Method.DELETE); request.AddHeader("authorization", "Bearer {yourMgmtApiToken}"); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -56,11 +64,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.delete("https://{yourDomain}/api/v2/clients/%7ByourClientId%7D") +} +``` +```java Java +HttpResponse response = Unirest.delete("https://{yourDomain}/api/v2/clients/%7ByourClientId%7D") .header("authorization", "Bearer {yourMgmtApiToken}") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'DELETE', @@ -72,8 +84,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer {yourMgmtApiToken}" }; @@ -93,8 +107,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/clients/%7ByourClientId%7D", @@ -118,8 +134,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -130,8 +148,10 @@ conn.request("DELETE", "/{yourDomain}/api/v2/clients/%7ByourClientId%7D", header res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -145,8 +165,10 @@ request = Net::HTTP::Delete.new(url) request["authorization"] = 'Bearer {yourMgmtApiToken}' response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer {yourMgmtApiToken}"] @@ -166,20 +188,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
    diff --git a/main/docs/get-started/applications/rotate-client-secret.mdx b/main/docs/get-started/applications/rotate-client-secret.mdx index cdf09d35d..41d3d57f0 100644 --- a/main/docs/get-started/applications/rotate-client-secret.mdx +++ b/main/docs/get-started/applications/rotate-client-secret.mdx @@ -12,6 +12,8 @@ title: Rotate Client Secrets --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + You can change an application's client secret using the Auth0 Dashboard or the Auth0 Management API. When you rotate a client secret, you must update any authorized applications with the new value. @@ -44,16 +46,22 @@ Secrets can be stored in a list (or similar structure) until they're no longer n 1. Call the Management API [Rotate a client secret](https://auth0.com/docs/api/management/v2#!/Clients/post_rotate_secret) endpoint. Replace the `YOUR_CLIENT_ID` and `MGMT_API_ACCESS_TOKEN` placeholder values with your client ID and Management API access token, respectively. -export const codeExample1 = ` curl --request POST \ + +```bash cURL + curl --request POST \ --url 'https://{yourDomain}/api/v2/clients/%7ByourClientId%7D/rotate-secret' \ --header 'authorization: Bearer {yourMgmtApiAccessToken}' -`; -export const codeExample2 = ` var client = new RestClient("https://{yourDomain}/api/v2/clients/%7ByourClientId%7D/rotate-secret"); + +``` +```csharp C# + var client = new RestClient("https://{yourDomain}/api/v2/clients/%7ByourClientId%7D/rotate-secret"); var request = new RestRequest(Method.POST); request.AddHeader("authorization", "Bearer {yourMgmtApiAccessToken}"); IRestResponse response = client.Execute(request); -`; -export const codeExample3 = ` package main + +``` +```go Go + package main import ( "fmt" @@ -78,12 +86,16 @@ fmt.Println(res) fmt.Println(string(body)) } -`; -export const codeExample4 = ` HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/clients/%7ByourClientId%7D/rotate-secret") + +``` +```java Java + HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/clients/%7ByourClientId%7D/rotate-secret") .header("authorization", "Bearer {yourMgmtApiAccessToken}") .asString(); -`; -export const codeExample5 = ` var axios = require("axios").default; + +``` +```javascript Node.JS + var axios = require("axios").default; var options = { method: 'POST', @@ -96,8 +108,10 @@ axios.request(options).then(function (response) { }).catch(function (error) { console.error(error); }); -`; -export const codeExample6 = ` #import + +``` +```obj-c Obj-C + #import NSDictionary *headers = @{ @"authorization": @"Bearer {yourMgmtApiAccessToken}" }; @@ -118,8 +132,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request } }]; [dataTask resume]; -`; -export const codeExample7 = ` $curl = curl_init(); + +``` +```php PHP + $curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/clients/%7ByourClientId%7D/rotate-secret", @@ -144,8 +160,10 @@ if ($err) { } else { echo $response; } -`; -export const codeExample8 = ` import http.client + +``` +```python Python + import http.client conn = http.client.HTTPSConnection("") @@ -158,8 +176,10 @@ res = conn.getresponse() data = res.read() print(data.decode("utf-8")) -`; -export const codeExample9 = ` require 'uri' + +``` +```ruby Ruby + require 'uri' require 'net/http' require 'openssl' url = URI("https://{yourDomain}/api/v2/clients/%7ByourClientId%7D/rotate-secret") @@ -170,8 +190,10 @@ request = Net::HTTP::Post.new(url) request["authorization"] = 'Bearer {yourMgmtApiAccessToken}' response = http.request(request) puts response.read_body -`; -export const codeExample10 = ` import Foundation + +``` +```swift Swift + import Foundation let headers = ["authorization": "Bearer {yourMgmtApiAccessToken}"] @@ -192,20 +214,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: }) dataTask.resume() -`; - - - - - - - - - - - - - + +``` +
    diff --git a/main/docs/get-started/applications/update-grant-types.mdx b/main/docs/get-started/applications/update-grant-types.mdx index 3139ae396..cdeca6ecc 100644 --- a/main/docs/get-started/applications/update-grant-types.mdx +++ b/main/docs/get-started/applications/update-grant-types.mdx @@ -12,6 +12,8 @@ title: Update Grant Types --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + You can change your application's grant types using the Auth0 Dashboard or the Management API. ## Use the Dashboard @@ -28,20 +30,26 @@ You can change your application's grant types using the client ID, Management API access token, and desired grant type, respectively. -export const codeExample1 = `curl --request PATCH \ + +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/clients/%7ByourClientId%7D' \ --header 'authorization: Bearer {yourMgmtApiAccessToken}' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{ "grant_types": "{grantTypes}" }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/clients/%7ByourClientId%7D"); + --data '{ "grant_types": "{grantTypes}" }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/clients/%7ByourClientId%7D"); var request = new RestRequest(Method.PATCH); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer {yourMgmtApiAccessToken}"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{ \"grant_types\": \"{grantTypes}\" }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "grant_types": "{grantTypes}" }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -54,7 +62,7 @@ func main() { url := "https://{yourDomain}/api/v2/clients/%7ByourClientId%7D" - payload := strings.NewReader("{ \"grant_types\": \"{grantTypes}\" }") + payload := strings.NewReader("{ "grant_types": "{grantTypes}" }") req, _ := http.NewRequest("PATCH", url, payload) @@ -70,14 +78,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/clients/%7ByourClientId%7D") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/clients/%7ByourClientId%7D") .header("content-type", "application/json") .header("authorization", "Bearer {yourMgmtApiAccessToken}") .header("cache-control", "no-cache") - .body("{ \"grant_types\": \"{grantTypes}\" }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "grant_types": "{grantTypes}" }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -94,8 +106,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer {yourMgmtApiAccessToken}", @@ -121,8 +135,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/clients/%7ByourClientId%7D", @@ -132,7 +148,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{ \"grant_types\": \"{grantTypes}\" }", + CURLOPT_POSTFIELDS => "{ "grant_types": "{grantTypes}" }", CURLOPT_HTTPHEADER => [ "authorization: Bearer {yourMgmtApiAccessToken}", "cache-control: no-cache", @@ -149,12 +165,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"grant_types\": \"{grantTypes}\" }" +payload = "{ "grant_types": "{grantTypes}" }" headers = { 'content-type': "application/json", @@ -167,8 +185,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/clients/%7ByourClientId%7D", payload res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -182,11 +202,13 @@ request = Net::HTTP::Patch.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer {yourMgmtApiAccessToken}' request["cache-control"] = 'no-cache' -request.body = "{ \"grant_types\": \"{grantTypes}\" }" +request.body = "{ "grant_types": "{grantTypes}" }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -214,20 +236,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
    diff --git a/main/docs/get-started/architecture-scenarios/mobile-api/part-3.mdx b/main/docs/get-started/architecture-scenarios/mobile-api/part-3.mdx index 146f5cdeb..e4daa11a6 100644 --- a/main/docs/get-started/architecture-scenarios/mobile-api/part-3.mdx +++ b/main/docs/get-started/architecture-scenarios/mobile-api/part-3.mdx @@ -11,6 +11,8 @@ title: API and Mobile Configuration (Mobile Apps + API) --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + In this section we will see how we can implement an API for our scenario. @@ -98,11 +100,6 @@ export const codeExample1 = `https://{yourDomain}/authorize? - - - - - The `GET` request to the authorization URL should include the following values:
    @@ -154,27 +151,28 @@ Location: https://{yourDomain}/callback?code=AUTHORIZATION_CODE`; - - - - - Next you can exchange the `authorization_code` from the response for an Access Token that can be used to call your API. Perform a `POST` request to the [Token URL](https://auth0.com/docs/api/authentication#authorization-code-pkce-) including the following data: -export const codeExample3 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=authorization_code \ --data 'client_id={yourClientId}' \ --data code_verified=YOUR_GENERATED_CODE_VERIFIER \ --data code=YOUR_AUTHORIZATION_CODE \ - --data 'redirect_uri=https://{https://yourApp/callback}'`; -export const codeExample4 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data 'redirect_uri=https://{https://yourApp/callback}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=authorization_code&client_id={yourClientId}&code_verified=YOUR_GENERATED_CODE_VERIFIER&code=YOUR_AUTHORIZATION_CODE&redirect_uri=https%3A%2F%2F{https://yourApp/callback}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample5 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -201,12 +199,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample6 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=authorization_code&client_id={yourClientId}&code_verified=YOUR_GENERATED_CODE_VERIFIER&code=YOUR_AUTHORIZATION_CODE&redirect_uri=https%3A%2F%2F{https://yourApp/callback}") - .asString();`; -export const codeExample7 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -225,8 +227,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample8 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -253,8 +257,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample9 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -279,8 +285,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample10 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -293,8 +301,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample11 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -309,8 +319,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=authorization_code&client_id={yourClientId}&code_verified=YOUR_GENERATED_CODE_VERIFIER&code=YOUR_AUTHORIZATION_CODE&redirect_uri=https%3A%2F%2F{https://yourApp/callback}" response = http.request(request) -puts response.read_body`; -export const codeExample12 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -337,20 +349,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
    @@ -394,11 +395,6 @@ The response from the Token URL will contain: } ``` - - - - - * **access_token**: An Access Token for the API, specified by the `audience`. * **refresh_token**: A [Refresh Token](/docs/secure/tokens/refresh-tokens) will only be present if you included the `offline_access` scope AND enabled **Allow Offline Access** for your API in the Dashboard. * **id_token**: An ID Token JWT containing user profile information. @@ -428,11 +424,6 @@ To retrieve the [User Profile](https://auth0.com/docs/api/authentication?http#u } ``` - - - - - [See the implementation in Android.](/docs/get-started/architecture-scenarios/mobile-api/mobile-implementation-android#3-get-the-user-profile) ### Display UI Elements Conditionally Based on Scope @@ -461,14 +452,20 @@ A [Refresh Token](/docs/secure/tokens/refresh-tokens) will only be present if Your request should include: -export const codeExample13 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ - --header 'content-type: application/x-www-form-urlencoded'`; -export const codeExample14 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --header 'content-type: application/x-www-form-urlencoded' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); -IRestResponse response = client.Execute(request);`; -export const codeExample15 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -492,11 +489,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample16 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") - .asString();`; -export const codeExample17 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -508,8 +509,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample18 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -532,8 +535,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample19 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -557,8 +562,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample20 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -569,8 +576,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", headers=headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample21 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -584,8 +593,10 @@ request = Net::HTTP::Post.new(url) request["content-type"] = 'application/x-www-form-urlencoded' response = http.request(request) -puts response.read_body`; -export const codeExample22 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -608,20 +619,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
    @@ -657,9 +657,4 @@ The response will include the new Access Token: } ``` - - - - - [See the implementation in Android.](/docs/get-started/architecture-scenarios/mobile-api/mobile-implementation-android#store-the-credentials) \ No newline at end of file diff --git a/main/docs/get-started/authentication-and-authorization-flow/authorization-code-flow-with-pkce/add-login-using-the-authorization-code-flow-with-pkce.mdx b/main/docs/get-started/authentication-and-authorization-flow/authorization-code-flow-with-pkce/add-login-using-the-authorization-code-flow-with-pkce.mdx index f055e6981..599be95a3 100644 --- a/main/docs/get-started/authentication-and-authorization-flow/authorization-code-flow-with-pkce/add-login-using-the-authorization-code-flow-with-pkce.mdx +++ b/main/docs/get-started/authentication-and-authorization-flow/authorization-code-flow-with-pkce/add-login-using-the-authorization-code-flow-with-pkce.mdx @@ -12,6 +12,8 @@ title: Add Login Using the Authorization Code Flow with PKCE --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + You can add login to your native, mobile, or single-page app using the Authorization Code Flow with PKCE. To learn how the flow works and why you should use it, read [Authorization Code Flow with Proof Key for Code Exchange (PKCE)](/docs/get-started/authentication-and-authorization-flow/authorization-code-flow-with-pkce). To learn how to call your API from a native, mobile, or single-page app, read [Call Your API Using Authorization Code Flow with PKCE](/docs/get-started/authentication-and-authorization-flow/authorization-code-flow-with-pkce/call-your-api-using-the-authorization-code-flow-with-pkce). To implement the Authorization Code Flow with Proof Key for Code Exchange (PKCE), you can use the following resources: @@ -49,11 +51,6 @@ function base64URLEncode(str) { var verifier = base64URLEncode(crypto.randomBytes(32)); ``` - - - - - ### Java sample ```javascript lines @@ -67,11 +64,6 @@ sr.nextBytes(code); String verifier = Base64.getUrlEncoder().withoutPadding().encodeToString(code); ``` - - - - - ### Android sample ```javascript lines @@ -85,11 +77,6 @@ sr.nextBytes(code); String verifier = Base64.encodeToString(code, Base64.URL_SAFE | Base64.NO_WRAP | Base64.NO_PADDING); ``` - - - - - ### Swift 5 sample ```javascript lines @@ -101,11 +88,6 @@ let verifier = Data(buffer).base64EncodedString() .replacingOccurrences(of: "=", with: "") ``` - - - - - ### Objective-C sample ```obj-c lines @@ -117,11 +99,6 @@ NSString *verifier = [[[[data base64EncodedStringWithOptions:0] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"="]]; ``` - - - - - ## Create code challenge Generate a `code_challenge` from the `code_verifier` that will be sent to Auth0 to request an `authorization_code`. @@ -139,11 +116,6 @@ function sha256(buffer) { var challenge = base64URLEncode(sha256(verifier)); ``` - - - - - ### Java sample ```java lines @@ -158,11 +130,6 @@ byte[] digest = md.digest(); String challenge = Base64.encodeBase64URLSafeString(digest); ``` - - - - - ### Swift 5 sample ```swift lines @@ -182,11 +149,6 @@ let challenge = hash.base64EncodedString() .replacingOccurrences(of: "=", with: "") ``` - - - - - ### Objective-C sample ```obj-c lines @@ -203,11 +165,6 @@ NSString *challenge = [[[[hash base64EncodedStringWithOptions:0] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"="]]; ``` - - - - - ## Authorize user Request the user's authorization and redirect back to your app with an `authorization_code`. @@ -234,11 +191,6 @@ export const codeExample1 = `https://{yourDomain}/authorize? - - - - - ### Parameters
    @@ -306,11 +258,6 @@ export const codeExample2 = ` - - - - - ### Response If all goes well, you'll receive an `HTTP 302` response. The authorization code is included at the end of the URL: @@ -320,11 +267,6 @@ HTTP/1.1 302 Found Location: {yourCallbackUrl}?code={authorizationCode}&state=xyzABC123 ``` - - - - - ## Request tokens Exchange your `authorization_code` and `code_verifier` for tokens. @@ -333,20 +275,26 @@ Now that you have an Authorization Code, you must exchange it for tokens. Using ### POST to token URL example -export const codeExample3 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=authorization_code \ --data 'client_id={yourClientId}' \ --data 'code_verifier={yourGeneratedCodeVerifier}' \ --data 'code={yourAuthorizationCode}' \ - --data 'redirect_uri={https://yourApp/callback}'`; -export const codeExample4 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data 'redirect_uri={https://yourApp/callback}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=authorization_code&client_id={yourClientId}&code_verifier=%7ByourGeneratedCodeVerifier%7D&code=%7ByourAuthorizationCode%7D&redirect_uri={https://yourApp/callback}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample5 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -373,12 +321,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample6 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=authorization_code&client_id={yourClientId}&code_verifier=%7ByourGeneratedCodeVerifier%7D&code=%7ByourAuthorizationCode%7D&redirect_uri={https://yourApp/callback}") - .asString();`; -export const codeExample7 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -397,8 +349,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample8 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -425,8 +379,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample9 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -451,8 +407,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample10 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -465,8 +423,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample11 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -481,8 +441,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=authorization_code&client_id={yourClientId}&code_verifier=%7ByourGeneratedCodeVerifier%7D&code=%7ByourAuthorizationCode%7D&redirect_uri={https://yourApp/callback}" response = http.request(request) -puts response.read_body`; -export const codeExample12 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -509,20 +471,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ### Parameters @@ -570,11 +521,6 @@ If all goes well, you'll receive an HTTP 200 response with a payload containing } ``` - - - - - Validate your tokens before saving them. To learn how, read [Validate ID Tokens](/docs/secure/tokens/id-tokens/validate-id-tokens) and [Validate Access Tokens](/docs/secure/tokens/access-tokens/validate-access-tokens). @@ -609,11 +555,6 @@ export const codeExample13 = `https://{yourDomain}/authorize? - - - - - Now, when you request tokens, your ID Token will contain the most basic claims. When you decode the ID Token, it will look similar to: ```json lines @@ -626,11 +567,6 @@ Now, when you request tokens, your ID Token will contain the most basic claims. } ``` - - - - - ### Request user's name and profile picture In addition to the usual user authentication, this example shows how to request additional user details, such as name and picture. @@ -648,11 +584,6 @@ export const codeExample14 = `https://{yourDomain}/authorize? - - - - - Now, when you request tokens, your ID token will contain the requested name and picture claims. When you decode the ID token, it will look similar to: ```json lines @@ -667,11 +598,6 @@ Now, when you request tokens, your ID token will contain the requested name and } ``` - - - - - ### Request user log in with GitHub In addition to the usual user authentication, this example shows how to send users directly to a social identity provider, such as GitHub. For this example to work, you need to go to [Auth0 Dashboard > Authentication > Social](https://manage.auth0.com/#/connections/social) and configure the appropriate connection. Get the connection name from the **Settings** tab. @@ -690,11 +616,6 @@ export const codeExample15 = `https://{yourDomain}/authorize? - - - - - Now, when you request tokens, your ID token will contain a `sub` claim with the user's unique ID returned from GitHub. When you decode the ID token, it will look similar to: ```json lines @@ -711,11 +632,6 @@ Now, when you request tokens, your ID token will contain a `sub` claim with the } ``` - - - - - ## Learn more * [OAuth 2.0 Authorization Framework](/docs/authenticate/protocols/oauth) diff --git a/main/docs/get-started/authentication-and-authorization-flow/authorization-code-flow-with-pkce/call-your-api-using-the-authorization-code-flow-with-pkce.mdx b/main/docs/get-started/authentication-and-authorization-flow/authorization-code-flow-with-pkce/call-your-api-using-the-authorization-code-flow-with-pkce.mdx index f12bce8f0..cf7b9e5ed 100644 --- a/main/docs/get-started/authentication-and-authorization-flow/authorization-code-flow-with-pkce/call-your-api-using-the-authorization-code-flow-with-pkce.mdx +++ b/main/docs/get-started/authentication-and-authorization-flow/authorization-code-flow-with-pkce/call-your-api-using-the-authorization-code-flow-with-pkce.mdx @@ -12,6 +12,8 @@ title: Call Your API Using the Authorization Code Flow with PKCE --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + This tutorial helps you call your own API from a native, mobile, or single-page app using the Authorization Code Flow with PKCE. To learn how the flow works and why you should use it, read [Authorization Code Flow with Proof Key for Code Exchange (PKCE)](/docs/get-started/authentication-and-authorization-flow/authorization-code-flow-with-pkce). To learn to add login to your native, mobile, or single-page app, read [Add Login Using Authorization Code Flow with PKCE](/docs/get-started/authentication-and-authorization-flow/authorization-code-flow-with-pkce/add-login-using-the-authorization-code-flow-with-pkce). @@ -72,11 +74,6 @@ function base64URLEncode(str) { var verifier = base64URLEncode(crypto.randomBytes(32)); ``` - - - - - #### Java sample ```java lines @@ -90,11 +87,6 @@ sr.nextBytes(code); String verifier = Base64.getUrlEncoder().withoutPadding().encodeToString(code); ``` - - - - - #### Android sample ```kotlin lines @@ -107,11 +99,6 @@ sr.nextBytes(code); String verifier = Base64.encodeToString(code, Base64.URL_SAFE | Base64.NO_WRAP | Base64.NO_PADDING); ``` - - - - - #### Swift 5 sample ```swift lines @@ -123,11 +110,6 @@ let verifier = Data(buffer).base64EncodedString() .replacingOccurrences(of: "=", with: "") ``` - - - - - #### Objective-C sample ```obj-c lines @@ -139,11 +121,6 @@ NSString *verifier = [[[[data base64EncodedStringWithOptions:0] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"="]]; ``` - - - - - ### Create code challenge Generate a `code_challenge` from the `code_verifier` that will be sent to Auth0 to request an `authorization_code`. @@ -159,11 +136,6 @@ function sha256(buffer) { var challenge = base64URLEncode(sha256(verifier)); ``` - - - - - #### Java sample ```java lines @@ -178,11 +150,6 @@ byte[] digest = md.digest(); String challenge = Base64.encodeBase64URLSafeString(digest); ``` - - - - - #### Swift 5 sample ```swift lines @@ -202,11 +169,6 @@ let challenge = hash.base64EncodedString() .replacingOccurrences(of: "=", with: "") ``` - - - - - #### Objective-C sample ```obj-c lines @@ -223,11 +185,6 @@ NSString *challenge = [[[[hash base64EncodedStringWithOptions:0] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"="]]; ``` - - - - - ### Authorize user Once you've created the `code_verifier` and the `code_challenge`, you must get the user's authorization. This is technically the beginning of the authorization flow, and this step may include one or more of the following processes: @@ -253,11 +210,6 @@ export const codeExample1 = `https://{yourDomain}/authorize? - - - - - ##### Parameters Note that for authorizing a user when calling a custom API, you: @@ -331,11 +283,6 @@ export const codeExample2 = ` - - - - - #### Response If all goes well, you'll receive an `HTTP 302` response. The authorization code is included at the end of the URL: @@ -345,31 +292,32 @@ HTTP/1.1 302 Found Location: {yourCallbackUrl}?code={authorizationCode}&state=xyzABC123 ``` - - - - - ### Request tokens Now that you have an Authorization Code, you must exchange it for tokens. Using the extracted Authorization Code (`code`) from the previous step, you will need to `POST` to the [token URL](https://auth0.com/docs/api/authentication#authorization-code-pkce-) sending along the `code_verifier`. #### Example POST to token URL -export const codeExample3 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=authorization_code \ --data 'client_id={yourClientId}' \ --data 'code_verifier={yourGeneratedCodeVerifier}' \ --data 'code={yourAuthorizationCode}' \ - --data 'redirect_uri={https://yourApp/callback}'`; -export const codeExample4 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data 'redirect_uri={https://yourApp/callback}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=authorization_code&client_id={yourClientId}&code_verifier=%7ByourGeneratedCodeVerifier%7D&code=%7ByourAuthorizationCode%7D&redirect_uri={https://yourApp/callback}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample5 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -396,12 +344,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample6 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=authorization_code&client_id={yourClientId}&code_verifier=%7ByourGeneratedCodeVerifier%7D&code=%7ByourAuthorizationCode%7D&redirect_uri={https://yourApp/callback}") - .asString();`; -export const codeExample7 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -420,8 +372,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample8 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -448,8 +402,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample9 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -474,8 +430,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample10 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -488,8 +446,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample11 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -504,8 +464,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=authorization_code&client_id={yourClientId}&code_verifier=%7ByourGeneratedCodeVerifier%7D&code=%7ByourAuthorizationCode%7D&redirect_uri={https://yourApp/callback}" response = http.request(request) -puts response.read_body`; -export const codeExample12 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -532,20 +494,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ##### Parameters @@ -593,11 +544,6 @@ If all goes well, you'll receive an HTTP 200 response with a payload containing } ``` - - - - - Validate your tokens before saving them. To learn how, read [Validate ID Tokens](/docs/secure/tokens/id-tokens/validate-id-tokens) and [Validate Access Tokens](/docs/secure/tokens/access-tokens/validate-access-tokens). @@ -620,7 +566,7 @@ Refresh tokens must be stored securely since they allow a user to remain authent To call your API from a native/mobile application, the application must pass the retrieved Access Token as a Bearer token in the Authorization header of your HTTP request. - + ```bash cURL lines curl --request GET \ --url https://myapi.com/api \ @@ -800,7 +746,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + ### Refresh tokens @@ -815,18 +761,24 @@ To refresh your token, make a `POST` request to the `/oauth/token` endpoint in t #### Example POST to token URL -export const codeExample13 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=refresh_token \ --data 'client_id={yourClientId}' \ - --data 'refresh_token={yourRefreshToken}'`; -export const codeExample14 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data 'refresh_token={yourRefreshToken}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=refresh_token&client_id={yourClientId}&refresh_token=%7ByourRefreshToken%7D", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample15 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -853,12 +805,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample16 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=refresh_token&client_id={yourClientId}&refresh_token=%7ByourRefreshToken%7D") - .asString();`; -export const codeExample17 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -875,8 +831,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample18 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -901,8 +859,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample19 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -927,8 +887,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample20 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -941,8 +903,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample21 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -957,8 +921,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=refresh_token&client_id={yourClientId}&refresh_token=%7ByourRefreshToken%7D" response = http.request(request) -puts response.read_body`; -export const codeExample22 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -983,20 +949,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ##### Parameters @@ -1040,11 +995,6 @@ If all goes well, you'll receive an `HTTP 200` response with a payload containin } ``` - - - - - Validate your tokens before saving them. To learn how, read [Validate ID Tokens](/docs/secure/tokens/id-tokens/validate-id-tokens) and [Validate Access Tokens](/docs/secure/tokens/access-tokens/validate-access-tokens). @@ -1069,11 +1019,6 @@ exports.onExecutePostLogin = async (event, api) => { }; ``` - - - - - Scopes will be available in the token after the Action has run. diff --git a/main/docs/get-started/authentication-and-authorization-flow/authorization-code-flow/add-login-auth-code-flow.mdx b/main/docs/get-started/authentication-and-authorization-flow/authorization-code-flow/add-login-auth-code-flow.mdx index 715fe856b..bef163427 100644 --- a/main/docs/get-started/authentication-and-authorization-flow/authorization-code-flow/add-login-auth-code-flow.mdx +++ b/main/docs/get-started/authentication-and-authorization-flow/authorization-code-flow/add-login-auth-code-flow.mdx @@ -12,6 +12,8 @@ title: Add Login Using the Authorization Code Flow --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + You can add login to your regular web application using the Authorization Code Flow. To learn how the flow works and why you should use it, read [Authorization Code Flow](/docs/get-started/authentication-and-authorization-flow/authorization-code-flow). To call your API from a regular web app, read [Call Your API Using the Authorization Code Flow](/docs/get-started/authentication-and-authorization-flow/authorization-code-flow/call-your-api-using-the-authorization-code-flow). To implement the Authorization Code Flow, Auth0 provides the following resources: @@ -52,11 +54,6 @@ export const codeExample1 = `https://{yourDomain}/authorize? - - - - - ### Parameters
    @@ -118,11 +115,6 @@ export const codeExample2 = ` - - - - - ### Response If all goes well, you'll receive an `HTTP 302` response. The authorization code is included at the end of the URL: @@ -132,31 +124,32 @@ HTTP/1.1 302 Found Location: {https://yourApp/callback}?code={authorizationCode}&state=xyzABC123 ``` - - - - - ## Request tokens Now that you have an Authorization Code, you must exchange it for tokens. Using the extracted Authorization Code (`code`) from the previous step, you will need to `POST` to the [token URL](https://auth0.com/docs/api/authentication#authorization-code). ### POST to token URL example -export const codeExample3 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=authorization_code \ --data 'client_id={yourClientId}' \ --data 'client_secret={yourClientSecret}' \ --data 'code=yourAuthorizationCode}' \ - --data 'redirect_uri={https://yourApp/callback}'`; -export const codeExample4 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data 'redirect_uri={https://yourApp/callback}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=authorization_code&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&code=yourAuthorizationCode%7D&redirect_uri={https://yourApp/callback}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample5 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -183,12 +176,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample6 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=authorization_code&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&code=yourAuthorizationCode%7D&redirect_uri={https://yourApp/callback}") - .asString();`; -export const codeExample7 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -207,8 +204,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample8 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -235,8 +234,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample9 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -261,8 +262,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample10 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -275,8 +278,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample11 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -291,8 +296,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=authorization_code&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&code=yourAuthorizationCode%7D&redirect_uri={https://yourApp/callback}" response = http.request(request) -puts response.read_body`; -export const codeExample12 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -319,20 +326,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ### Parameters @@ -379,11 +375,6 @@ If all goes well, you'll receive an HTTP 200 response with a payload containing } ``` - - - - - Validate your tokens before saving them. To learn how, read [Validate ID Tokens](/docs/secure/tokens/id-tokens/validate-id-tokens) and [Validate Access Tokens](/docs/secure/tokens/access-tokens/validate-access-tokens). @@ -416,11 +407,6 @@ export const codeExample13 = `https://{yourDomain}/authorize? - - - - - Now, when you request tokens, your ID Token will contain the most basic claims. When you decode the ID Token, it will look similar to: ```json lines @@ -433,11 +419,6 @@ Now, when you request tokens, your ID Token will contain the most basic claims. } ``` - - - - - ### Request user's name and profile picture In addition to the usual user authentication, this example shows how to request additional user details, such as name and picture. @@ -453,11 +434,6 @@ export const codeExample14 = `https://{yourDomain}/authorize? - - - - - Now, when you request tokens, your ID token will contain the requested name and picture claims. When you decode the ID token, it will look similar to: ```json lines @@ -472,11 +448,6 @@ Now, when you request tokens, your ID token will contain the requested name and } ``` - - - - - ### Request user log in with GitHub In addition to the usual user authentication, this example shows how to send users directly to a social identity provider, such as GitHub. You will first need to configure the appropriate connection in [Auth0 Dashboard > Authentication > Social](https://manage.auth0.com/#/connections/social) and get the connection name from the **Settings** tab. @@ -493,11 +464,6 @@ export const codeExample15 = `https://{yourDomain}/authorize? - - - - - Now, when you request tokens, your ID Token will contain a `sub` claim with the user's unique ID returned from GitHub. When you decode the ID token, it will look similar to: ```json lines @@ -513,11 +479,6 @@ Now, when you request tokens, your ID Token will contain a `sub` claim with the } ``` - - - - - ## Learn more * [OAuth 2.0 Authorization Framework](/docs/authenticate/protocols/oauth) diff --git a/main/docs/get-started/authentication-and-authorization-flow/authorization-code-flow/call-your-api-using-the-authorization-code-flow.mdx b/main/docs/get-started/authentication-and-authorization-flow/authorization-code-flow/call-your-api-using-the-authorization-code-flow.mdx index 803d1743c..acc442812 100644 --- a/main/docs/get-started/authentication-and-authorization-flow/authorization-code-flow/call-your-api-using-the-authorization-code-flow.mdx +++ b/main/docs/get-started/authentication-and-authorization-flow/authorization-code-flow/call-your-api-using-the-authorization-code-flow.mdx @@ -11,6 +11,8 @@ title: Call Your API Using the Authorization Code Flow --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + This tutorial will help you call your own API using the Authorization Code Flow. If you want to learn how the flow works and why you should use it, see [Authorization Code Flow](/docs/get-started/authentication-and-authorization-flow/authorization-code-flow). If you want to learn to add login to your regular web app, see [Add Login Using the Authorization Code Flow](/docs/get-started/authentication-and-authorization-flow/authorization-code-flow/add-login-auth-code-flow). @@ -62,11 +64,6 @@ export const codeExample1 = `https://{yourDomain}/authorize? - - - - - ##### Parameters Note that for authorizing a user when calling a custom API, you: @@ -130,11 +127,6 @@ export const codeExample2 = ` - - - - - #### Response If all goes well, you'll receive an `HTTP 302` response. The authorization code is included at the end of the URL: @@ -152,20 +144,26 @@ Now that you have an Authorization Code, you must exchange it for tokens. Using #### Example POST to token URL -export const codeExample3 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=authorization_code \ --data 'client_id={yourClientId}' \ --data 'client_secret={yourClientSecret}' \ --data 'code=yourAuthorizationCode}' \ - --data 'redirect_uri={https://yourApp/callback}'`; -export const codeExample4 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data 'redirect_uri={https://yourApp/callback}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=authorization_code&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&code=yourAuthorizationCode%7D&redirect_uri={https://yourApp/callback}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample5 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -192,12 +190,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample6 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=authorization_code&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&code=yourAuthorizationCode%7D&redirect_uri={https://yourApp/callback}") - .asString();`; -export const codeExample7 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -216,8 +218,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample8 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -244,8 +248,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample9 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -270,16 +276,20 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample10 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") payload = "grant_type=authorization_code&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&code=yourAuthorizationCode%7D&redirect_uri={https://yourApp/callback}" headers = { 'content-type': "application/x-www-form-urlencoded" } conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample11 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -294,8 +304,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=authorization_code&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&code=yourAuthorizationCode%7D&redirect_uri={https://yourApp/callback}" response = http.request(request) -puts response.read_body`; -export const codeExample12 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -322,20 +334,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ##### Parameters @@ -382,11 +383,6 @@ If all goes well, you'll receive an `HTTP 200` response with a payload containin } ``` - - - - - Validate your tokens before saving them. To learn how, read [Validate ID Tokens](/docs/secure/tokens/id-tokens/validate-id-tokens) and [Validate Access Tokens](/docs/secure/tokens/access-tokens/validate-access-tokens). @@ -411,7 +407,7 @@ Refresh tokens must be stored securely since they allow a user to remain authent To call your API from a regular web application, the application must pass the retrieved access token as a Bearer token in the Authorization header of your HTTP request. - + ```bash cURL lines curl --request GET \ --url https://myapi.com/api \ @@ -590,7 +586,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + @@ -607,18 +603,24 @@ To refresh your token, make a `POST` request to the `/oauth/token` endpoint in t ##### Example POST to token URL -export const codeExample13 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=refresh_token \ --data 'client_id={yourClientId}' \ - --data 'refresh_token={yourRefreshToken}'`; -export const codeExample14 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data 'refresh_token={yourRefreshToken}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=refresh_token&client_id={yourClientId}&refresh_token=%7ByourRefreshToken%7D", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample15 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -645,12 +647,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample16 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=refresh_token&client_id={yourClientId}&refresh_token=%7ByourRefreshToken%7D") - .asString();`; -export const codeExample17 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -667,8 +673,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample18 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -693,8 +701,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample19 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -719,16 +729,20 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample20 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") payload = "grant_type=refresh_token&client_id={yourClientId}&refresh_token=%7ByourRefreshToken%7D" headers = { 'content-type': "application/x-www-form-urlencoded" } conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample21 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' url = URI("https://{yourDomain}/oauth/token") @@ -739,8 +753,10 @@ request = Net::HTTP::Post.new(url) request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=refresh_token&client_id={yourClientId}&refresh_token=%7ByourRefreshToken%7D" response = http.request(request) -puts response.read_body`; -export const codeExample22 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -765,20 +781,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ###### Parameters @@ -822,11 +827,6 @@ If all goes well, you'll receive an `HTTP 200` response with a payload containin } ``` - - - - - Validate your tokens before saving them. To learn how, read [Validate ID Tokens](/docs/secure/tokens/id-tokens/validate-id-tokens) and [Validate Access Tokens](/docs/secure/tokens/access-tokens/validate-access-tokens). @@ -837,7 +837,6 @@ Validate your tokens before saving them. To learn how, read [Validate ID Tokens] - ### Sample use cases #### Customize tokens @@ -858,11 +857,6 @@ exports.onExecutePostLogin = async (event, api) => { }; ``` - - - - - Auth0 returns profile information in a structured claim format as defined by the [OpenID Connect (OIDC) specification](https://openid.net/specs/openid-connect-core-1_0.html#StandardClaims). This means that custom claims added to ID tokens or access tokens must [conform to guidelines and restrictions](/docs/secure/tokens/json-web-tokens/create-custom-claims) to avoid possible collisions. diff --git a/main/docs/get-started/authentication-and-authorization-flow/client-credentials-flow/call-your-api-using-the-client-credentials-flow.mdx b/main/docs/get-started/authentication-and-authorization-flow/client-credentials-flow/call-your-api-using-the-client-credentials-flow.mdx index e3884c8a4..8547e2ec0 100644 --- a/main/docs/get-started/authentication-and-authorization-flow/client-credentials-flow/call-your-api-using-the-client-credentials-flow.mdx +++ b/main/docs/get-started/authentication-and-authorization-flow/client-credentials-flow/call-your-api-using-the-client-credentials-flow.mdx @@ -11,6 +11,8 @@ title: Call Your API Using the Client Credentials Flow --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + This tutorial will help you call your API from a machine-to-machine (M2M) application using the Client Credentials Flow. To learn how the flow works and why you should use it, read [Client Credentials Flow](/docs/get-started/authentication-and-authorization-flow/client-credentials-flow). @@ -47,19 +49,25 @@ To access your API, you must request an access token for it. To do so, you will #### Example POST to token URL -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=client_credentials \ --data client_id=YOUR_CLIENT_ID \ --data client_secret=YOUR_CLIENT_SECRET \ - --data audience=YOUR_API_IDENTIFIER`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data audience=YOUR_API_IDENTIFIER +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&audience=YOUR_API_IDENTIFIER", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -86,12 +94,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&audience=YOUR_API_IDENTIFIER") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -109,8 +121,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -137,8 +151,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request } }]; [dataTask resume]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -163,8 +179,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -177,8 +195,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -193,8 +213,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&audience=YOUR_API_IDENTIFIER" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -220,20 +242,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ##### Parameters @@ -279,11 +290,6 @@ If all goes well, you'll receive an `HTTP 200` response with a payload containin } ``` - - - - - Validate your tokens before saving them. To learn how, read [Validate ID Tokens](/docs/secure/tokens/id-tokens/validate-id-tokens) and [Validate Access Tokens](/docs/secure/tokens/access-tokens/validate-access-tokens). @@ -294,7 +300,7 @@ Validate your tokens before saving them. To learn how, read [Validate ID Tokens] To call your API from the M2M application, the application must pass the retrieved access token as a Bearer token in the Authorization header of your HTTP request. - + ```bash cURL lines curl --request GET \ --url https://myapi.com/api \ @@ -474,7 +480,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + ### Sample use cases diff --git a/main/docs/get-started/authentication-and-authorization-flow/client-credentials-flow/customize-tokens-using-hooks-with-client-credentials-flow.mdx b/main/docs/get-started/authentication-and-authorization-flow/client-credentials-flow/customize-tokens-using-hooks-with-client-credentials-flow.mdx index 1608f52c2..65e9328a5 100644 --- a/main/docs/get-started/authentication-and-authorization-flow/client-credentials-flow/customize-tokens-using-hooks-with-client-credentials-flow.mdx +++ b/main/docs/get-started/authentication-and-authorization-flow/client-credentials-flow/customize-tokens-using-hooks-with-client-credentials-flow.mdx @@ -12,6 +12,8 @@ title: Customize Tokens Using Hooks with Client Credentials Flow --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + The End of Life (EOL) date of Rules and Hooks will be **November 18, 2026**, and they are no longer available to new tenants created as of **October 16, 2023**. Existing tenants with active Hooks will retain Hooks product access through end of life. @@ -81,11 +83,6 @@ module.exports = function(client, scope, audience, context, cb) { }; ``` - - - - - Auth0 returns profile information in a structured claim format as defined by the [OpenID Connect (OIDC) specification](https://openid.net/specs/openid-connect-core-1_0.html#StandardClaims). This means that custom claims added to ID tokens or access tokens must [conform to guidelines and restrictions](/docs/secure/tokens/json-web-tokens/create-custom-claims) to avoid possible collisions. @@ -100,19 +97,25 @@ To test the hook you just created you need to run a Client Credentials exchange, To get a token, make a `POST` call to the [Client Credentials Flow endpoint](https://auth0.com/docs/api/authentication#client-credentials-flow). Be sure to replace CLIENT_ID, CLIENT_SECRET, and API_IDENTIFIER placeholder values with your application's Client ID, your application's Client Secret, and your API's Identifier, respectively. You can find the Client ID and Client Secret in your [Application](https://manage.auth0.com/#/applications) settings and the API Identifier in your [API](https://manage.auth0.com/#/apis) settings. -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=client_credentials \ --data 'client_id={yourClientId}' \ --data client_secret=YOUR_CLIENT_SECRET \ - --data audience=YOUR_API_IDENTIFIER`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data audience=YOUR_API_IDENTIFIER +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=client_credentials&client_id={yourClientId}&client_secret=YOUR_CLIENT_SECRET&audience=YOUR_API_IDENTIFIER", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -139,12 +142,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=client_credentials&client_id={yourClientId}&client_secret=YOUR_CLIENT_SECRET&audience=YOUR_API_IDENTIFIER") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -162,8 +169,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -189,8 +198,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -215,8 +226,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -229,8 +242,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -245,8 +260,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=client_credentials&client_id={yourClientId}&client_secret=YOUR_CLIENT_SECRET&audience=YOUR_API_IDENTIFIER" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -272,20 +289,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + A successful response will include: @@ -305,11 +311,6 @@ Content-Type: application/json } ``` - - - - - #### Decode token The easiest way to decode the access token and review its contents is to use the [JWT.io Debugger](https://jwt.io/#debugger-io). diff --git a/main/docs/get-started/authentication-and-authorization-flow/device-authorization-flow/call-your-api-using-the-device-authorization-flow.mdx b/main/docs/get-started/authentication-and-authorization-flow/device-authorization-flow/call-your-api-using-the-device-authorization-flow.mdx index 59ee4bb65..dcc487e36 100644 --- a/main/docs/get-started/authentication-and-authorization-flow/device-authorization-flow/call-your-api-using-the-device-authorization-flow.mdx +++ b/main/docs/get-started/authentication-and-authorization-flow/device-authorization-flow/call-your-api-using-the-device-authorization-flow.mdx @@ -11,6 +11,8 @@ title: Call Your API Using the Device Authorization Flow --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + This tutorial will help you call your own API from an input-constrained device using the Device Authorization Flow. If you want to learn how the flow works and why you should use it, see [Device Authorization Flow](/docs/get-started/authentication-and-authorization-flow/device-authorization-flow). @@ -61,18 +63,24 @@ To get the device code, your app must request a code from the [device code URL]( #### Example POST to device code URL -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/device/code' \ --header 'content-type: application/x-www-form-urlencoded' \ --data 'client_id={yourClientId}' \ --data 'scope={scope}' \ - --data 'audience={audience}'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/oauth/device/code"); + --data 'audience={audience}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/device/code"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "client_id={yourClientId}&scope=%7Bscope%7D&audience=%7Baudience%7D", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -99,12 +107,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/device/code") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/device/code") .header("content-type", "application/x-www-form-urlencoded") .body("client_id={yourClientId}&scope=%7Bscope%7D&audience=%7Baudience%7D") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -117,8 +129,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -143,8 +157,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/device/code", @@ -169,8 +185,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -183,8 +201,10 @@ conn.request("POST", "/{yourDomain}/oauth/device/code", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -199,8 +219,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "client_id={yourClientId}&scope=%7Bscope%7D&audience=%7Baudience%7D" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -225,20 +247,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ##### Device code parameters @@ -290,11 +301,6 @@ If all goes well, you'll receive an `HTTP 200` response with a payload containin } ``` - - - - - * `device_code` is the unique code for the device. When the user goes to the `verification_uri` in their browser-based device, this code will be bound to their session. * `user_code` contains the code that should be input at the `verification_uri` to authorize the device. * `verification_uri` contains the URL the user should visit to authorize the device. @@ -345,18 +351,24 @@ To avoid errors due to network latency, you should start counting each interval #### Example request token POST to token URL -export const codeExample11 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=urn:ietf:params:oauth:grant-type:device_code \ --data 'device_code={yourDeviceCode}' \ - --data 'client_id={yourClientId}'`; -export const codeExample12 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data 'client_id={yourClientId}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Adevice_code&device_code=%7ByourDeviceCode%7D&client_id={yourClientId}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample13 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -383,12 +395,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample14 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Adevice_code&device_code=%7ByourDeviceCode%7D&client_id={yourClientId}") - .asString();`; -export const codeExample15 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -405,8 +421,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample16 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -431,8 +449,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -457,8 +477,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -471,8 +493,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -487,8 +511,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Adevice_code&device_code=%7ByourDeviceCode%7D&client_id={yourClientId}" response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -513,20 +539,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ##### Token request parameters @@ -568,11 +583,6 @@ HTTP/1.1 403 Forbidden } ``` - - - - - ##### Slow down You are polling too fast. Slow down and use the suggested interval retrieved in the previous step of this tutorial. To avoid receiving this error due to network latency, you should start counting each interval after receipt of the last polling request's response. @@ -585,11 +595,6 @@ HTTP/1.1 429 Too Many Requests } ``` - - - - - ##### Expired token The user has not authorized the device quickly enough, so the `device_code` has expired. Your application should notify the user that the flow has expired and prompt them to reinitiate the flow. @@ -608,11 +613,6 @@ HTTP/1.1 403 Bad Request } ``` - - - - - ##### Access denied Finally, if access is denied, you will receive: @@ -625,11 +625,6 @@ HTTP/1.1 403 Forbidden } ``` - - - - - This can occur for a variety of reasons, including: * the user refused to authorize the device @@ -677,11 +672,6 @@ Once the user has successfully authorized the device, you'll receive an `HTTP 20 } ``` - - - - - Validate your tokens before saving them. To learn how, read [Validate ID Tokens](/docs/secure/tokens/id-tokens/validate-id-tokens) and [Validate Access Tokens](/docs/secure/tokens/access-tokens/validate-access-tokens). @@ -704,7 +694,7 @@ Refresh tokens must be stored securely since they allow a user to remain authent To call your API, the application must pass the retrieved Access Token as a Bearer token in the Authorization header of your HTTP request. - + ```bash cURL lines curl --request GET \ --url https://myapi.com/api \ @@ -884,7 +874,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + ### Refresh tokens @@ -899,19 +889,25 @@ To refresh your token, make a `POST` request to the `/oauth/token` endpoint in t #### Example refresh token POST to token URL -export const codeExample21 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=refresh_token \ --data 'client_id={yourClientId}' \ --data 'client_secret={yourClientSecret}' \ - --data 'refresh_token={yourRefreshToken}'`; -export const codeExample22 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data 'refresh_token={yourRefreshToken}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=refresh_token&client_id={yourClientId}&client_secret={yourClientSecret}&refresh_token=%7ByourRefreshToken%7D", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample23 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -938,12 +934,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample24 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=refresh_token&client_id={yourClientId}&client_secret={yourClientSecret}&refresh_token=%7ByourRefreshToken%7D") - .asString();`; -export const codeExample25 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -961,8 +961,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample26 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -988,8 +990,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample27 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -1014,8 +1018,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample28 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -1028,8 +1034,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample29 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -1044,8 +1052,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=refresh_token&client_id={yourClientId}&client_secret={yourClientSecret}&refresh_token=%7ByourRefreshToken%7D" response = http.request(request) -puts response.read_body`; -export const codeExample30 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -1071,20 +1081,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ##### Refresh token request parameters @@ -1132,11 +1131,6 @@ If all goes well, you'll receive an `HTTP 200` response with a payload containin } ``` - - - - - Validate your tokens before saving them. To learn how, read [Validate ID Tokens](/docs/secure/tokens/id-tokens/validate-id-tokens) and [Validate Access Tokens](/docs/secure/tokens/access-tokens/validate-access-tokens). @@ -1159,11 +1153,6 @@ function (user, context, callback) { } ``` - - - - - ### Sample implementations * [Device Authorization Playground](https://auth0.github.io/device-flow-playground/) diff --git a/main/docs/get-started/authentication-and-authorization-flow/hybrid-flow/call-api-hybrid-flow.mdx b/main/docs/get-started/authentication-and-authorization-flow/hybrid-flow/call-api-hybrid-flow.mdx index 894d782fd..1eb6b3956 100644 --- a/main/docs/get-started/authentication-and-authorization-flow/hybrid-flow/call-api-hybrid-flow.mdx +++ b/main/docs/get-started/authentication-and-authorization-flow/hybrid-flow/call-api-hybrid-flow.mdx @@ -14,6 +14,8 @@ title: Call Your API Using the Hybrid Flow --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + This tutorial will help you call your own API using the Hybrid Flow. If you want to learn how the flow works and why you should use it, see [Hybrid Flow](/docs/get-started/authentication-and-authorization-flow/hybrid-flow). @@ -76,7 +78,6 @@ export const codeExample1 = `https://{yourDomain}/authorize? - ##### Parameters Note that for authorizing a user when calling a custom API, you: @@ -149,11 +150,6 @@ export const codeExample2 = ` - - - - - #### Response If all goes well, you'll receive an `HTTP 302` response. The requested credentials are encoded in the body: @@ -169,11 +165,6 @@ id_token=eyJ...acA& state=xyzABC123 ``` - - - - - Note that the returned values depend on what you requested as a `response_type`.
    @@ -230,20 +221,26 @@ The +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -322,8 +325,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample9 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -348,8 +353,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample10 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -362,8 +369,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample11 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -378,8 +387,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=authorization_code&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&code=yourAuthorizationCode%7D&redirect_uri={https://yourApp/callback}" response = http.request(request) -puts response.read_body`; -export const codeExample12 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -406,20 +417,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ##### Parameters @@ -466,11 +466,6 @@ If all goes well, you'll receive an `HTTP 200` response with a payload containin } ``` - - - - - Validate your tokens before saving them. To learn how, read [Validate ID Tokens](/docs/secure/tokens/id-tokens/validate-id-tokens) and [Validate Access Tokens](/docs/secure/tokens/access-tokens/validate-access-tokens). @@ -493,7 +488,7 @@ Refresh tokens must be stored securely since they allow a user to remain authent To call your API from a regular web application (or similar cases in which the application credentials can be safely stored), the application must pass the retrieved Access Token as a Bearer token in the Authorization header of your HTTP request. - + ```bash cURL lines curl --request GET \ --url https://myapi.com/api \ @@ -673,7 +668,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + ### Refresh tokens @@ -688,18 +683,24 @@ To refresh your token, make a `POST` request to the `/oauth/token` endpoint in t #### Example POST to token URL -export const codeExample13 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=refresh_token \ --data 'client_id={yourClientId}' \ - --data 'refresh_token={yourRefreshToken}'`; -export const codeExample14 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data 'refresh_token={yourRefreshToken}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=refresh_token&client_id={yourClientId}&refresh_token=%7ByourRefreshToken%7D", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample15 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -726,12 +727,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample16 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=refresh_token&client_id={yourClientId}&refresh_token=%7ByourRefreshToken%7D") - .asString();`; -export const codeExample17 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -748,8 +753,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample18 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -774,8 +781,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample19 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -800,8 +809,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample20 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -814,8 +825,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample21 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -830,8 +843,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=refresh_token&client_id={yourClientId}&refresh_token=%7ByourRefreshToken%7D" response = http.request(request) -puts response.read_body`; -export const codeExample22 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -856,20 +871,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ##### Parameters @@ -913,11 +917,6 @@ If all goes well, you'll receive an `HTTP 200` response with a payload containin } ``` - - - - - Validate your tokens before saving them. To learn how, read [Validate ID Tokens](/docs/secure/tokens/id-tokens/validate-id-tokens) and [Validate Access Tokens](/docs/secure/tokens/access-tokens/validate-access-tokens). @@ -942,11 +941,6 @@ exports.onExecutePostLogin = async (event, api) => { }; ``` - - - - - Scopes will be available in the token after all rules have run. diff --git a/main/docs/get-started/authentication-and-authorization-flow/resource-owner-password-flow/call-your-api-using-resource-owner-password-flow.mdx b/main/docs/get-started/authentication-and-authorization-flow/resource-owner-password-flow/call-your-api-using-resource-owner-password-flow.mdx index 664727f51..3562a4ef5 100644 --- a/main/docs/get-started/authentication-and-authorization-flow/resource-owner-password-flow/call-your-api-using-resource-owner-password-flow.mdx +++ b/main/docs/get-started/authentication-and-authorization-flow/resource-owner-password-flow/call-your-api-using-resource-owner-password-flow.mdx @@ -11,6 +11,8 @@ title: Call Your API Using Resource Owner Password Flow --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + This tutorial will help you call your own API using the Resource Owner Password Flow. If you want to learn how the flow works and why you should use it, see [Resource Owner Password Flow](/docs/get-started/authentication-and-authorization-flow/resource-owner-password-flow). @@ -74,7 +76,9 @@ To call your API, you must first get the user's credentials, typically through a #### Example POST to token URL -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=password \ @@ -83,13 +87,17 @@ export const codeExample1 = `curl --request POST \ --data 'audience={yourApiIdentifier}' \ --data scope=read:sample \ --data 'client_id={yourClientId}' \ - --data 'client_secret={yourClientSecret}'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data 'client_secret={yourClientSecret}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=password&username=%7Busername%7D&password=%7Bpassword%7D&audience=%7ByourApiIdentifier%7D&scope=read%3Asample&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -116,12 +124,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=password&username=%7Busername%7D&password=%7Bpassword%7D&audience=%7ByourApiIdentifier%7D&scope=read%3Asample&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -142,8 +154,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -172,8 +186,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -198,8 +214,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -212,8 +230,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -228,8 +248,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=password&username=%7Busername%7D&password=%7Bpassword%7D&audience=%7ByourApiIdentifier%7D&scope=read%3Asample&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -258,20 +280,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ##### Parameters @@ -335,11 +346,6 @@ If all goes well, you'll receive an `HTTP 200` response with a payload containin } ``` - - - - - Validate your tokens before saving them. To learn how, read [Validate ID Tokens](/docs/secure/tokens/id-tokens/validate-id-tokens) and [Validate Access Tokens](/docs/secure/tokens/access-tokens/validate-access-tokens). @@ -366,7 +372,7 @@ If you need the user's information, include the `openid` scope in your request. To call your API, the application must pass the retrieved Access Token as a Bearer token in the Authorization header of your HTTP request. - + ```bash cURL lines curl --request GET \ --url https://myapi.com/api \ @@ -546,7 +552,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + ### Refresh tokens @@ -561,18 +567,24 @@ To refresh your token, make a `POST` request to the `/oauth/token` endpoint in t #### Example POST to token URL -export const codeExample11 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=refresh_token \ --data 'client_id={yourClientId}' \ - --data 'refresh_token={yourRefreshToken}'`; -export const codeExample12 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data 'refresh_token={yourRefreshToken}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=refresh_token&client_id={yourClientId}&refresh_token=%7ByourRefreshToken%7D", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample13 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -599,12 +611,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample14 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=refresh_token&client_id={yourClientId}&refresh_token=%7ByourRefreshToken%7D") - .asString();`; -export const codeExample15 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -621,8 +637,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample16 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -647,8 +665,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -673,8 +693,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -687,8 +709,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -703,8 +727,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=refresh_token&client_id={yourClientId}&refresh_token=%7ByourRefreshToken%7D" response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -729,20 +755,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ##### Parameters @@ -785,11 +800,6 @@ If all goes well, you'll receive an `HTTP 200` response with a payload containin } ``` - - - - - Validate your tokens before saving them. To learn how, read [Validate ID Tokens](/docs/secure/tokens/id-tokens/validate-id-tokens) and [Validate Access Tokens](/docs/secure/tokens/access-tokens/validate-access-tokens). @@ -814,11 +824,6 @@ exports.onExecutePostLogin = async (event, api) => { }; ``` - - - - - Scopes will be available in the token after the Action has run. diff --git a/main/docs/get-started/onboarding/self-service-m2m.mdx b/main/docs/get-started/onboarding/self-service-m2m.mdx index 315231e03..fcd4b3648 100644 --- a/main/docs/get-started/onboarding/self-service-m2m.mdx +++ b/main/docs/get-started/onboarding/self-service-m2m.mdx @@ -10,6 +10,8 @@ title: Self-Service Machine-to-Machine --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + If your business case services a non-interactive audience, like APIs or backend servers, you will onboard with a machine-to-machine (M2M) configuration. ## Use cases @@ -234,19 +236,25 @@ Auth0 supports other client authentication methods besides providing Client ID a A request to the `/oauth/token` endpoint should be similar to the sample below: -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=client_credentials \ --data client_id=YOUR_CLIENT_ID \ --data client_secret=YOUR_CLIENT_SECRET \ - --data audience=YOUR_API_IDENTIFIER`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data audience=YOUR_API_IDENTIFIER +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&audience=YOUR_API_IDENTIFIER", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -273,12 +281,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&audience=YOUR_API_IDENTIFIER") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -296,8 +308,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -323,8 +337,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -349,8 +365,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -363,8 +381,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -379,8 +399,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&audience=YOUR_API_IDENTIFIER" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -406,20 +428,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + The response should be similar to the sample below: @@ -433,11 +444,6 @@ Content-Type: application/json } ``` - - - - - #### Token expiration Your access tokens have a limit for how long the token is valid. Since your communications are on the back-channel, you cannot use refresh tokens to extend sessions, and should consider configuring your access tokens with a 1-hour expiration time. You may need to strike your own balance between security and performance for your specific environment. To learn more, read [Update Access Token Lifetime](/docs/secure/tokens/access-tokens/update-access-token-lifetime). diff --git a/main/docs/get-started/tenant-settings/signing-keys/revoke-signing-keys.mdx b/main/docs/get-started/tenant-settings/signing-keys/revoke-signing-keys.mdx index 4e5f01f65..b7ef00e8b 100644 --- a/main/docs/get-started/tenant-settings/signing-keys/revoke-signing-keys.mdx +++ b/main/docs/get-started/tenant-settings/signing-keys/revoke-signing-keys.mdx @@ -12,6 +12,8 @@ title: Revoke Signing Keys --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + You can revoke your tenant's application or API signing key using the Auth0 Dashboard or the Management API. The signing key is used to sign ID tokens, access tokens, SAML assertions, and WS-Fed assertions sent to your application or API. To learn more, read [Signing Keys](/docs/get-started/tenant-settings/signing-keys). ## Prerequisites @@ -52,16 +54,22 @@ You can only revoke the previously used signing key. 1. To get a list of the signing keys, make a `GET` call to the [Get all Application Signing Keys](https://auth0.com/docs/api/management/v2#!/Keys/get_signing_keys) endpoint. 2. Make a `PUT` call to the [Revoke an Application Signing Key by its Key ID](https://auth0.com/docs/api/management/v2#!/Keys/put_signing_keys) endpoint. Be sure to replace the `{yourKeyId}` and `{yourMgmtApiAccessToken}` placeholder values with your signing key's ID and Management API access token, respectively. -export const codeExample1 = ` curl --request PUT \ + +```bash cURL + curl --request PUT \ --url 'https://{yourDomain}/api/v2/keys/signing/%7ByourKeyId%7D/revoke' \ --header 'authorization: Bearer {yourMgmtApiAccessToken}' -`; -export const codeExample2 = ` var client = new RestClient("https://{yourDomain}/api/v2/keys/signing/%7ByourKeyId%7D/revoke"); + +``` +```csharp C# + var client = new RestClient("https://{yourDomain}/api/v2/keys/signing/%7ByourKeyId%7D/revoke"); var request = new RestRequest(Method.PUT); request.AddHeader("authorization", "Bearer {yourMgmtApiAccessToken}"); IRestResponse response = client.Execute(request); -`; -export const codeExample3 = ` package main + +``` +```go Go + package main import ( "fmt" @@ -86,12 +94,16 @@ func main() { fmt.Println(string(body)) } -`; -export const codeExample4 = ` HttpResponse response = Unirest.put("https://{yourDomain}/api/v2/keys/signing/%7ByourKeyId%7D/revoke") + +``` +```java Java + HttpResponse response = Unirest.put("https://{yourDomain}/api/v2/keys/signing/%7ByourKeyId%7D/revoke") .header("authorization", "Bearer {yourMgmtApiAccessToken}") .asString(); -`; -export const codeExample5 = ` var axios = require("axios").default; + +``` +```javascript Node.JS + var axios = require("axios").default; var options = { method: 'PUT', @@ -104,8 +116,10 @@ console.log(response.data); }).catch(function (error) { console.error(error); }); -`; -export const codeExample6 = ` #import + +``` +```obj-c Obj-C + #import NSDictionary *headers = @{ @"authorization": @"Bearer {yourMgmtApiAccessToken}" }; @@ -126,8 +140,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request } }]; [dataTask resume]; -`; -export const codeExample7 = ` $curl = curl_init(); + +``` +```php PHP + $curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/keys/signing/%7ByourKeyId%7D/revoke", @@ -152,8 +168,10 @@ echo "cURL Error #:" . $err; } else { echo $response; } -`; -export const codeExample8 = ` import http.client + +``` +```python Python + import http.client conn = http.client.HTTPSConnection("") @@ -165,8 +183,10 @@ res = conn.getresponse() data = res.read() print(data.decode("utf-8")) -`; -export const codeExample9 = ` require 'uri' + +``` +```ruby Ruby + require 'uri' require 'net/http' require 'openssl' @@ -181,8 +201,10 @@ request["authorization"] = 'Bearer {yourMgmtApiAccessToken}' response = http.request(request) puts response.read_body -`; -export const codeExample10 = ` import Foundation + +``` +```swift Swift + import Foundation let headers = ["authorization": "Bearer {yourMgmtApiAccessToken}"] @@ -203,20 +225,9 @@ if (error != nil) { }) dataTask.resume() -`; - - - - - - - - - - - - - + +``` +
    diff --git a/main/docs/get-started/tenant-settings/signing-keys/rotate-signing-keys.mdx b/main/docs/get-started/tenant-settings/signing-keys/rotate-signing-keys.mdx index 9ff04fece..8c87f9d9e 100644 --- a/main/docs/get-started/tenant-settings/signing-keys/rotate-signing-keys.mdx +++ b/main/docs/get-started/tenant-settings/signing-keys/rotate-signing-keys.mdx @@ -11,6 +11,8 @@ title: Rotate Signing Keys --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + You can manually rotate a signing key periodically to change the JSON web key (JWK) key used by applications and APIs to validate tokens. If your application or API **does not** allow for this key change, and it attempts to use an expired signing key to verify a token, the authentication request will fail. @@ -44,16 +46,22 @@ You can rotate your tenant's application signing key using the + +``` +```obj-c Obj-C + #import NSDictionary *headers = @{ @"authorization": @"Bearer {yourMgmtApiAccessToken}" }; @@ -118,8 +132,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request } }]; [dataTask resume]; -`; -export const codeExample7 = ` $curl = curl_init(); + +``` +```php PHP + $curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/keys/signing/rotate", @@ -144,8 +160,10 @@ echo "cURL Error #:" . $err; } else { echo $response; } -`; -export const codeExample8 = ` import http.client + +``` +```python Python + import http.client conn = http.client.HTTPSConnection("") @@ -157,8 +175,10 @@ res = conn.getresponse() data = res.read() print(data.decode("utf-8")) -`; -export const codeExample9 = ` require 'uri' + +``` +```ruby Ruby + require 'uri' require 'net/http' require 'openssl' @@ -173,8 +193,10 @@ request["authorization"] = 'Bearer {yourMgmtApiAccessToken}' response = http.request(request) puts response.read_body -`; -export const codeExample10 = ` import Foundation + +``` +```swift Swift + import Foundation let headers = ["authorization": "Bearer {yourMgmtApiAccessToken}"] @@ -195,20 +217,9 @@ if (error != nil) { }) dataTask.resume() -`; - - - - - - - - - - - - - + +``` +
    diff --git a/main/docs/get-started/tenant-settings/signing-keys/view-signing-certificates.mdx b/main/docs/get-started/tenant-settings/signing-keys/view-signing-certificates.mdx index 7ee6b8374..e2621d3a0 100644 --- a/main/docs/get-started/tenant-settings/signing-keys/view-signing-certificates.mdx +++ b/main/docs/get-started/tenant-settings/signing-keys/view-signing-certificates.mdx @@ -12,6 +12,8 @@ title: View Signing Certificates --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + You can view your tenant's application client secrets and signing keys using the Auth0 Dashboard or the Management API. The application signing key is used to sign ID tokens, access tokens, SAML assertions, and WS-Fed assertions sent to your application. These keys are different from those used to sign interactions with connections, including signing SAML requests to identity providers (IdPs) and encrypting responses from IdPs. By default, SAML assertions for IdP connections are signed, which we recommend. To learn more, read [SAML Identity Provider Configuration Settings](/docs/authenticate/protocols/saml/saml-identity-provider-configuration-settings). ## Use the Dashboard @@ -51,14 +53,20 @@ You can also view an application's signing key and/or client secret depending on Make a `GET` call to the [`/signing_keys/get_signing_keys`](https://auth0.com/docs/api/management/v2#!/signing_keys/get_signing_keys) endpoint. Be sure to replace the `{yourMgmtApiAccessToken}` placeholder value with your Management API Access Token. -export const codeExample1 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/keys/signing' \ - --header 'authorization: Bearer {yourMgmtApiAccessToken}'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/keys/signing"); + --header 'authorization: Bearer {yourMgmtApiAccessToken}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/keys/signing"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer {yourMgmtApiAccessToken}"); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -82,11 +90,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/keys/signing") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/keys/signing") .header("authorization", "Bearer {yourMgmtApiAccessToken}") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -98,8 +110,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer {yourMgmtApiAccessToken}" }; @@ -119,8 +133,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/keys/signing", @@ -144,8 +160,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -156,8 +174,10 @@ conn.request("GET", "/{yourDomain}/api/v2/keys/signing", headers=headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -171,8 +191,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer {yourMgmtApiAccessToken}' response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer {yourMgmtApiAccessToken}"] @@ -192,20 +214,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
    @@ -225,14 +236,20 @@ dataTask.resume()`; Make a `GET` call to the [`/signing_keys/get_signing_key`](https://auth0.com/docs/api/management/v2#!/signing_keys/get_signing_key) endpoint. Be sure to replace the `{yourKeyId}` and `{yourMgmtApiAccessToken}` placeholder values with your signing key's ID and Management API Access Token, respectively. -export const codeExample11 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/keys/signing/%7ByourKeyId%7D' \ - --header 'authorization: Bearer {yourMgmtApiAccessToken}'`; -export const codeExample12 = `var client = new RestClient("https://{yourDomain}/api/v2/keys/signing/%7ByourKeyId%7D"); + --header 'authorization: Bearer {yourMgmtApiAccessToken}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/keys/signing/%7ByourKeyId%7D"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer {yourMgmtApiAccessToken}"); -IRestResponse response = client.Execute(request);`; -export const codeExample13 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -256,11 +273,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample14 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/keys/signing/%7ByourKeyId%7D") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/keys/signing/%7ByourKeyId%7D") .header("authorization", "Bearer {yourMgmtApiAccessToken}") - .asString();`; -export const codeExample15 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -272,8 +293,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample16 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer {yourMgmtApiAccessToken}" }; @@ -293,8 +316,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/keys/signing/%7ByourKeyId%7D", @@ -318,8 +343,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -330,8 +357,10 @@ conn.request("GET", "/{yourDomain}/api/v2/keys/signing/%7ByourKeyId%7D", headers res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -345,8 +374,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer {yourMgmtApiAccessToken}' response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer {yourMgmtApiAccessToken}"] @@ -366,20 +397,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
    diff --git a/main/docs/index.mdx b/main/docs/index.mdx index f16edbef1..7640f1489 100644 --- a/main/docs/index.mdx +++ b/main/docs/index.mdx @@ -5,10 +5,12 @@ sidebarTitle: Welcome to Auth0 Docs import {DocsBanner, DocsFeatureCards, LanguageGrid, ProductGrid, LearnBasicsGrid} from "/snippets/home.jsx"; import {BgImage} from "/snippets/BgImage.jsx"; +import {Footer} from "/snippets/Footer.jsx"; - \ No newline at end of file + +
    \ No newline at end of file diff --git a/main/docs/ja-jp/authenticate/database-connections/password-change.mdx b/main/docs/ja-jp/authenticate/database-connections/password-change.mdx index 43b488d53..e010d417f 100644 --- a/main/docs/ja-jp/authenticate/database-connections/password-change.mdx +++ b/main/docs/ja-jp/authenticate/database-connections/password-change.mdx @@ -10,6 +10,7 @@ permalink: "password-change" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; @@ -58,16 +59,22 @@ APIをブラウザーから呼び出す場合は、送信元URLが許可され カスタムデータベース接続の場合は、Authentication APIで`changePassword`を呼び出す前にデータベースにそのユーザーが存在しないかどうかをチェックします。 -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/dbconnections/change_password' \ --header 'content-type: application/json' \ ---data '{"client_id": "{yourClientId}","email": "","connection": "Username-Password-Authentication"}'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/dbconnections/change_password"); +--data '{"client_id": "{yourClientId}","email": "","connection": "Username-Password-Authentication"}' +``` lines +```csharp C# +var client = new RestClient("https://{yourDomain}/dbconnections/change_password"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\"client_id\": \"{yourClientId}\",\"email\": \"\",\"connection\": \"Username-Password-Authentication\"}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{"client_id": "{yourClientId}","email": "","connection": "Username-Password-Authentication"}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" "strings" @@ -76,7 +83,7 @@ import ( ) func main() { url := "https://{yourDomain}/dbconnections/change_password" -payload := strings.NewReader("{\"client_id\": \"{yourClientId}\",\"email\": \"\",\"connection\": \"Username-Password-Authentication\"}") +payload := strings.NewReader("{"client_id": "{yourClientId}","email": "","connection": "Username-Password-Authentication"}") req, _ := http.NewRequest("POST", url, payload) req.Header.Add("content-type", "application/json") res, _ := http.DefaultClient.Do(req) @@ -84,12 +91,16 @@ defer res.Body.Close() body, _ := ioutil.ReadAll(res.Body) fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/dbconnections/change_password") +} +``` lines +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/dbconnections/change_password") .header("content-type", "application/json") -.body("{\"client_id\": \"{yourClientId}\",\"email\": \"\",\"connection\": \"Username-Password-Authentication\"}") -.asString();`; -export const codeExample5 = `var axios = require("axios").default; +.body("{"client_id": "{yourClientId}","email": "","connection": "Username-Password-Authentication"}") +.asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', url: 'https://{yourDomain}/dbconnections/change_password', @@ -104,8 +115,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` lines +```obj-c Obj-C +#import NSDictionary \*headers = @{ @"content-type": @"application/json" }; NSDictionary \*parameters = @{ @"client_id": @"{yourClientId}", @"email": @"", @@ -127,8 +140,10 @@ NSHTTPURLResponse \*httpResponse = (NSHTTPURLResponse \*) response; NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/dbconnections/change_password", CURLOPT_RETURNTRANSFER => true, @@ -137,7 +152,7 @@ CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", -CURLOPT_POSTFIELDS => "{\"client_id\": \"{yourClientId}\",\"email\": \"\",\"connection\": \"Username-Password-Authentication\"}", +CURLOPT_POSTFIELDS => "{"client_id": "{yourClientId}","email": "","connection": "Username-Password-Authentication"}", CURLOPT_HTTPHEADER => [ "content-type: application/json" ], @@ -149,16 +164,20 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` lines +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"client_id\": \"{yourClientId}\",\"email\": \"\",\"connection\": \"Username-Password-Authentication\"}" +payload = "{"client_id": "{yourClientId}","email": "","connection": "Username-Password-Authentication"}" headers = { 'content-type': "application/json" } conn.request("POST", "/{yourDomain}/dbconnections/change_password", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' url = URI("https://{yourDomain}/dbconnections/change_password") @@ -167,10 +186,12 @@ http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["content-type"] = 'application/json' -request.body = "{\"client_id\": \"{yourClientId}\",\"email\": \"\",\"connection\": \"Username-Password-Authentication\"}" +request.body = "{"client_id": "{yourClientId}","email": "","connection": "Username-Password-Authentication"}" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` lines +```swift Swift +import Foundation let headers = ["content-type": "application/json"] let parameters = [ "client_id": "{yourClientId}", @@ -193,20 +214,9 @@ let httpResponse = response as? HTTPURLResponse print(httpResponse) } }) -dataTask.resume()`; - - - lines - - lines - - lines - - lines - - lines - - +dataTask.resume() +``` + ### パスワードリセットメール @@ -249,18 +259,24 @@ Management APIには[Create a Password Change Ticket](/docs/ja-jp/api/management 独自のパスワードリセットフローを実装したい場合は、Management APIへのサーバー要求からユーザーパスワードを直接変更できます。それには、[Update a Userエンドポイント](/docs/ja-jp/api/management/v2#!/Users/patch_users_by_id)に`PATCH`呼び出しを行います。 -export const codeExample11 = `curl --request PATCH \ + +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/users/%7BuserId%7D' \ --header 'authorization: Bearer {yourMgmtApiAccessToken}' \ --header 'content-type: application/json' \ ---data '{"password": "newPassword","connection": "connectionName"}'`; -export const codeExample12 = `var client = new RestClient("https://{yourDomain}/api/v2/users/%7BuserId%7D"); +--data '{"password": "newPassword","connection": "connectionName"}' +``` lines +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users/%7BuserId%7D"); var request = new RestRequest(Method.PATCH); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer {yourMgmtApiAccessToken}"); -request.AddParameter("application/json", "{\"password\": \"newPassword\",\"connection\": \"connectionName\"}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample13 = `package main +request.AddParameter("application/json", "{"password": "newPassword","connection": "connectionName"}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" "strings" @@ -269,7 +285,7 @@ import ( ) func main() { url := "https://{yourDomain}/api/v2/users/%7BuserId%7D" -payload := strings.NewReader("{\"password\": \"newPassword\",\"connection\": \"connectionName\"}") +payload := strings.NewReader("{"password": "newPassword","connection": "connectionName"}") req, _ := http.NewRequest("PATCH", url, payload) req.Header.Add("content-type", "application/json") req.Header.Add("authorization", "Bearer {yourMgmtApiAccessToken}") @@ -278,13 +294,17 @@ defer res.Body.Close() body, _ := ioutil.ReadAll(res.Body) fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample14 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/users/%7BuserId%7D") +} +``` lines +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/users/%7BuserId%7D") .header("content-type", "application/json") .header("authorization", "Bearer {yourMgmtApiAccessToken}") -.body("{\"password\": \"newPassword\",\"connection\": \"connectionName\"}") -.asString();`; -export const codeExample15 = `var axios = require("axios").default; +.body("{"password": "newPassword","connection": "connectionName"}") +.asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', url: 'https://{yourDomain}/api/v2/users/%7BuserId%7D', @@ -298,8 +318,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample16 = `#import +}); +``` lines +```obj-c Obj-C +#import NSDictionary \*headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer {yourMgmtApiAccessToken}" }; NSDictionary \*parameters = @{ @"password": @"newPassword", @@ -321,8 +343,10 @@ NSHTTPURLResponse \*httpResponse = (NSHTTPURLResponse \*) response; NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users/%7BuserId%7D", CURLOPT_RETURNTRANSFER => true, @@ -331,7 +355,7 @@ CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", -CURLOPT_POSTFIELDS => "{\"password\": \"newPassword\",\"connection\": \"connectionName\"}", +CURLOPT_POSTFIELDS => "{"password": "newPassword","connection": "connectionName"}", CURLOPT_HTTPHEADER => [ "authorization: Bearer {yourMgmtApiAccessToken}", "content-type: application/json" @@ -344,10 +368,12 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `import http.client +} +``` lines +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"password\": \"newPassword\",\"connection\": \"connectionName\"}" +payload = "{"password": "newPassword","connection": "connectionName"}" headers = { 'content-type': "application/json", 'authorization': "Bearer {yourMgmtApiAccessToken}" @@ -355,8 +381,10 @@ headers = { conn.request("PATCH", "/{yourDomain}/api/v2/users/%7BuserId%7D", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' url = URI("https://{yourDomain}/api/v2/users/%7BuserId%7D") @@ -366,10 +394,12 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Patch.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer {yourMgmtApiAccessToken}' -request.body = "{\"password\": \"newPassword\",\"connection\": \"connectionName\"}" +request.body = "{"password": "newPassword","connection": "connectionName"}" response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` lines +```swift Swift +import Foundation let headers = [ "content-type": "application/json", "authorization": "Bearer {yourMgmtApiAccessToken}" @@ -394,20 +424,9 @@ let httpResponse = response as? HTTPURLResponse print(httpResponse) } }) -dataTask.resume()`; - - - lines - - lines - - lines - - lines - - lines - - +dataTask.resume() +``` + ### Auth0 Dashboardを使ってユーザーパスワードを手動で設定する diff --git a/main/docs/ja-jp/authenticate/identity-providers/calling-an-external-idp-api.mdx b/main/docs/ja-jp/authenticate/identity-providers/calling-an-external-idp-api.mdx index fe9aaa690..8d1eb5a24 100644 --- a/main/docs/ja-jp/authenticate/identity-providers/calling-an-external-idp-api.mdx +++ b/main/docs/ja-jp/authenticate/identity-providers/calling-an-external-idp-api.mdx @@ -10,6 +10,7 @@ permalink: "calling-an-external-idp-api" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; FacebookやGitHubなどの外部IDプロバイダー(IdP)でユーザーを正常に認証すると、多くの場合、IdPはAuth0に返すユーザープロファイルにアクセストークンを含めます。 @@ -105,14 +106,20 @@ FacebookやGitHubなどの外部IDプロバイダー( "https://{yourDomain}/api/v2/users/%7BuserId%7D", CURLOPT_RETURNTRANSFER => true, @@ -180,15 +195,19 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` lines +```python Python +import http.client conn = http.client.HTTPSConnection("") headers = { 'authorization': "Bearer {yourAccessToken}" } conn.request("GET", "/{yourDomain}/api/v2/users/%7BuserId%7D", headers=headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' url = URI("https://{yourDomain}/api/v2/users/%7BuserId%7D") @@ -198,8 +217,10 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer {yourAccessToken}' response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` lines +```swift Swift +import Foundation let headers = ["authorization": "Bearer {yourAccessToken}"] let request = NSMutableURLRequest(url: NSURL(string: "https://{yourDomain}/api/v2/users/%7BuserId%7D")! as URL, cachePolicy: .useProtocolCachePolicy, @@ -215,20 +236,9 @@ let httpResponse = response as? HTTPURLResponse print(httpResponse) } }) -dataTask.resume()`; - - - lines - - lines - - lines - - lines - - lines - - +dataTask.resume() +``` + 次の値を置き換えます: diff --git a/main/docs/ja-jp/authenticate/identity-providers/enterprise-identity-providers/oidc.mdx b/main/docs/ja-jp/authenticate/identity-providers/enterprise-identity-providers/oidc.mdx index e627d754b..e99a165d3 100644 --- a/main/docs/ja-jp/authenticate/identity-providers/enterprise-identity-providers/oidc.mdx +++ b/main/docs/ja-jp/authenticate/identity-providers/enterprise-identity-providers/oidc.mdx @@ -10,6 +10,7 @@ permalink: "oidc" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; ## 前提条件 @@ -213,16 +214,22 @@ Auth0 Dashboardを介した構成を可能にするためには、OpenID Connect #### ディスカバリーエンドポイントでフロントチャネルを使用 -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/api/v2/connections' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ - --data '{ "strategy": "oidc", "name": "CONNECTION_NAME", "options": { "type": "front_channel", "discovery_url": "https://IDP_DOMAIN/.well-known/openid-configuration", "client_id" : "IDP_CLIENT_ID", "scopes": "openid profile" } }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/connections"); + --data '{ "strategy": "oidc", "name": "CONNECTION_NAME", "options": { "type": "front_channel", "discovery_url": "https://IDP_DOMAIN/.well-known/openid-configuration", "client_id" : "IDP_CLIENT_ID", "scopes": "openid profile" } }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/connections"); var request = new RestRequest(Method.POST); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); -request.AddParameter("undefined", "{ \"strategy\": \"oidc\", \"name\": \"CONNECTION_NAME\", \"options\": { \"type\": \"front_channel\", \"discovery_url\": \"https://IDP_DOMAIN/.well-known/openid-configuration\", \"client_id\" : \"IDP_CLIENT_ID\", \"scopes\": \"openid profile\" } }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("undefined", "{ "strategy": "oidc", "name": "CONNECTION_NAME", "options": { "type": "front_channel", "discovery_url": "https://IDP_DOMAIN/.well-known/openid-configuration", "client_id" : "IDP_CLIENT_ID", "scopes": "openid profile" } }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -235,7 +242,7 @@ func main() { url := "https://{yourDomain}/api/v2/connections" - payload := strings.NewReader("{ \"strategy\": \"oidc\", \"name\": \"CONNECTION_NAME\", \"options\": { \"type\": \"front_channel\", \"discovery_url\": \"https://IDP_DOMAIN/.well-known/openid-configuration\", \"client_id\" : \"IDP_CLIENT_ID\", \"scopes\": \"openid profile\" } }") + payload := strings.NewReader("{ "strategy": "oidc", "name": "CONNECTION_NAME", "options": { "type": "front_channel", "discovery_url": "https://IDP_DOMAIN/.well-known/openid-configuration", "client_id" : "IDP_CLIENT_ID", "scopes": "openid profile" } }") req, _ := http.NewRequest("POST", url, payload) @@ -249,12 +256,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/connections") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/connections") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") - .body("{ \"strategy\": \"oidc\", \"name\": \"CONNECTION_NAME\", \"options\": { \"type\": \"front_channel\", \"discovery_url\": \"https://IDP_DOMAIN/.well-known/openid-configuration\", \"client_id\" : \"IDP_CLIENT_ID\", \"scopes\": \"openid profile\" } }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "strategy": "oidc", "name": "CONNECTION_NAME", "options": { "type": "front_channel", "discovery_url": "https://IDP_DOMAIN/.well-known/openid-configuration", "client_id" : "IDP_CLIENT_ID", "scopes": "openid profile" } }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -276,8 +287,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN" }; NSDictionary *parameters = @{ @"strategy": @"oidc", @@ -303,8 +316,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/connections", @@ -314,7 +329,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{ \"strategy\": \"oidc\", \"name\": \"CONNECTION_NAME\", \"options\": { \"type\": \"front_channel\", \"discovery_url\": \"https://IDP_DOMAIN/.well-known/openid-configuration\", \"client_id\" : \"IDP_CLIENT_ID\", \"scopes\": \"openid profile\" } }", + CURLOPT_POSTFIELDS => "{ "strategy": "oidc", "name": "CONNECTION_NAME", "options": { "type": "front_channel", "discovery_url": "https://IDP_DOMAIN/.well-known/openid-configuration", "client_id" : "IDP_CLIENT_ID", "scopes": "openid profile" } }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN" ], @@ -329,12 +344,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"strategy\": \"oidc\", \"name\": \"CONNECTION_NAME\", \"options\": { \"type\": \"front_channel\", \"discovery_url\": \"https://IDP_DOMAIN/.well-known/openid-configuration\", \"client_id\" : \"IDP_CLIENT_ID\", \"scopes\": \"openid profile\" } }" +payload = "{ "strategy": "oidc", "name": "CONNECTION_NAME", "options": { "type": "front_channel", "discovery_url": "https://IDP_DOMAIN/.well-known/openid-configuration", "client_id" : "IDP_CLIENT_ID", "scopes": "openid profile" } }" headers = { 'authorization': "Bearer MGMT_API_ACCESS_TOKEN" } @@ -343,8 +360,10 @@ conn.request("POST", "/{yourDomain}/api/v2/connections", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -356,11 +375,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' -request.body = "{ \"strategy\": \"oidc\", \"name\": \"CONNECTION_NAME\", \"options\": { \"type\": \"front_channel\", \"discovery_url\": \"https://IDP_DOMAIN/.well-known/openid-configuration\", \"client_id\" : \"IDP_CLIENT_ID\", \"scopes\": \"openid profile\" } }" +request.body = "{ "strategy": "oidc", "name": "CONNECTION_NAME", "options": { "type": "front_channel", "discovery_url": "https://IDP_DOMAIN/.well-known/openid-configuration", "client_id" : "IDP_CLIENT_ID", "scopes": "openid profile" } }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer MGMT_API_ACCESS_TOKEN"] let parameters = [ @@ -393,33 +414,28 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + #### ディスカバリーエンドポイントでバックチャネルを使用 -export const codeExample11 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/api/v2/connections' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ - --data '{ "strategy": "oidc", "name": "CONNECTION_NAME", "options": { "type": "back_channel", "discovery_url": "https://IDP_DOMAIN/.well-known/openid-configuration", "client_id" : "IDP_CLIENT_ID", "client_secret" : "IDP_CLIENT_SECRET", "scopes": "openid profile" } }'`; -export const codeExample12 = `var client = new RestClient("https://{yourDomain}/api/v2/connections"); + --data '{ "strategy": "oidc", "name": "CONNECTION_NAME", "options": { "type": "back_channel", "discovery_url": "https://IDP_DOMAIN/.well-known/openid-configuration", "client_id" : "IDP_CLIENT_ID", "client_secret" : "IDP_CLIENT_SECRET", "scopes": "openid profile" } }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/connections"); var request = new RestRequest(Method.POST); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); -request.AddParameter("undefined", "{ \"strategy\": \"oidc\", \"name\": \"CONNECTION_NAME\", \"options\": { \"type\": \"back_channel\", \"discovery_url\": \"https://IDP_DOMAIN/.well-known/openid-configuration\", \"client_id\" : \"IDP_CLIENT_ID\", \"client_secret\" : \"IDP_CLIENT_SECRET\", \"scopes\": \"openid profile\" } }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample13 = `package main +request.AddParameter("undefined", "{ "strategy": "oidc", "name": "CONNECTION_NAME", "options": { "type": "back_channel", "discovery_url": "https://IDP_DOMAIN/.well-known/openid-configuration", "client_id" : "IDP_CLIENT_ID", "client_secret" : "IDP_CLIENT_SECRET", "scopes": "openid profile" } }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -432,7 +448,7 @@ func main() { url := "https://{yourDomain}/api/v2/connections" - payload := strings.NewReader("{ \"strategy\": \"oidc\", \"name\": \"CONNECTION_NAME\", \"options\": { \"type\": \"back_channel\", \"discovery_url\": \"https://IDP_DOMAIN/.well-known/openid-configuration\", \"client_id\" : \"IDP_CLIENT_ID\", \"client_secret\" : \"IDP_CLIENT_SECRET\", \"scopes\": \"openid profile\" } }") + payload := strings.NewReader("{ "strategy": "oidc", "name": "CONNECTION_NAME", "options": { "type": "back_channel", "discovery_url": "https://IDP_DOMAIN/.well-known/openid-configuration", "client_id" : "IDP_CLIENT_ID", "client_secret" : "IDP_CLIENT_SECRET", "scopes": "openid profile" } }") req, _ := http.NewRequest("POST", url, payload) @@ -446,12 +462,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample14 = `HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/connections") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/connections") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") - .body("{ \"strategy\": \"oidc\", \"name\": \"CONNECTION_NAME\", \"options\": { \"type\": \"back_channel\", \"discovery_url\": \"https://IDP_DOMAIN/.well-known/openid-configuration\", \"client_id\" : \"IDP_CLIENT_ID\", \"client_secret\" : \"IDP_CLIENT_SECRET\", \"scopes\": \"openid profile\" } }") - .asString();`; -export const codeExample15 = `var axios = require("axios").default; + .body("{ "strategy": "oidc", "name": "CONNECTION_NAME", "options": { "type": "back_channel", "discovery_url": "https://IDP_DOMAIN/.well-known/openid-configuration", "client_id" : "IDP_CLIENT_ID", "client_secret" : "IDP_CLIENT_SECRET", "scopes": "openid profile" } }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -474,8 +494,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample16 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN" }; NSDictionary *parameters = @{ @"strategy": @"oidc", @@ -501,8 +523,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/connections", @@ -512,7 +536,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{ \"strategy\": \"oidc\", \"name\": \"CONNECTION_NAME\", \"options\": { \"type\": \"back_channel\", \"discovery_url\": \"https://IDP_DOMAIN/.well-known/openid-configuration\", \"client_id\" : \"IDP_CLIENT_ID\", \"client_secret\" : \"IDP_CLIENT_SECRET\", \"scopes\": \"openid profile\" } }", + CURLOPT_POSTFIELDS => "{ "strategy": "oidc", "name": "CONNECTION_NAME", "options": { "type": "back_channel", "discovery_url": "https://IDP_DOMAIN/.well-known/openid-configuration", "client_id" : "IDP_CLIENT_ID", "client_secret" : "IDP_CLIENT_SECRET", "scopes": "openid profile" } }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN" ], @@ -527,12 +551,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"strategy\": \"oidc\", \"name\": \"CONNECTION_NAME\", \"options\": { \"type\": \"back_channel\", \"discovery_url\": \"https://IDP_DOMAIN/.well-known/openid-configuration\", \"client_id\" : \"IDP_CLIENT_ID\", \"client_secret\" : \"IDP_CLIENT_SECRET\", \"scopes\": \"openid profile\" } }" +payload = "{ "strategy": "oidc", "name": "CONNECTION_NAME", "options": { "type": "back_channel", "discovery_url": "https://IDP_DOMAIN/.well-known/openid-configuration", "client_id" : "IDP_CLIENT_ID", "client_secret" : "IDP_CLIENT_SECRET", "scopes": "openid profile" } }" headers = { 'authorization': "Bearer MGMT_API_ACCESS_TOKEN" } @@ -541,8 +567,10 @@ conn.request("POST", "/{yourDomain}/api/v2/connections", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -554,11 +582,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' -request.body = "{ \"strategy\": \"oidc\", \"name\": \"CONNECTION_NAME\", \"options\": { \"type\": \"back_channel\", \"discovery_url\": \"https://IDP_DOMAIN/.well-known/openid-configuration\", \"client_id\" : \"IDP_CLIENT_ID\", \"client_secret\" : \"IDP_CLIENT_SECRET\", \"scopes\": \"openid profile\" } }" +request.body = "{ "strategy": "oidc", "name": "CONNECTION_NAME", "options": { "type": "back_channel", "discovery_url": "https://IDP_DOMAIN/.well-known/openid-configuration", "client_id" : "IDP_CLIENT_ID", "client_secret" : "IDP_CLIENT_SECRET", "scopes": "openid profile" } }" response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer MGMT_API_ACCESS_TOKEN"] let parameters = [ @@ -592,33 +622,28 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + #### バックチャネルを使って発行者の設定を指定 -export const codeExample21 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/api/v2/connections' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ - --data '{ "strategy": "oidc", "name": "CONNECTION_NAME", "options": { "type": "back_channel", "issuer": "https://IDP_DOMAIN", "authorization_endpoint": "https://IDP_DOMAIN/authorize", "client_secret" : "IDP_CLIENT_SECRET", "client_id" : "IDP_CLIENT_ID", "scopes": "openid profile" } }'`; -export const codeExample22 = `var client = new RestClient("https://{yourDomain}/api/v2/connections"); + --data '{ "strategy": "oidc", "name": "CONNECTION_NAME", "options": { "type": "back_channel", "issuer": "https://IDP_DOMAIN", "authorization_endpoint": "https://IDP_DOMAIN/authorize", "client_secret" : "IDP_CLIENT_SECRET", "client_id" : "IDP_CLIENT_ID", "scopes": "openid profile" } }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/connections"); var request = new RestRequest(Method.POST); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); -request.AddParameter("undefined", "{ \"strategy\": \"oidc\", \"name\": \"CONNECTION_NAME\", \"options\": { \"type\": \"back_channel\", \"issuer\": \"https://IDP_DOMAIN\", \"authorization_endpoint\": \"https://IDP_DOMAIN/authorize\", \"client_secret\" : \"IDP_CLIENT_SECRET\", \"client_id\" : \"IDP_CLIENT_ID\", \"scopes\": \"openid profile\" } }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample23 = `package main +request.AddParameter("undefined", "{ "strategy": "oidc", "name": "CONNECTION_NAME", "options": { "type": "back_channel", "issuer": "https://IDP_DOMAIN", "authorization_endpoint": "https://IDP_DOMAIN/authorize", "client_secret" : "IDP_CLIENT_SECRET", "client_id" : "IDP_CLIENT_ID", "scopes": "openid profile" } }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -631,7 +656,7 @@ func main() { url := "https://{yourDomain}/api/v2/connections" - payload := strings.NewReader("{ \"strategy\": \"oidc\", \"name\": \"CONNECTION_NAME\", \"options\": { \"type\": \"back_channel\", \"issuer\": \"https://IDP_DOMAIN\", \"authorization_endpoint\": \"https://IDP_DOMAIN/authorize\", \"client_secret\" : \"IDP_CLIENT_SECRET\", \"client_id\" : \"IDP_CLIENT_ID\", \"scopes\": \"openid profile\" } }") + payload := strings.NewReader("{ "strategy": "oidc", "name": "CONNECTION_NAME", "options": { "type": "back_channel", "issuer": "https://IDP_DOMAIN", "authorization_endpoint": "https://IDP_DOMAIN/authorize", "client_secret" : "IDP_CLIENT_SECRET", "client_id" : "IDP_CLIENT_ID", "scopes": "openid profile" } }") req, _ := http.NewRequest("POST", url, payload) @@ -645,12 +670,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample24 = `HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/connections") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/connections") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") - .body("{ \"strategy\": \"oidc\", \"name\": \"CONNECTION_NAME\", \"options\": { \"type\": \"back_channel\", \"issuer\": \"https://IDP_DOMAIN\", \"authorization_endpoint\": \"https://IDP_DOMAIN/authorize\", \"client_secret\" : \"IDP_CLIENT_SECRET\", \"client_id\" : \"IDP_CLIENT_ID\", \"scopes\": \"openid profile\" } }") - .asString();`; -export const codeExample25 = `var axios = require("axios").default; + .body("{ "strategy": "oidc", "name": "CONNECTION_NAME", "options": { "type": "back_channel", "issuer": "https://IDP_DOMAIN", "authorization_endpoint": "https://IDP_DOMAIN/authorize", "client_secret" : "IDP_CLIENT_SECRET", "client_id" : "IDP_CLIENT_ID", "scopes": "openid profile" } }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -674,8 +703,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample26 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN" }; NSDictionary *parameters = @{ @"strategy": @"oidc", @@ -701,8 +732,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample27 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/connections", @@ -712,7 +745,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{ \"strategy\": \"oidc\", \"name\": \"CONNECTION_NAME\", \"options\": { \"type\": \"back_channel\", \"issuer\": \"https://IDP_DOMAIN\", \"authorization_endpoint\": \"https://IDP_DOMAIN/authorize\", \"client_secret\" : \"IDP_CLIENT_SECRET\", \"client_id\" : \"IDP_CLIENT_ID\", \"scopes\": \"openid profile\" } }", + CURLOPT_POSTFIELDS => "{ "strategy": "oidc", "name": "CONNECTION_NAME", "options": { "type": "back_channel", "issuer": "https://IDP_DOMAIN", "authorization_endpoint": "https://IDP_DOMAIN/authorize", "client_secret" : "IDP_CLIENT_SECRET", "client_id" : "IDP_CLIENT_ID", "scopes": "openid profile" } }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN" ], @@ -727,12 +760,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample28 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"strategy\": \"oidc\", \"name\": \"CONNECTION_NAME\", \"options\": { \"type\": \"back_channel\", \"issuer\": \"https://IDP_DOMAIN\", \"authorization_endpoint\": \"https://IDP_DOMAIN/authorize\", \"client_secret\" : \"IDP_CLIENT_SECRET\", \"client_id\" : \"IDP_CLIENT_ID\", \"scopes\": \"openid profile\" } }" +payload = "{ "strategy": "oidc", "name": "CONNECTION_NAME", "options": { "type": "back_channel", "issuer": "https://IDP_DOMAIN", "authorization_endpoint": "https://IDP_DOMAIN/authorize", "client_secret" : "IDP_CLIENT_SECRET", "client_id" : "IDP_CLIENT_ID", "scopes": "openid profile" } }" headers = { 'authorization': "Bearer MGMT_API_ACCESS_TOKEN" } @@ -741,8 +776,10 @@ conn.request("POST", "/{yourDomain}/api/v2/connections", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample29 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -754,11 +791,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' -request.body = "{ \"strategy\": \"oidc\", \"name\": \"CONNECTION_NAME\", \"options\": { \"type\": \"back_channel\", \"issuer\": \"https://IDP_DOMAIN\", \"authorization_endpoint\": \"https://IDP_DOMAIN/authorize\", \"client_secret\" : \"IDP_CLIENT_SECRET\", \"client_id\" : \"IDP_CLIENT_ID\", \"scopes\": \"openid profile\" } }" +request.body = "{ "strategy": "oidc", "name": "CONNECTION_NAME", "options": { "type": "back_channel", "issuer": "https://IDP_DOMAIN", "authorization_endpoint": "https://IDP_DOMAIN/authorize", "client_secret" : "IDP_CLIENT_SECRET", "client_id" : "IDP_CLIENT_ID", "scopes": "openid profile" } }" response = http.request(request) -puts response.read_body`; -export const codeExample30 = `imimport Foundation +puts response.read_body +``` +```swift Swift +imimport Foundation let headers = ["authorization": "Bearer MGMT_API_ACCESS_TOKEN"] let parameters = [ @@ -793,33 +832,28 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + #### フロントチャネルを使って発行者の設定を指定 -export const codeExample31 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/api/v2/connections' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ - --data '{ "strategy": "oidc", "name": "CONNECTION_NAME", "options": { "type": "front_channel", "issuer": "https://IDP_DOMAIN", "authorization_endpoint": "https://IDP_DOMAIN/authorize", "token_endpoint": "https://IDP_DOMAIN/oauth/token", "client_id" : "IDP_CLIENT_ID", "scopes": "openid profile" } }'`; -export const codeExample32 = `var client = new RestClient("https://{yourDomain}/api/v2/connections"); + --data '{ "strategy": "oidc", "name": "CONNECTION_NAME", "options": { "type": "front_channel", "issuer": "https://IDP_DOMAIN", "authorization_endpoint": "https://IDP_DOMAIN/authorize", "token_endpoint": "https://IDP_DOMAIN/oauth/token", "client_id" : "IDP_CLIENT_ID", "scopes": "openid profile" } }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/connections"); var request = new RestRequest(Method.POST); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); -request.AddParameter("undefined", "{ \"strategy\": \"oidc\", \"name\": \"CONNECTION_NAME\", \"options\": { \"type\": \"front_channel\", \"issuer\": \"https://IDP_DOMAIN\", \"authorization_endpoint\": \"https://IDP_DOMAIN/authorize\", \"token_endpoint\": \"https://IDP_DOMAIN/oauth/token\", \"client_id\" : \"IDP_CLIENT_ID\", \"scopes\": \"openid profile\" } }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample33 = `package main +request.AddParameter("undefined", "{ "strategy": "oidc", "name": "CONNECTION_NAME", "options": { "type": "front_channel", "issuer": "https://IDP_DOMAIN", "authorization_endpoint": "https://IDP_DOMAIN/authorize", "token_endpoint": "https://IDP_DOMAIN/oauth/token", "client_id" : "IDP_CLIENT_ID", "scopes": "openid profile" } }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -832,7 +866,7 @@ func main() { url := "https://{yourDomain}/api/v2/connections" - payload := strings.NewReader("{ \"strategy\": \"oidc\", \"name\": \"CONNECTION_NAME\", \"options\": { \"type\": \"front_channel\", \"issuer\": \"https://IDP_DOMAIN\", \"authorization_endpoint\": \"https://IDP_DOMAIN/authorize\", \"token_endpoint\": \"https://IDP_DOMAIN/oauth/token\", \"client_id\" : \"IDP_CLIENT_ID\", \"scopes\": \"openid profile\" } }") + payload := strings.NewReader("{ "strategy": "oidc", "name": "CONNECTION_NAME", "options": { "type": "front_channel", "issuer": "https://IDP_DOMAIN", "authorization_endpoint": "https://IDP_DOMAIN/authorize", "token_endpoint": "https://IDP_DOMAIN/oauth/token", "client_id" : "IDP_CLIENT_ID", "scopes": "openid profile" } }") req, _ := http.NewRequest("POST", url, payload) @@ -846,12 +880,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample34 = `HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/connections") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/connections") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") - .body("{ \"strategy\": \"oidc\", \"name\": \"CONNECTION_NAME\", \"options\": { \"type\": \"front_channel\", \"issuer\": \"https://IDP_DOMAIN\", \"authorization_endpoint\": \"https://IDP_DOMAIN/authorize\", \"token_endpoint\": \"https://IDP_DOMAIN/oauth/token\", \"client_id\" : \"IDP_CLIENT_ID\", \"scopes\": \"openid profile\" } }") - .asString();`; -export const codeExample35 = `var axios = require("axios").default; + .body("{ "strategy": "oidc", "name": "CONNECTION_NAME", "options": { "type": "front_channel", "issuer": "https://IDP_DOMAIN", "authorization_endpoint": "https://IDP_DOMAIN/authorize", "token_endpoint": "https://IDP_DOMAIN/oauth/token", "client_id" : "IDP_CLIENT_ID", "scopes": "openid profile" } }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -875,8 +913,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample36 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN" }; NSDictionary *parameters = @{ @"strategy": @"oidc", @@ -902,8 +942,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample37 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/connections", @@ -913,7 +955,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{ \"strategy\": \"oidc\", \"name\": \"CONNECTION_NAME\", \"options\": { \"type\": \"front_channel\", \"issuer\": \"https://IDP_DOMAIN\", \"authorization_endpoint\": \"https://IDP_DOMAIN/authorize\", \"token_endpoint\": \"https://IDP_DOMAIN/oauth/token\", \"client_id\" : \"IDP_CLIENT_ID\", \"scopes\": \"openid profile\" } }", + CURLOPT_POSTFIELDS => "{ "strategy": "oidc", "name": "CONNECTION_NAME", "options": { "type": "front_channel", "issuer": "https://IDP_DOMAIN", "authorization_endpoint": "https://IDP_DOMAIN/authorize", "token_endpoint": "https://IDP_DOMAIN/oauth/token", "client_id" : "IDP_CLIENT_ID", "scopes": "openid profile" } }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN" ], @@ -928,12 +970,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample38 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"strategy\": \"oidc\", \"name\": \"CONNECTION_NAME\", \"options\": { \"type\": \"front_channel\", \"issuer\": \"https://IDP_DOMAIN\", \"authorization_endpoint\": \"https://IDP_DOMAIN/authorize\", \"token_endpoint\": \"https://IDP_DOMAIN/oauth/token\", \"client_id\" : \"IDP_CLIENT_ID\", \"scopes\": \"openid profile\" } }" +payload = "{ "strategy": "oidc", "name": "CONNECTION_NAME", "options": { "type": "front_channel", "issuer": "https://IDP_DOMAIN", "authorization_endpoint": "https://IDP_DOMAIN/authorize", "token_endpoint": "https://IDP_DOMAIN/oauth/token", "client_id" : "IDP_CLIENT_ID", "scopes": "openid profile" } }" headers = { 'authorization': "Bearer MGMT_API_ACCESS_TOKEN" } @@ -942,8 +986,10 @@ conn.request("POST", "/{yourDomain}/api/v2/connections", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample39 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -955,11 +1001,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' -request.body = "{ \"strategy\": \"oidc\", \"name\": \"CONNECTION_NAME\", \"options\": { \"type\": \"front_channel\", \"issuer\": \"https://IDP_DOMAIN\", \"authorization_endpoint\": \"https://IDP_DOMAIN/authorize\", \"token_endpoint\": \"https://IDP_DOMAIN/oauth/token\", \"client_id\" : \"IDP_CLIENT_ID\", \"scopes\": \"openid profile\" } }" +request.body = "{ "strategy": "oidc", "name": "CONNECTION_NAME", "options": { "type": "front_channel", "issuer": "https://IDP_DOMAIN", "authorization_endpoint": "https://IDP_DOMAIN/authorize", "token_endpoint": "https://IDP_DOMAIN/oauth/token", "client_id" : "IDP_CLIENT_ID", "scopes": "openid profile" } }" response = http.request(request) -puts response.read_body`; -export const codeExample40 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer MGMT_API_ACCESS_TOKEN"] let parameters = [ @@ -994,20 +1042,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ## PKCEとクレームのマッピングを構成する diff --git a/main/docs/ja-jp/authenticate/identity-providers/enterprise-identity-providers/saml.mdx b/main/docs/ja-jp/authenticate/identity-providers/enterprise-identity-providers/saml.mdx index 61f2d2631..2bb811c83 100644 --- a/main/docs/ja-jp/authenticate/identity-providers/enterprise-identity-providers/saml.mdx +++ b/main/docs/ja-jp/authenticate/identity-providers/enterprise-identity-providers/saml.mdx @@ -10,6 +10,7 @@ permalink: "saml" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Auth0を使用すると、SAML IDプロバイダー(IdP)の接続を作成することができます。 @@ -181,20 +182,26 @@ SAMLログインでは、Auth0はサービスプロバイダーとして機能 [接続作成エンドポイント](/docs/ja-jp/api/management/v2#!/Connections/patch_connections_by_id)に`POST`呼び出しを行います。`MGMT_API_ACCESS_TOKEN`、`CONNECTION_NAME`、`SIGN_IN_ENDPOINT_URL`、`SIGN_OUT_ENDPOINT_URL`と`BASE64_SIGNING_CERT`のプレースホルダーをそれぞれManagement APIのアクセストークン、接続名、サインインURL、サインアウトURLとBase64エンコードされた署名証明書(PEMまたはCERの形式)に置き換えます。 -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/api/v2/connections' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{ "strategy": "samlp", "name": "CONNECTION_NAME", "options": { "signInEndpoint": "SIGN_IN_ENDPOINT_URL", "signOutEndpoint": "SIGN_OUT_ENDPOINT_URL", "signatureAlgorithm": "rsa-sha256", "digestAlgorithm": "sha256", "fieldsMap": {}, "signingCert": "BASE64_SIGNING_CERT" } }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/connections"); + --data '{ "strategy": "samlp", "name": "CONNECTION_NAME", "options": { "signInEndpoint": "SIGN_IN_ENDPOINT_URL", "signOutEndpoint": "SIGN_OUT_ENDPOINT_URL", "signatureAlgorithm": "rsa-sha256", "digestAlgorithm": "sha256", "fieldsMap": {}, "signingCert": "BASE64_SIGNING_CERT" } }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/connections"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{ \"strategy\": \"samlp\", \"name\": \"CONNECTION_NAME\", \"options\": { \"signInEndpoint\": \"SIGN_IN_ENDPOINT_URL\", \"signOutEndpoint\": \"SIGN_OUT_ENDPOINT_URL\", \"signatureAlgorithm\": \"rsa-sha256\", \"digestAlgorithm\": \"sha256\", \"fieldsMap\": {}, \"signingCert\": \"BASE64_SIGNING_CERT\" } }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "strategy": "samlp", "name": "CONNECTION_NAME", "options": { "signInEndpoint": "SIGN_IN_ENDPOINT_URL", "signOutEndpoint": "SIGN_OUT_ENDPOINT_URL", "signatureAlgorithm": "rsa-sha256", "digestAlgorithm": "sha256", "fieldsMap": {}, "signingCert": "BASE64_SIGNING_CERT" } }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -207,7 +214,7 @@ func main() { url := "https://{yourDomain}/api/v2/connections" - payload := strings.NewReader("{ \"strategy\": \"samlp\", \"name\": \"CONNECTION_NAME\", \"options\": { \"signInEndpoint\": \"SIGN_IN_ENDPOINT_URL\", \"signOutEndpoint\": \"SIGN_OUT_ENDPOINT_URL\", \"signatureAlgorithm\": \"rsa-sha256\", \"digestAlgorithm\": \"sha256\", \"fieldsMap\": {}, \"signingCert\": \"BASE64_SIGNING_CERT\" } }") + payload := strings.NewReader("{ "strategy": "samlp", "name": "CONNECTION_NAME", "options": { "signInEndpoint": "SIGN_IN_ENDPOINT_URL", "signOutEndpoint": "SIGN_OUT_ENDPOINT_URL", "signatureAlgorithm": "rsa-sha256", "digestAlgorithm": "sha256", "fieldsMap": {}, "signingCert": "BASE64_SIGNING_CERT" } }") req, _ := http.NewRequest("POST", url, payload) @@ -223,14 +230,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/connections") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/connections") .header("content-type", "application/json") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ \"strategy\": \"samlp\", \"name\": \"CONNECTION_NAME\", \"options\": { \"signInEndpoint\": \"SIGN_IN_ENDPOINT_URL\", \"signOutEndpoint\": \"SIGN_OUT_ENDPOINT_URL\", \"signatureAlgorithm\": \"rsa-sha256\", \"digestAlgorithm\": \"sha256\", \"fieldsMap\": {}, \"signingCert\": \"BASE64_SIGNING_CERT\" } }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "strategy": "samlp", "name": "CONNECTION_NAME", "options": { "signInEndpoint": "SIGN_IN_ENDPOINT_URL", "signOutEndpoint": "SIGN_OUT_ENDPOINT_URL", "signatureAlgorithm": "rsa-sha256", "digestAlgorithm": "sha256", "fieldsMap": {}, "signingCert": "BASE64_SIGNING_CERT" } }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -258,8 +269,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @@ -287,8 +300,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/connections", @@ -298,7 +313,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{ \"strategy\": \"samlp\", \"name\": \"CONNECTION_NAME\", \"options\": { \"signInEndpoint\": \"SIGN_IN_ENDPOINT_URL\", \"signOutEndpoint\": \"SIGN_OUT_ENDPOINT_URL\", \"signatureAlgorithm\": \"rsa-sha256\", \"digestAlgorithm\": \"sha256\", \"fieldsMap\": {}, \"signingCert\": \"BASE64_SIGNING_CERT\" } }", + CURLOPT_POSTFIELDS => "{ "strategy": "samlp", "name": "CONNECTION_NAME", "options": { "signInEndpoint": "SIGN_IN_ENDPOINT_URL", "signOutEndpoint": "SIGN_OUT_ENDPOINT_URL", "signatureAlgorithm": "rsa-sha256", "digestAlgorithm": "sha256", "fieldsMap": {}, "signingCert": "BASE64_SIGNING_CERT" } }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "cache-control: no-cache", @@ -315,12 +330,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"strategy\": \"samlp\", \"name\": \"CONNECTION_NAME\", \"options\": { \"signInEndpoint\": \"SIGN_IN_ENDPOINT_URL\", \"signOutEndpoint\": \"SIGN_OUT_ENDPOINT_URL\", \"signatureAlgorithm\": \"rsa-sha256\", \"digestAlgorithm\": \"sha256\", \"fieldsMap\": {}, \"signingCert\": \"BASE64_SIGNING_CERT\" } }" +payload = "{ "strategy": "samlp", "name": "CONNECTION_NAME", "options": { "signInEndpoint": "SIGN_IN_ENDPOINT_URL", "signOutEndpoint": "SIGN_OUT_ENDPOINT_URL", "signatureAlgorithm": "rsa-sha256", "digestAlgorithm": "sha256", "fieldsMap": {}, "signingCert": "BASE64_SIGNING_CERT" } }" headers = { 'content-type': "application/json", @@ -333,8 +350,10 @@ conn.request("POST", "/{yourDomain}/api/v2/connections", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -348,11 +367,13 @@ request = Net::HTTP::Post.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ \"strategy\": \"samlp\", \"name\": \"CONNECTION_NAME\", \"options\": { \"signInEndpoint\": \"SIGN_IN_ENDPOINT_URL\", \"signOutEndpoint\": \"SIGN_OUT_ENDPOINT_URL\", \"signatureAlgorithm\": \"rsa-sha256\", \"digestAlgorithm\": \"sha256\", \"fieldsMap\": {}, \"signingCert\": \"BASE64_SIGNING_CERT\" } }" +request.body = "{ "strategy": "samlp", "name": "CONNECTION_NAME", "options": { "signInEndpoint": "SIGN_IN_ENDPOINT_URL", "signOutEndpoint": "SIGN_OUT_ENDPOINT_URL", "signatureAlgorithm": "rsa-sha256", "digestAlgorithm": "sha256", "fieldsMap": {}, "signingCert": "BASE64_SIGNING_CERT" } }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -391,20 +412,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
    @@ -463,20 +473,26 @@ SAMLの構成フィールドをそれぞれ指定する代わりに、構成値 `metadataXml`オプションを使用して、ドキュメントの内容を提供します。 -export const codeExample11 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/api/v2/connections' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{ "strategy": "samlp", "name": "CONNECTION_NAME", "options": { "metadataXml": "..." } }'`; -export const codeExample12 = `var client = new RestClient("https://{yourDomain}/api/v2/connections"); + --data '{ "strategy": "samlp", "name": "CONNECTION_NAME", "options": { "metadataXml": "..." } }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/connections"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{ \"strategy\": \"samlp\", \"name\": \"CONNECTION_NAME\", \"options\": { \"metadataXml\": \"...\" } }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample13 = `package main +request.AddParameter("application/json", "{ "strategy": "samlp", "name": "CONNECTION_NAME", "options": { "metadataXml": "..." } }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -489,7 +505,7 @@ func main() { url := "https://{yourDomain}/api/v2/connections" - payload := strings.NewReader("{ \"strategy\": \"samlp\", \"name\": \"CONNECTION_NAME\", \"options\": { \"metadataXml\": \"...\" } }") + payload := strings.NewReader("{ "strategy": "samlp", "name": "CONNECTION_NAME", "options": { "metadataXml": "..." } }") req, _ := http.NewRequest("POST", url, payload) @@ -505,14 +521,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample14 = `HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/connections") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/connections") .header("content-type", "application/json") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ \"strategy\": \"samlp\", \"name\": \"CONNECTION_NAME\", \"options\": { \"metadataXml\": \"...\" } }") - .asString();`; -export const codeExample15 = `var axios = require("axios").default; + .body("{ "strategy": "samlp", "name": "CONNECTION_NAME", "options": { "metadataXml": "..." } }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -526,7 +546,7 @@ var options = { strategy: 'samlp', name: 'CONNECTION_NAME', options: { - metadataXml: '...' + metadataXml: '...' } } }; @@ -535,8 +555,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample16 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @@ -564,8 +586,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/connections", @@ -575,7 +599,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{ \"strategy\": \"samlp\", \"name\": \"CONNECTION_NAME\", \"options\": { \"metadataXml\": \"...\" } }", + CURLOPT_POSTFIELDS => "{ "strategy": "samlp", "name": "CONNECTION_NAME", "options": { "metadataXml": "..." } }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "cache-control: no-cache", @@ -592,12 +616,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `iimport http.client +} +``` +```python Python +iimport http.client conn = http.client.HTTPSConnection("") -payload = "{ \"strategy\": \"samlp\", \"name\": \"CONNECTION_NAME\", \"options\": { \"metadataXml\": \"...\" } }" +payload = "{ "strategy": "samlp", "name": "CONNECTION_NAME", "options": { "metadataXml": "..." } }" headers = { 'content-type': "application/json", @@ -610,8 +636,10 @@ conn.request("POST", "/{yourDomain}/api/v2/connections", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -625,11 +653,13 @@ request = Net::HTTP::Post.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ \"strategy\": \"samlp\", \"name\": \"CONNECTION_NAME\", \"options\": { \"metadataXml\": \"...\" } }" +request.body = "{ "strategy": "samlp", "name": "CONNECTION_NAME", "options": { "metadataXml": "..." } }" response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -661,39 +691,34 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ##### メタデータドキュメントのURLを提供する `metadataUrl`オプションを使用して、ドキュメントのURLを提供します。 -export const codeExample21 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/api/v2/connections' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{ "strategy": "samlp", "name": "CONNECTION_NAME", "options": { "metadataUrl": "https://saml-idp/samlp/metadata/uarlU13n63e0feZNJxOCNZ1To3a9H7jX" } }'`; -export const codeExample22 = `var client = new RestClient("https://{yourDomain}/api/v2/connections"); + --data '{ "strategy": "samlp", "name": "CONNECTION_NAME", "options": { "metadataUrl": "https://saml-idp/samlp/metadata/uarlU13n63e0feZNJxOCNZ1To3a9H7jX" } }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/connections"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{ \"strategy\": \"samlp\", \"name\": \"CONNECTION_NAME\", \"options\": { \"metadataUrl\": \"https://saml-idp/samlp/metadata/uarlU13n63e0feZNJxOCNZ1To3a9H7jX\" } }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample23 = `package main +request.AddParameter("application/json", "{ "strategy": "samlp", "name": "CONNECTION_NAME", "options": { "metadataUrl": "https://saml-idp/samlp/metadata/uarlU13n63e0feZNJxOCNZ1To3a9H7jX" } }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -706,7 +731,7 @@ func main() { url := "https://{yourDomain}/api/v2/connections" - payload := strings.NewReader("{ \"strategy\": \"samlp\", \"name\": \"CONNECTION_NAME\", \"options\": { \"metadataUrl\": \"https://saml-idp/samlp/metadata/uarlU13n63e0feZNJxOCNZ1To3a9H7jX\" } }") + payload := strings.NewReader("{ "strategy": "samlp", "name": "CONNECTION_NAME", "options": { "metadataUrl": "https://saml-idp/samlp/metadata/uarlU13n63e0feZNJxOCNZ1To3a9H7jX" } }") req, _ := http.NewRequest("POST", url, payload) @@ -722,14 +747,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample24 = `HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/connections") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/connections") .header("content-type", "application/json") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ \"strategy\": \"samlp\", \"name\": \"CONNECTION_NAME\", \"options\": { \"metadataUrl\": \"https://saml-idp/samlp/metadata/uarlU13n63e0feZNJxOCNZ1To3a9H7jX\" } }") - .asString();`; -export const codeExample25 = `var axios = require("axios").default; + .body("{ "strategy": "samlp", "name": "CONNECTION_NAME", "options": { "metadataUrl": "https://saml-idp/samlp/metadata/uarlU13n63e0feZNJxOCNZ1To3a9H7jX" } }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -752,8 +781,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample26 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @@ -781,8 +812,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample27 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/connections", @@ -792,7 +825,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{ \"strategy\": \"samlp\", \"name\": \"CONNECTION_NAME\", \"options\": { \"metadataUrl\": \"https://saml-idp/samlp/metadata/uarlU13n63e0feZNJxOCNZ1To3a9H7jX\" } }", + CURLOPT_POSTFIELDS => "{ "strategy": "samlp", "name": "CONNECTION_NAME", "options": { "metadataUrl": "https://saml-idp/samlp/metadata/uarlU13n63e0feZNJxOCNZ1To3a9H7jX" } }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "cache-control: no-cache", @@ -809,12 +842,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample28 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"strategy\": \"samlp\", \"name\": \"CONNECTION_NAME\", \"options\": { \"metadataUrl\": \"https://saml-idp/samlp/metadata/uarlU13n63e0feZNJxOCNZ1To3a9H7jX\" } }" +payload = "{ "strategy": "samlp", "name": "CONNECTION_NAME", "options": { "metadataUrl": "https://saml-idp/samlp/metadata/uarlU13n63e0feZNJxOCNZ1To3a9H7jX" } }" headers = { 'content-type': "application/json", @@ -827,8 +862,10 @@ conn.request("POST", "/{yourDomain}/api/v2/connections", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample29 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -842,11 +879,13 @@ request = Net::HTTP::Post.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ \"strategy\": \"samlp\", \"name\": \"CONNECTION_NAME\", \"options\": { \"metadataUrl\": \"https://saml-idp/samlp/metadata/uarlU13n63e0feZNJxOCNZ1To3a9H7jX\" } }" +request.body = "{ "strategy": "samlp", "name": "CONNECTION_NAME", "options": { "metadataUrl": "https://saml-idp/samlp/metadata/uarlU13n63e0feZNJxOCNZ1To3a9H7jX" } }" response = http.request(request) -puts response.read_body`; -export const codeExample30 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -878,20 +917,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + URLを提供すると、コンテンツが一度だけダウンロードされます。後でURLのコンテンツが変更されても、接続は自動的には再構成されません。 diff --git a/main/docs/ja-jp/authenticate/identity-providers/pass-parameters-to-idps.mdx b/main/docs/ja-jp/authenticate/identity-providers/pass-parameters-to-idps.mdx index 2b4972564..ba3961887 100644 --- a/main/docs/ja-jp/authenticate/identity-providers/pass-parameters-to-idps.mdx +++ b/main/docs/ja-jp/authenticate/identity-providers/pass-parameters-to-idps.mdx @@ -10,6 +10,7 @@ permalink: "pass-parameters-to-idps" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; 認証中、プロバイダー固有のパラメーターをIDプロバイダー(IdP)に渡せます。値は、接続ごとに静的またはユーザーごとに動的のいずれにも設定できます。 @@ -37,16 +38,22 @@ WordPressでは、その response = Unirest.get("https://{yourDomain}/api/v2/connections/%7ByourWordpressConnectionId%7D") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/connections/%7ByourWordpressConnectionId%7D") .header("authorization", "Bearer {yourMgmtApiAccessToken}") .header("content-type", "application/json") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -91,8 +102,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer {yourMgmtApiAccessToken}", @"content-type": @"application/json" }; @@ -113,8 +126,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/connections/%7ByourWordpressConnectionId%7D", @@ -139,8 +154,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -154,8 +171,10 @@ conn.request("GET", "/{yourDomain}/api/v2/connections/%7ByourWordpressConnection res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -170,8 +189,10 @@ request["authorization"] = 'Bearer {yourMgmtApiAccessToken}' request["content-type"] = 'application/json' response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "authorization": "Bearer {yourMgmtApiAccessToken}", @@ -194,20 +215,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + `options`オブジェクトは、次のようになります: @@ -240,18 +250,24 @@ dataTask.resume()`; Management APIの[接続を更新](https://auth0.com/docs/api/management/v2/#!/Connections/patch_connections_by_id)エンドポイントを、本文の`options`オブジェクトを次の通りにして呼び出します: -export const codeExample11 = `curl --request PATCH \ + +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/connections/%7ByourWordpressConnectionId%7D' \ --header 'authorization: Bearer {yourMgmtApiAccessToken}' \ --header 'content-type: application/json' \ - --data '{"options":{"client_id":"","profile":true,"scope":["profile"],"upstream_params":{"blog":{"value":"myblog.wordpress.com"}}}}'`; -export const codeExample12 = `var client = new RestClient("https://{yourDomain}/api/v2/connections/%7ByourWordpressConnectionId%7D"); + --data '{"options":{"client_id":"","profile":true,"scope":["profile"],"upstream_params":{"blog":{"value":"myblog.wordpress.com"}}}}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/connections/%7ByourWordpressConnectionId%7D"); var request = new RestRequest(Method.PATCH); request.AddHeader("authorization", "Bearer {yourMgmtApiAccessToken}"); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\"options\":{\"client_id\":\"\",\"profile\":true,\"scope\":[\"profile\"],\"upstream_params\":{\"blog\":{\"value\":\"myblog.wordpress.com\"}}}}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample13 = `package main +request.AddParameter("application/json", "{"options":{"client_id":"","profile":true,"scope":["profile"],"upstream_params":{"blog":{"value":"myblog.wordpress.com"}}}}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -264,7 +280,7 @@ func main() { url := "https://{yourDomain}/api/v2/connections/%7ByourWordpressConnectionId%7D" - payload := strings.NewReader("{\"options\":{\"client_id\":\"\",\"profile\":true,\"scope\":[\"profile\"],\"upstream_params\":{\"blog\":{\"value\":\"myblog.wordpress.com\"}}}}") + payload := strings.NewReader("{"options":{"client_id":"","profile":true,"scope":["profile"],"upstream_params":{"blog":{"value":"myblog.wordpress.com"}}}}") req, _ := http.NewRequest("PATCH", url, payload) @@ -279,13 +295,17 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample14 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/connections/%7ByourWordpressConnectionId%7D") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/connections/%7ByourWordpressConnectionId%7D") .header("authorization", "Bearer {yourMgmtApiAccessToken}") .header("content-type", "application/json") - .body("{\"options\":{\"client_id\":\"\",\"profile\":true,\"scope\":[\"profile\"],\"upstream_params\":{\"blog\":{\"value\":\"myblog.wordpress.com\"}}}}") - .asString();`; -export const codeExample15 = `var axios = require("axios").default; + .body("{"options":{"client_id":"","profile":true,"scope":["profile"],"upstream_params":{"blog":{"value":"myblog.wordpress.com"}}}}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -308,8 +328,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample16 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer {yourMgmtApiAccessToken}", @"content-type": @"application/json" }; @@ -334,8 +356,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/connections/%7ByourWordpressConnectionId%7D", @@ -345,7 +369,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{\"options\":{\"client_id\":\"\",\"profile\":true,\"scope\":[\"profile\"],\"upstream_params\":{\"blog\":{\"value\":\"myblog.wordpress.com\"}}}}", + CURLOPT_POSTFIELDS => "{"options":{"client_id":"","profile":true,"scope":["profile"],"upstream_params":{"blog":{"value":"myblog.wordpress.com"}}}}", CURLOPT_HTTPHEADER => [ "authorization: Bearer {yourMgmtApiAccessToken}", "content-type: application/json" @@ -361,12 +385,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"options\":{\"client_id\":\"\",\"profile\":true,\"scope\":[\"profile\"],\"upstream_params\":{\"blog\":{\"value\":\"myblog.wordpress.com\"}}}}" +payload = "{"options":{"client_id":"","profile":true,"scope":["profile"],"upstream_params":{"blog":{"value":"myblog.wordpress.com"}}}}" headers = { 'authorization': "Bearer {yourMgmtApiAccessToken}", @@ -378,8 +404,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/connections/%7ByourWordpressConnecti res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -392,11 +420,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Patch.new(url) request["authorization"] = 'Bearer {yourMgmtApiAccessToken}' request["content-type"] = 'application/json' -request.body = "{\"options\":{\"client_id\":\"\",\"profile\":true,\"scope\":[\"profile\"],\"upstream_params\":{\"blog\":{\"value\":\"myblog.wordpress.com\"}}}}" +request.body = "{"options":{"client_id":"","profile":true,"scope":["profile"],"upstream_params":{"blog":{"value":"myblog.wordpress.com"}}}}" response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "authorization": "Bearer {yourMgmtApiAccessToken}", @@ -428,20 +458,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + これで、ユーザーがこの接続と認証するたびに、Wordpress認証エンドポイントへの要求には、クエリパラメーターとなる`blog=myblog.wordpress.com`が含まれるようになります。 @@ -492,16 +511,22 @@ Xにより、任意の`screen_name`のパラメーターをOAuth認証エンド Management APIの[接続の取得](/docs/ja-jp/api/management/v2#!/Connections/get_connections_by_id)エンドポイントを呼び出し、`options`オブジェクトの既存の値を取得します: -export const codeExample21 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/connections/%7ByourXConnectionId%7D' \ --header 'authorization: Bearer {yourMgmtApiAccessToken}' \ - --header 'content-type: application/json'`; -export const codeExample22 = `var client = new RestClient("https://{yourDomain}/api/v2/connections/%7ByourXConnectionId%7D"); + --header 'content-type: application/json' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/connections/%7ByourXConnectionId%7D"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer {yourMgmtApiAccessToken}"); request.AddHeader("content-type", "application/json"); -IRestResponse response = client.Execute(request);`; -export const codeExample23 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -526,12 +551,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample24 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/connections/%7ByourXConnectionId%7D") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/connections/%7ByourXConnectionId%7D") .header("authorization", "Bearer {yourMgmtApiAccessToken}") .header("content-type", "application/json") - .asString();`; -export const codeExample25 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -546,8 +575,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample26 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer {yourMgmtApiAccessToken}", @"content-type": @"application/json" }; @@ -568,8 +599,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample27 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/connections/%7ByourXConnectionId%7D", @@ -594,8 +627,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample28 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -609,8 +644,10 @@ conn.request("GET", "/{yourDomain}/api/v2/connections/%7ByourXConnectionId%7D", res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample29 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -625,8 +662,10 @@ request["authorization"] = 'Bearer {yourMgmtApiAccessToken}' request["content-type"] = 'application/json' response = http.request(request) -puts response.read_body`; -export const codeExample30 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "authorization": "Bearer {yourMgmtApiAccessToken}", @@ -649,20 +688,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + `options`オブジェクトは、次のようになります: @@ -695,18 +723,24 @@ dataTask.resume()`; Management APIの[接続を更新](https://auth0.com/docs/api/management/v2/#!/Connections/patch_connections_by_id)エンドポイントを、本文の`options`オブジェクトを次の通りにして呼び出します: -export const codeExample31 = `curl --request PATCH \ + +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/connections/%7ByourXConnectionId%7D' \ --header 'authorization: Bearer {yourMgmtApiAccessToken}' \ --header 'content-type: application/json' \ - --data '{"options": {"client_id": "{clientId}", "client_secret": "{clientSecret}", "profile": true, "upstream_params": {"screen_name": {"alias": "login_hint"}}}}'`; -export const codeExample32 = `var client = new RestClient("https://{yourDomain}/api/v2/connections/%7ByourXConnectionId%7D"); + --data '{"options": {"client_id": "{clientId}", "client_secret": "{clientSecret}", "profile": true, "upstream_params": {"screen_name": {"alias": "login_hint"}}}}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/connections/%7ByourXConnectionId%7D"); var request = new RestRequest(Method.PATCH); request.AddHeader("authorization", "Bearer {yourMgmtApiAccessToken}"); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\"options\": {\"client_id\": \"{clientId}\", \"client_secret\": \"{clientSecret}\", \"profile\": true, \"upstream_params\": {\"screen_name\": {\"alias\": \"login_hint\"}}}}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample33 = `package main +request.AddParameter("application/json", "{"options": {"client_id": "{clientId}", "client_secret": "{clientSecret}", "profile": true, "upstream_params": {"screen_name": {"alias": "login_hint"}}}}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -719,7 +753,7 @@ func main() { url := "https://{yourDomain}/api/v2/connections/%7ByourXConnectionId%7D" - payload := strings.NewReader("{\"options\": {\"client_id\": \"{clientId}\", \"client_secret\": \"{clientSecret}\", \"profile\": true, \"upstream_params\": {\"screen_name\": {\"alias\": \"login_hint\"}}}}") + payload := strings.NewReader("{"options": {"client_id": "{clientId}", "client_secret": "{clientSecret}", "profile": true, "upstream_params": {"screen_name": {"alias": "login_hint"}}}}") req, _ := http.NewRequest("PATCH", url, payload) @@ -734,13 +768,17 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample34 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/connections/%7ByourXConnectionId%7D") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/connections/%7ByourXConnectionId%7D") .header("authorization", "Bearer {yourMgmtApiAccessToken}") .header("content-type", "application/json") - .body("{\"options\": {\"client_id\": \"{clientId}\", \"client_secret\": \"{clientSecret}\", \"profile\": true, \"upstream_params\": {\"screen_name\": {\"alias\": \"login_hint\"}}}}") - .asString();`; -export const codeExample35 = `var axios = require("axios").default; + .body("{"options": {"client_id": "{clientId}", "client_secret": "{clientSecret}", "profile": true, "upstream_params": {"screen_name": {"alias": "login_hint"}}}}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -763,8 +801,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample36 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer {yourMgmtApiAccessToken}", @"content-type": @"application/json" }; @@ -789,8 +829,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample37 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/connections/%7ByourXConnectionId%7D", @@ -800,7 +842,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{\"options\": {\"client_id\": \"{clientId}\", \"client_secret\": \"{clientSecret}\", \"profile\": true, \"upstream_params\": {\"screen_name\": {\"alias\": \"login_hint\"}}}}", + CURLOPT_POSTFIELDS => "{"options": {"client_id": "{clientId}", "client_secret": "{clientSecret}", "profile": true, "upstream_params": {"screen_name": {"alias": "login_hint"}}}}", CURLOPT_HTTPHEADER => [ "authorization: Bearer {yourMgmtApiAccessToken}", "content-type: application/json" @@ -816,12 +858,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample38 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"options\": {\"client_id\": \"{clientId}\", \"client_secret\": \"{clientSecret}\", \"profile\": true, \"upstream_params\": {\"screen_name\": {\"alias\": \"login_hint\"}}}}" +payload = "{"options": {"client_id": "{clientId}", "client_secret": "{clientSecret}", "profile": true, "upstream_params": {"screen_name": {"alias": "login_hint"}}}}" headers = { 'authorization': "Bearer {yourMgmtApiAccessToken}", @@ -833,8 +877,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/connections/%7ByourXConnectionId%7D" res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample39 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -847,11 +893,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Patch.new(url) request["authorization"] = 'Bearer {yourMgmtApiAccessToken}' request["content-type"] = 'application/json' -request.body = "{\"options\": {\"client_id\": \"{clientId}\", \"client_secret\": \"{clientSecret}\", \"profile\": true, \"upstream_params\": {\"screen_name\": {\"alias\": \"login_hint\"}}}}" +request.body = "{"options": {"client_id": "{clientId}", "client_secret": "{clientSecret}", "profile": true, "upstream_params": {"screen_name": {"alias": "login_hint"}}}}" response = http.request(request) -puts response.read_body`; -export const codeExample40 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "authorization": "Bearer {yourMgmtApiAccessToken}", @@ -883,20 +931,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + #### ログインエンドポイントを呼び出す diff --git a/main/docs/ja-jp/authenticate/identity-providers/promote-connections-to-domain-level.mdx b/main/docs/ja-jp/authenticate/identity-providers/promote-connections-to-domain-level.mdx index 9ad119ce5..9c01bcb24 100644 --- a/main/docs/ja-jp/authenticate/identity-providers/promote-connections-to-domain-level.mdx +++ b/main/docs/ja-jp/authenticate/identity-providers/promote-connections-to-domain-level.mdx @@ -10,6 +10,7 @@ permalink: "promote-connections-to-domain-level" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; テナントの[[Dynamic Client Registration(動的クライアント登録)]](/docs/ja-jp/get-started/applications/dynamic-client-registration)が有効になっている場合は、ドメインレベルの接続に昇格することで、[サードパーティーアプリケーション](/docs/ja-jp/get-started/applications/confidential-and-public-applications/enable-third-party-applications)が接続を利用できるようにすることができます。ドメインレベル接続は、テナント内のすべてのアプリケーションに対して有効または無効になります。 @@ -17,20 +18,26 @@ import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; [接続更新エンドポイント](/docs/ja-jp/api/management/v2#!/Connections/patch_connections_by_id)に`PATCH`呼び出しを行います。必ず、`CONNECTION_ID`と`MGMT_API_ACCESS_TOKEN`のプレースホルダーの値を、それぞれご自身の接続IDとManagement APIのアクセストークンに置き換えてください。 -export const codeExample1 = `curl --request PATCH \ + +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/connections/CONNECTION_ID' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{ "is_domain_connection": true }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/connections/CONNECTION_ID"); + --data '{ "is_domain_connection": true }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/connections/CONNECTION_ID"); var request = new RestRequest(Method.PATCH); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{ \"is_domain_connection\": true }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "is_domain_connection": true }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -43,7 +50,7 @@ func main() { url := "https://{yourDomain}/api/v2/connections/CONNECTION_ID" - payload := strings.NewReader("{ \"is_domain_connection\": true }") + payload := strings.NewReader("{ "is_domain_connection": true }") req, _ := http.NewRequest("PATCH", url, payload) @@ -59,14 +66,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/connections/CONNECTION_ID") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/connections/CONNECTION_ID") .header("content-type", "application/json") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ \"is_domain_connection\": true }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "is_domain_connection": true }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -83,8 +94,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @@ -110,8 +123,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/connections/CONNECTION_ID", @@ -121,7 +136,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{ \"is_domain_connection\": true }", + CURLOPT_POSTFIELDS => "{ "is_domain_connection": true }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "cache-control: no-cache", @@ -138,12 +153,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"is_domain_connection\": true }" +payload = "{ "is_domain_connection": true }" headers = { 'content-type': "application/json", @@ -156,8 +173,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/connections/CONNECTION_ID", payload, res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -171,11 +190,13 @@ request = Net::HTTP::Patch.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ \"is_domain_connection\": true }" +request.body = "{ "is_domain_connection": true }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -203,20 +224,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
    diff --git a/main/docs/ja-jp/authenticate/identity-providers/retrieve-connection-options.mdx b/main/docs/ja-jp/authenticate/identity-providers/retrieve-connection-options.mdx index 023949f3c..a5194f33a 100644 --- a/main/docs/ja-jp/authenticate/identity-providers/retrieve-connection-options.mdx +++ b/main/docs/ja-jp/authenticate/identity-providers/retrieve-connection-options.mdx @@ -10,19 +10,26 @@ permalink: "retrieve-connection-options" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; [接続](/docs/ja-jp/connections)のオプションオブジェクトはAuth0のManagement APIを使用して取得できます。 [接続取得エンドポイント](/docs/ja-jp/api/management/v2#!/Connections/get_connections_by_id)に`GET`呼び出しを行います。`CONNECTION_ID`と`MGMT_API_ACCESS_TOKEN`のプレースホルダーの値を、それぞれ接続IDとManagement APIのアクセストークンに置き換えてください。 -export const codeExample1 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/connections/CONNECTION-ID?fields=options' \ - --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/connections/CONNECTION-ID?fields=options"); + --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/connections/CONNECTION-ID?fields=options"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -46,11 +53,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/connections/CONNECTION-ID?fields=options") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/connections/CONNECTION-ID?fields=options") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -63,8 +74,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN" }; @@ -84,8 +97,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/connections/CONNECTION-ID?fields=options", @@ -109,8 +124,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = ` +} +``` +```import http.client + conn = http.client.HTTPSConnection("") headers = { 'authorization': "Bearer MGMT_API_ACCESS_TOKEN" } @@ -120,8 +137,10 @@ conn.request("GET", "/{yourDomain}/api/v2/connections/CONNECTION-ID?fields=optio res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -135,8 +154,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer MGMT_API_ACCESS_TOKEN"] @@ -156,20 +177,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
    diff --git a/main/docs/ja-jp/authenticate/identity-providers/social-identity-providers/oauth2.mdx b/main/docs/ja-jp/authenticate/identity-providers/social-identity-providers/oauth2.mdx index ee8cd9b85..b6b6b8d4e 100644 --- a/main/docs/ja-jp/authenticate/identity-providers/social-identity-providers/oauth2.mdx +++ b/main/docs/ja-jp/authenticate/identity-providers/social-identity-providers/oauth2.mdx @@ -10,6 +10,7 @@ permalink: "oauth2" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; 最も一般的な[IDプロバイダー(IdP)](/docs/ja-jp/authenticate/identity-providers)は、[Auth0 Dashboard](https://manage.auth0.com/#)や[Auth0 Marketplace](https://marketplace.auth0.com/features/social-connections)から利用できます。ただし、Auth0 Dashboardでは、任意のOAuth 2.0プロバイダーを **カスタムソーシャル接続** として追加することもできます。 @@ -147,16 +148,22 @@ IDプロバイダーのログインボタンにアイコンを追加するには -export const codeExample2 = `curl --request PATCH \ + +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/connections/CONNECTION-ID' \ --header 'content-type: application/json' \ - --data '{ "options": { "client_id": "...", "client_secret": "...", "icon_url": "https://cdn.example.com/assets/icon.png", "scripts": { "fetchUserProfile": "..." }, "authorizationURL": "https://public-auth.example.com/oauth2/authorize", "tokenURL": "https://auth.example.com/oauth2/token", "scope": "auth" }, "enabled_clients": [ "..." ] }, "display_name": "Connection Name"'`; -export const codeExample3 = `var client = new RestClient("https://{yourDomain}/api/v2/connections/CONNECTION-ID"); + --data '{ "options": { "client_id": "...", "client_secret": "...", "icon_url": "https://cdn.example.com/assets/icon.png", "scripts": { "fetchUserProfile": "..." }, "authorizationURL": "https://public-auth.example.com/oauth2/authorize", "tokenURL": "https://auth.example.com/oauth2/token", "scope": "auth" }, "enabled_clients": [ "..." ] }, "display_name": "Connection Name"' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/connections/CONNECTION-ID"); var request = new RestRequest(Method.PATCH); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{ \"options\": { \"client_id\": \"...\", \"client_secret\": \"...\", \"icon_url\": \"https://cdn.example.com/assets/icon.png\", \"scripts\": { \"fetchUserProfile\": \"...\" }, \"authorizationURL\": \"https://public-auth.example.com/oauth2/authorize\", \"tokenURL\": \"https://auth.example.com/oauth2/token\", \"scope\": \"auth\" }, \"enabled_clients\": [ \"...\" ] }, \"display_name\": \"Connection Name\"", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample4 = `package main +request.AddParameter("application/json", "{ "options": { "client_id": "...", "client_secret": "...", "icon_url": "https://cdn.example.com/assets/icon.png", "scripts": { "fetchUserProfile": "..." }, "authorizationURL": "https://public-auth.example.com/oauth2/authorize", "tokenURL": "https://auth.example.com/oauth2/token", "scope": "auth" }, "enabled_clients": [ "..." ] }, "display_name": "Connection Name"", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -169,7 +176,7 @@ func main() { url := "https://{yourDomain}/api/v2/connections/CONNECTION-ID" - payload := strings.NewReader("{ \"options\": { \"client_id\": \"...\", \"client_secret\": \"...\", \"icon_url\": \"https://cdn.example.com/assets/icon.png\", \"scripts\": { \"fetchUserProfile\": \"...\" }, \"authorizationURL\": \"https://public-auth.example.com/oauth2/authorize\", \"tokenURL\": \"https://auth.example.com/oauth2/token\", \"scope\": \"auth\" }, \"enabled_clients\": [ \"...\" ] }, \"display_name\": \"Connection Name\"") + payload := strings.NewReader("{ "options": { "client_id": "...", "client_secret": "...", "icon_url": "https://cdn.example.com/assets/icon.png", "scripts": { "fetchUserProfile": "..." }, "authorizationURL": "https://public-auth.example.com/oauth2/authorize", "tokenURL": "https://auth.example.com/oauth2/token", "scope": "auth" }, "enabled_clients": [ "..." ] }, "display_name": "Connection Name"") req, _ := http.NewRequest("PATCH", url, payload) @@ -183,12 +190,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample5 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/connections/CONNECTION-ID") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/connections/CONNECTION-ID") .header("content-type", "application/json") - .body("{ \"options\": { \"client_id\": \"...\", \"client_secret\": \"...\", \"icon_url\": \"https://cdn.example.com/assets/icon.png\", \"scripts\": { \"fetchUserProfile\": \"...\" }, \"authorizationURL\": \"https://public-auth.example.com/oauth2/authorize\", \"tokenURL\": \"https://auth.example.com/oauth2/token\", \"scope\": \"auth\" }, \"enabled_clients\": [ \"...\" ] }, \"display_name\": \"Connection Name\"") - .asString();`; -export const codeExample6 = `var axios = require("axios").default; + .body("{ "options": { "client_id": "...", "client_secret": "...", "icon_url": "https://cdn.example.com/assets/icon.png", "scripts": { "fetchUserProfile": "..." }, "authorizationURL": "https://public-auth.example.com/oauth2/authorize", "tokenURL": "https://auth.example.com/oauth2/token", "scope": "auth" }, "enabled_clients": [ "..." ] }, "display_name": "Connection Name"") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -201,8 +212,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample7 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json" }; @@ -225,8 +238,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample8 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/connections/CONNECTION-ID", @@ -236,7 +251,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{ \"options\": { \"client_id\": \"...\", \"client_secret\": \"...\", \"icon_url\": \"https://cdn.example.com/assets/icon.png\", \"scripts\": { \"fetchUserProfile\": \"...\" }, \"authorizationURL\": \"https://public-auth.example.com/oauth2/authorize\", \"tokenURL\": \"https://auth.example.com/oauth2/token\", \"scope\": \"auth\" }, \"enabled_clients\": [ \"...\" ] }, \"display_name\": \"Connection Name\"", + CURLOPT_POSTFIELDS => "{ "options": { "client_id": "...", "client_secret": "...", "icon_url": "https://cdn.example.com/assets/icon.png", "scripts": { "fetchUserProfile": "..." }, "authorizationURL": "https://public-auth.example.com/oauth2/authorize", "tokenURL": "https://auth.example.com/oauth2/token", "scope": "auth" }, "enabled_clients": [ "..." ] }, "display_name": "Connection Name"", CURLOPT_HTTPHEADER => [ "content-type: application/json" ], @@ -251,12 +266,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample9 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"options\": { \"client_id\": \"...\", \"client_secret\": \"...\", \"icon_url\": \"https://cdn.example.com/assets/icon.png\", \"scripts\": { \"fetchUserProfile\": \"...\" }, \"authorizationURL\": \"https://public-auth.example.com/oauth2/authorize\", \"tokenURL\": \"https://auth.example.com/oauth2/token\", \"scope\": \"auth\" }, \"enabled_clients\": [ \"...\" ] }, \"display_name\": \"Connection Name\"" +payload = "{ "options": { "client_id": "...", "client_secret": "...", "icon_url": "https://cdn.example.com/assets/icon.png", "scripts": { "fetchUserProfile": "..." }, "authorizationURL": "https://public-auth.example.com/oauth2/authorize", "tokenURL": "https://auth.example.com/oauth2/token", "scope": "auth" }, "enabled_clients": [ "..." ] }, "display_name": "Connection Name"" headers = { 'content-type': "application/json" } @@ -265,8 +282,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/connections/CONNECTION-ID", payload, res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample10 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -278,11 +297,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Patch.new(url) request["content-type"] = 'application/json' -request.body = "{ \"options\": { \"client_id\": \"...\", \"client_secret\": \"...\", \"icon_url\": \"https://cdn.example.com/assets/icon.png\", \"scripts\": { \"fetchUserProfile\": \"...\" }, \"authorizationURL\": \"https://public-auth.example.com/oauth2/authorize\", \"tokenURL\": \"https://auth.example.com/oauth2/token\", \"scope\": \"auth\" }, \"enabled_clients\": [ \"...\" ] }, \"display_name\": \"Connection Name\"" +request.body = "{ "options": { "client_id": "...", "client_secret": "...", "icon_url": "https://cdn.example.com/assets/icon.png", "scripts": { "fetchUserProfile": "..." }, "authorizationURL": "https://public-auth.example.com/oauth2/authorize", "tokenURL": "https://auth.example.com/oauth2/token", "scope": "auth" }, "enabled_clients": [ "..." ] }, "display_name": "Connection Name"" response = http.request(request) -puts response.read_body`; -export const codeExample11 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/json"] @@ -305,20 +326,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ## プロバイダー固有のパラメータを渡す @@ -328,16 +338,22 @@ OAuth 2.0プロバイダーの認可エンドポイントには、プロバイ 静的パラメーター(すべての認可要求で送信されるパラメーター)を渡すには、[Management API](/docs/ja-jp/api/management/v2#!/Connections/patch_connections_by_id)を使ってOAuth 2.0接続を構成した場合、`option`の`authParams`要素を使用することができます。以下の呼び出しは、すべての認可要求について、`custom_param`の静的パラメーターを`custom.param.value`に設定します。 -export const codeExample12 = `curl --request PATCH \ + +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/connections/CONNECTION-ID' \ --header 'content-type: application/json' \ - --data '{ "options": { "client_id": "...", "client_secret": "...", "authParams": { "custom_param": "custom.param.value" }, "scripts": { "fetchUserProfile": "..." }, "authorizationURL": "https://public-auth.example.com/oauth2/authorize", "tokenURL": "https://auth.example.com/oauth2/token", "scope": "auth" }, "enabled_clients": [ "..." ] }'`; -export const codeExample13 = `var client = new RestClient("https://{yourDomain}/api/v2/connections/CONNECTION-ID"); + --data '{ "options": { "client_id": "...", "client_secret": "...", "authParams": { "custom_param": "custom.param.value" }, "scripts": { "fetchUserProfile": "..." }, "authorizationURL": "https://public-auth.example.com/oauth2/authorize", "tokenURL": "https://auth.example.com/oauth2/token", "scope": "auth" }, "enabled_clients": [ "..." ] }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/connections/CONNECTION-ID"); var request = new RestRequest(Method.PATCH); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{ \"options\": { \"client_id\": \"...\", \"client_secret\": \"...\", \"authParams\": { \"custom_param\": \"custom.param.value\" }, \"scripts\": { \"fetchUserProfile\": \"...\" }, \"authorizationURL\": \"https://public-auth.example.com/oauth2/authorize\", \"tokenURL\": \"https://auth.example.com/oauth2/token\", \"scope\": \"auth\" }, \"enabled_clients\": [ \"...\" ] }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample14 = `package main +request.AddParameter("application/json", "{ "options": { "client_id": "...", "client_secret": "...", "authParams": { "custom_param": "custom.param.value" }, "scripts": { "fetchUserProfile": "..." }, "authorizationURL": "https://public-auth.example.com/oauth2/authorize", "tokenURL": "https://auth.example.com/oauth2/token", "scope": "auth" }, "enabled_clients": [ "..." ] }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -350,7 +366,7 @@ func main() { url := "https://{yourDomain}/api/v2/connections/CONNECTION-ID" - payload := strings.NewReader("{ \"options\": { \"client_id\": \"...\", \"client_secret\": \"...\", \"authParams\": { \"custom_param\": \"custom.param.value\" }, \"scripts\": { \"fetchUserProfile\": \"...\" }, \"authorizationURL\": \"https://public-auth.example.com/oauth2/authorize\", \"tokenURL\": \"https://auth.example.com/oauth2/token\", \"scope\": \"auth\" }, \"enabled_clients\": [ \"...\" ] }") + payload := strings.NewReader("{ "options": { "client_id": "...", "client_secret": "...", "authParams": { "custom_param": "custom.param.value" }, "scripts": { "fetchUserProfile": "..." }, "authorizationURL": "https://public-auth.example.com/oauth2/authorize", "tokenURL": "https://auth.example.com/oauth2/token", "scope": "auth" }, "enabled_clients": [ "..." ] }") req, _ := http.NewRequest("PATCH", url, payload) @@ -364,12 +380,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample15 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/connections/CONNECTION-ID") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/connections/CONNECTION-ID") .header("content-type", "application/json") - .body("{ \"options\": { \"client_id\": \"...\", \"client_secret\": \"...\", \"authParams\": { \"custom_param\": \"custom.param.value\" }, \"scripts\": { \"fetchUserProfile\": \"...\" }, \"authorizationURL\": \"https://public-auth.example.com/oauth2/authorize\", \"tokenURL\": \"https://auth.example.com/oauth2/token\", \"scope\": \"auth\" }, \"enabled_clients\": [ \"...\" ] }") - .asString();`; -export const codeExample16 = `var axios = require("axios").default; + .body("{ "options": { "client_id": "...", "client_secret": "...", "authParams": { "custom_param": "custom.param.value" }, "scripts": { "fetchUserProfile": "..." }, "authorizationURL": "https://public-auth.example.com/oauth2/authorize", "tokenURL": "https://auth.example.com/oauth2/token", "scope": "auth" }, "enabled_clients": [ "..." ] }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -393,8 +413,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample17 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json" }; NSDictionary *parameters = @{ @"options": @{ @"client_id": @"...", @"client_secret": @"...", @"authParams": @{ @"custom_param": @"custom.param.value" }, @"scripts": @{ @"fetchUserProfile": @"..." }, @"authorizationURL": @"https://public-auth.example.com/oauth2/authorize", @"tokenURL": @"https://auth.example.com/oauth2/token", @"scope": @"auth" }, @@ -419,8 +441,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample18 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/connections/CONNECTION-ID", @@ -430,7 +454,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{ \"options\": { \"client_id\": \"...\", \"client_secret\": \"...\", \"authParams\": { \"custom_param\": \"custom.param.value\" }, \"scripts\": { \"fetchUserProfile\": \"...\" }, \"authorizationURL\": \"https://public-auth.example.com/oauth2/authorize\", \"tokenURL\": \"https://auth.example.com/oauth2/token\", \"scope\": \"auth\" }, \"enabled_clients\": [ \"...\" ] }", + CURLOPT_POSTFIELDS => "{ "options": { "client_id": "...", "client_secret": "...", "authParams": { "custom_param": "custom.param.value" }, "scripts": { "fetchUserProfile": "..." }, "authorizationURL": "https://public-auth.example.com/oauth2/authorize", "tokenURL": "https://auth.example.com/oauth2/token", "scope": "auth" }, "enabled_clients": [ "..." ] }", CURLOPT_HTTPHEADER => [ "content-type: application/json" ], @@ -445,12 +469,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample19 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"options\": { \"client_id\": \"...\", \"client_secret\": \"...\", \"authParams\": { \"custom_param\": \"custom.param.value\" }, \"scripts\": { \"fetchUserProfile\": \"...\" }, \"authorizationURL\": \"https://public-auth.example.com/oauth2/authorize\", \"tokenURL\": \"https://auth.example.com/oauth2/token\", \"scope\": \"auth\" }, \"enabled_clients\": [ \"...\" ] }" +payload = "{ "options": { "client_id": "...", "client_secret": "...", "authParams": { "custom_param": "custom.param.value" }, "scripts": { "fetchUserProfile": "..." }, "authorizationURL": "https://public-auth.example.com/oauth2/authorize", "tokenURL": "https://auth.example.com/oauth2/token", "scope": "auth" }, "enabled_clients": [ "..." ] }" headers = { 'content-type': "application/json" } @@ -459,8 +485,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/connections/CONNECTION-ID", payload, res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample20 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -472,11 +500,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Patch.new(url) request["content-type"] = 'application/json' -request.body = "{ \"options\": { \"client_id\": \"...\", \"client_secret\": \"...\", \"authParams\": { \"custom_param\": \"custom.param.value\" }, \"scripts\": { \"fetchUserProfile\": \"...\" }, \"authorizationURL\": \"https://public-auth.example.com/oauth2/authorize\", \"tokenURL\": \"https://auth.example.com/oauth2/token\", \"scope\": \"auth\" }, \"enabled_clients\": [ \"...\" ] }" +request.body = "{ "options": { "client_id": "...", "client_secret": "...", "authParams": { "custom_param": "custom.param.value" }, "scripts": { "fetchUserProfile": "..." }, "authorizationURL": "https://public-auth.example.com/oauth2/authorize", "tokenURL": "https://auth.example.com/oauth2/token", "scope": "auth" }, "enabled_clients": [ "..." ] }" response = http.request(request) -puts response.read_body`; -export const codeExample21 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/json"] let parameters = [ @@ -511,20 +541,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ### 動的パラメーターを渡す @@ -534,16 +553,22 @@ dataTask.resume()`; この場合には、`/authorize`エンドポイントが受け入れる既存の追加パラメーターの1つ(`access_type`など)を使って、それを`custom_param`パラメーターにマッピングすることができます。 -export const codeExample22 = `curl --request PATCH \ + +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/connections/CONNECTION-ID' \ --header 'content-type: application/json' \ - --data '{ "options": { "client_id": "...", "client_secret": "...", "authParamsMap": { "custom_param": "access_type" }, "scripts": { "fetchUserProfile": "..." }, "authorizationURL": "https://auth.example.com/oauth2/authorize", "tokenURL": "https://auth.example.com/oauth2/token", "scope": "auth" }, "enabled_clients": [ "..." ] }'`; -export const codeExample23 = `var client = new RestClient("https://{yourDomain}/api/v2/connections/CONNECTION-ID"); + --data '{ "options": { "client_id": "...", "client_secret": "...", "authParamsMap": { "custom_param": "access_type" }, "scripts": { "fetchUserProfile": "..." }, "authorizationURL": "https://auth.example.com/oauth2/authorize", "tokenURL": "https://auth.example.com/oauth2/token", "scope": "auth" }, "enabled_clients": [ "..." ] }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/connections/CONNECTION-ID"); var request = new RestRequest(Method.PATCH); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{ \"options\": { \"client_id\": \"...\", \"client_secret\": \"...\", \"authParamsMap\": { \"custom_param\": \"access_type\" }, \"scripts\": { \"fetchUserProfile\": \"...\" }, \"authorizationURL\": \"https://auth.example.com/oauth2/authorize\", \"tokenURL\": \"https://auth.example.com/oauth2/token\", \"scope\": \"auth\" }, \"enabled_clients\": [ \"...\" ] }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample24 = `package main +request.AddParameter("application/json", "{ "options": { "client_id": "...", "client_secret": "...", "authParamsMap": { "custom_param": "access_type" }, "scripts": { "fetchUserProfile": "..." }, "authorizationURL": "https://auth.example.com/oauth2/authorize", "tokenURL": "https://auth.example.com/oauth2/token", "scope": "auth" }, "enabled_clients": [ "..." ] }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -556,7 +581,7 @@ func main() { url := "https://{yourDomain}/api/v2/connections/CONNECTION-ID" - payload := strings.NewReader("{ \"options\": { \"client_id\": \"...\", \"client_secret\": \"...\", \"authParamsMap\": { \"custom_param\": \"access_type\" }, \"scripts\": { \"fetchUserProfile\": \"...\" }, \"authorizationURL\": \"https://auth.example.com/oauth2/authorize\", \"tokenURL\": \"https://auth.example.com/oauth2/token\", \"scope\": \"auth\" }, \"enabled_clients\": [ \"...\" ] }") + payload := strings.NewReader("{ "options": { "client_id": "...", "client_secret": "...", "authParamsMap": { "custom_param": "access_type" }, "scripts": { "fetchUserProfile": "..." }, "authorizationURL": "https://auth.example.com/oauth2/authorize", "tokenURL": "https://auth.example.com/oauth2/token", "scope": "auth" }, "enabled_clients": [ "..." ] }") req, _ := http.NewRequest("PATCH", url, payload) @@ -570,12 +595,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample25 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/connections/CONNECTION-ID") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/connections/CONNECTION-ID") .header("content-type", "application/json") - .body("{ \"options\": { \"client_id\": \"...\", \"client_secret\": \"...\", \"authParamsMap\": { \"custom_param\": \"access_type\" }, \"scripts\": { \"fetchUserProfile\": \"...\" }, \"authorizationURL\": \"https://auth.example.com/oauth2/authorize\", \"tokenURL\": \"https://auth.example.com/oauth2/token\", \"scope\": \"auth\" }, \"enabled_clients\": [ \"...\" ] }") - .asString();`; -export const codeExample26 = `var axios = require("axios").default; + .body("{ "options": { "client_id": "...", "client_secret": "...", "authParamsMap": { "custom_param": "access_type" }, "scripts": { "fetchUserProfile": "..." }, "authorizationURL": "https://auth.example.com/oauth2/authorize", "tokenURL": "https://auth.example.com/oauth2/token", "scope": "auth" }, "enabled_clients": [ "..." ] }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -599,8 +628,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample27 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json" }; NSDictionary *parameters = @{ @"options": @{ @"client_id": @"...", @"client_secret": @"...", @"authParamsMap": @{ @"custom_param": @"access_type" }, @"scripts": @{ @"fetchUserProfile": @"..." }, @"authorizationURL": @"https://auth.example.com/oauth2/authorize", @"tokenURL": @"https://auth.example.com/oauth2/token", @"scope": @"auth" }, @@ -625,8 +656,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample28 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/connections/CONNECTION-ID", @@ -636,7 +669,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{ \"options\": { \"client_id\": \"...\", \"client_secret\": \"...\", \"authParamsMap\": { \"custom_param\": \"access_type\" }, \"scripts\": { \"fetchUserProfile\": \"...\" }, \"authorizationURL\": \"https://auth.example.com/oauth2/authorize\", \"tokenURL\": \"https://auth.example.com/oauth2/token\", \"scope\": \"auth\" }, \"enabled_clients\": [ \"...\" ] }", + CURLOPT_POSTFIELDS => "{ "options": { "client_id": "...", "client_secret": "...", "authParamsMap": { "custom_param": "access_type" }, "scripts": { "fetchUserProfile": "..." }, "authorizationURL": "https://auth.example.com/oauth2/authorize", "tokenURL": "https://auth.example.com/oauth2/token", "scope": "auth" }, "enabled_clients": [ "..." ] }", CURLOPT_HTTPHEADER => [ "content-type: application/json" ], @@ -651,12 +684,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample29 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"options\": { \"client_id\": \"...\", \"client_secret\": \"...\", \"authParamsMap\": { \"custom_param\": \"access_type\" }, \"scripts\": { \"fetchUserProfile\": \"...\" }, \"authorizationURL\": \"https://auth.example.com/oauth2/authorize\", \"tokenURL\": \"https://auth.example.com/oauth2/token\", \"scope\": \"auth\" }, \"enabled_clients\": [ \"...\" ] }" +payload = "{ "options": { "client_id": "...", "client_secret": "...", "authParamsMap": { "custom_param": "access_type" }, "scripts": { "fetchUserProfile": "..." }, "authorizationURL": "https://auth.example.com/oauth2/authorize", "tokenURL": "https://auth.example.com/oauth2/token", "scope": "auth" }, "enabled_clients": [ "..." ] }" headers = { 'content-type': "application/json" } @@ -665,8 +700,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/connections/CONNECTION-ID", payload, res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample30 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -678,11 +715,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Patch.new(url) request["content-type"] = 'application/json' -request.body = "{ \"options\": { \"client_id\": \"...\", \"client_secret\": \"...\", \"authParamsMap\": { \"custom_param\": \"access_type\" }, \"scripts\": { \"fetchUserProfile\": \"...\" }, \"authorizationURL\": \"https://auth.example.com/oauth2/authorize\", \"tokenURL\": \"https://auth.example.com/oauth2/token\", \"scope\": \"auth\" }, \"enabled_clients\": [ \"...\" ] }" +request.body = "{ "options": { "client_id": "...", "client_secret": "...", "authParamsMap": { "custom_param": "access_type" }, "scripts": { "fetchUserProfile": "..." }, "authorizationURL": "https://auth.example.com/oauth2/authorize", "tokenURL": "https://auth.example.com/oauth2/token", "scope": "auth" }, "enabled_clients": [ "..." ] }" response = http.request(request) -puts response.read_body`; -export const codeExample31 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/json"] let parameters = [ @@ -717,20 +756,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + これで、`/authorize`エンドポイントを呼び出す際に`access_type`パラメーターにアクセスタイプを渡すことができ、その値が`custom_param`パラメーターで認可エンドポイントに渡されます。 diff --git a/main/docs/ja-jp/authenticate/login/auth0-universal-login/configure-default-login-routes.mdx b/main/docs/ja-jp/authenticate/login/auth0-universal-login/configure-default-login-routes.mdx index 7cfaa025f..67a841b6b 100644 --- a/main/docs/ja-jp/authenticate/login/auth0-universal-login/configure-default-login-routes.mdx +++ b/main/docs/ja-jp/authenticate/login/auth0-universal-login/configure-default-login-routes.mdx @@ -10,6 +10,7 @@ permalink: "configure-default-login-routes" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; 場合によっては(以下を参照)、Auth0がOIDCサードパーティ起点のログインを使って、アプリケーションのログイン開始エンドポイントにリダイレクトしなければならないことがあります。詳細については、[OpenID Foundation](https://openid.net/specs/openid-connect-core-1_0.html#ThirdPartyInitiatedLogin)の「[Initiating Login from a Third Party](https://openid.net)」をお読みください。 @@ -17,20 +18,26 @@ import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; -export const codeExample1 = `curl --request PATCH \ + +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/clients/{yourClientId}' \ --header 'authorization: Bearer API2_ACCESS_TOKEN' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{"initiate_login_uri": ""}'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/clients/{yourClientId}"); + --data '{"initiate_login_uri": ""}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/clients/{yourClientId}"); var request = new RestRequest(Method.PATCH); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer API2_ACCESS_TOKEN"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{\"initiate_login_uri\": \"\"}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{"initiate_login_uri": ""}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -43,7 +50,7 @@ func main() { url := "https://{yourDomain}/api/v2/clients/{yourClientId}" - payload := strings.NewReader("{\"initiate_login_uri\": \"\"}") + payload := strings.NewReader("{"initiate_login_uri": ""}") req, _ := http.NewRequest("PATCH", url, payload) @@ -59,14 +66,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/clients/{yourClientId}") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/clients/{yourClientId}") .header("content-type", "application/json") .header("authorization", "Bearer API2_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{\"initiate_login_uri\": \"\"}") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{"initiate_login_uri": ""}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -83,8 +94,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer API2_ACCESS_TOKEN", @@ -110,8 +123,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/clients/{yourClientId}", @@ -121,7 +136,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{\"initiate_login_uri\": \"\"}", + CURLOPT_POSTFIELDS => "{"initiate_login_uri": ""}", CURLOPT_HTTPHEADER => [ "authorization: Bearer API2_ACCESS_TOKEN", "cache-control: no-cache", @@ -138,12 +153,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"initiate_login_uri\": \"\"}" +payload = "{"initiate_login_uri": ""}" headers = { 'content-type': "application/json", @@ -156,8 +173,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/clients/{yourClientId}", payload, he res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -171,11 +190,13 @@ request = Net::HTTP::Patch.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer API2_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{\"initiate_login_uri\": \"\"}" +request.body = "{"initiate_login_uri": ""}" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -203,37 +224,32 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + -export const codeExample11 = `curl --request PATCH \ + +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/tenants/settings' \ --header 'authorization: Bearer API2_ACCESS_TOKEN' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{"default_redirection_uri": ""}'`; -export const codeExample12 = `var client = new RestClient("https://{yourDomain}/api/v2/tenants/settings"); + --data '{"default_redirection_uri": ""}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/tenants/settings"); var request = new RestRequest(Method.PATCH); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer API2_ACCESS_TOKEN"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{\"default_redirection_uri\": \"\"}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample13 = `package main +request.AddParameter("application/json", "{"default_redirection_uri": ""}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -246,7 +262,7 @@ func main() { url := "https://{yourDomain}/api/v2/tenants/settings" - payload := strings.NewReader("{\"default_redirection_uri\": \"\"}") + payload := strings.NewReader("{"default_redirection_uri": ""}") req, _ := http.NewRequest("PATCH", url, payload) @@ -262,14 +278,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample14 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/tenants/settings") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/tenants/settings") .header("content-type", "application/json") .header("authorization", "Bearer API2_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{\"default_redirection_uri\": \"\"}") - .asString();`; -export const codeExample15 = `var axios = require("axios").default; + .body("{"default_redirection_uri": ""}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -286,8 +306,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample16 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer API2_ACCESS_TOKEN", @@ -313,8 +335,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/tenants/settings", @@ -324,7 +348,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{\"default_redirection_uri\": \"\"}", + CURLOPT_POSTFIELDS => "{"default_redirection_uri": ""}", CURLOPT_HTTPHEADER => [ "authorization: Bearer API2_ACCESS_TOKEN", "cache-control: no-cache", @@ -341,12 +365,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"default_redirection_uri\": \"\"}" +payload = "{"default_redirection_uri": ""}" headers = { 'content-type': "application/json", @@ -359,8 +385,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/tenants/settings", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -374,11 +402,13 @@ request = Net::HTTP::Patch.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer API2_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{\"default_redirection_uri\": \"\"}" +request.body = "{"default_redirection_uri": ""}" response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -406,20 +436,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + @@ -451,18 +470,24 @@ Organizationsを使用している場合、エンドユーザーが組織のロ ユニバーサルログインを使うテナントの場合、[`/post-password-change`](/docs/ja-jp/api/management/v2/#!/Tickets/post_password_change)エンドポイントは、ユーザーを特定のアプリケーションにリダイレクトする動作に対応しています。`client_id`が指定され、アプリケーションのログインURIが設定されている場合は、パスワードのリセット完了後にユーザーをアプリケーションに送り返すボタンが表示されます。 -export const codeExample21 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/api/v2/tickets/password-change' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'content-type: application/json' \ - --data '{ "user_id": "A_USER_ID", "client_id": "A_CLIENT_ID" }'`; -export const codeExample22 = `var client = new RestClient("https://{yourDomain}/api/v2/tickets/password-change"); + --data '{ "user_id": "A_USER_ID", "client_id": "A_CLIENT_ID" }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/tickets/password-change"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); -request.AddParameter("application/json", "{ \"user_id\": \"A_USER_ID\", \"client_id\": \"A_CLIENT_ID\" }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample23 = `package main +request.AddParameter("application/json", "{ "user_id": "A_USER_ID", "client_id": "A_CLIENT_ID" }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -475,7 +500,7 @@ func main() { url := "https://{yourDomain}/api/v2/tickets/password-change" - payload := strings.NewReader("{ \"user_id\": \"A_USER_ID\", \"client_id\": \"A_CLIENT_ID\" }") + payload := strings.NewReader("{ "user_id": "A_USER_ID", "client_id": "A_CLIENT_ID" }") req, _ := http.NewRequest("POST", url, payload) @@ -490,13 +515,17 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample24 = `HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/tickets/password-change") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/tickets/password-change") .header("content-type", "application/json") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") - .body("{ \"user_id\": \"A_USER_ID\", \"client_id\": \"A_CLIENT_ID\" }") - .asString();`; -export const codeExample25 = `var axios = require("axios").default; + .body("{ "user_id": "A_USER_ID", "client_id": "A_CLIENT_ID" }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -512,8 +541,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample26 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN" }; @@ -539,8 +570,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample27 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/tickets/password-change", @@ -550,7 +583,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{ \"user_id\": \"A_USER_ID\", \"client_id\": \"A_CLIENT_ID\" }", + CURLOPT_POSTFIELDS => "{ "user_id": "A_USER_ID", "client_id": "A_CLIENT_ID" }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "content-type: application/json" @@ -566,12 +599,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample28 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"user_id\": \"A_USER_ID\", \"client_id\": \"A_CLIENT_ID\" }" +payload = "{ "user_id": "A_USER_ID", "client_id": "A_CLIENT_ID" }" headers = { 'content-type': "application/json", @@ -583,8 +618,10 @@ conn.request("POST", "/{yourDomain}/api/v2/tickets/password-change", payload, he res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample29 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -597,11 +634,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' -request.body = "{ \"user_id\": \"A_USER_ID\", \"client_id\": \"A_CLIENT_ID\" }" +request.body = "{ "user_id": "A_USER_ID", "client_id": "A_CLIENT_ID" }" response = http.request(request) -puts response.read_body`; -export const codeExample30 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -631,20 +670,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ### メール検証フローを完了する diff --git a/main/docs/ja-jp/authenticate/login/oidc-conformant-authentication/oidc-adoption-auth-code-flow.mdx b/main/docs/ja-jp/authenticate/login/oidc-conformant-authentication/oidc-adoption-auth-code-flow.mdx index 14da86f5a..aae47d4d0 100644 --- a/main/docs/ja-jp/authenticate/login/oidc-conformant-authentication/oidc-adoption-auth-code-flow.mdx +++ b/main/docs/ja-jp/authenticate/login/oidc-conformant-authentication/oidc-adoption-auth-code-flow.mdx @@ -10,6 +10,7 @@ permalink: "oidc-adoption-auth-code-flow" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; [認可コードフロー](/docs/ja-jp/get-started/authentication-and-authorization-flow/authorization-code-flow)は、シークレットを安全に保存できるサーバー側アプリケーション、またはネイティブアプリケーションが、[PKCEを使った認可コードフロー](/docs/ja-jp/get-started/authentication-and-authorization-flow/authorization-code-flow-with-pkce)を介して使用します。 @@ -69,20 +70,26 @@ Location: https://app.example.com/callback? 認可コードは両方のパイプラインで同じ方法で交換できます。 -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=authorization_code \ --data 'client_id={yourClientId}' \ --data client_secret=YOUR_CLIENT_SECRET \ --data code=YOUR_AUTHORIZATION_CODE \ - --data 'redirect_uri={https://yourApp/callback}'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data 'redirect_uri={https://yourApp/callback}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=authorization_code&client_id={yourClientId}&client_secret=YOUR_CLIENT_SECRET&code=YOUR_AUTHORIZATION_CODE&redirect_uri={https://yourApp/callback}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -109,12 +116,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=authorization_code&client_id={yourClientId}&client_secret=YOUR_CLIENT_SECRET&code=YOUR_AUTHORIZATION_CODE&redirect_uri={https://yourApp/callback}") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -133,8 +144,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -161,8 +174,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -187,8 +202,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -201,8 +218,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -217,8 +236,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=authorization_code&client_id={yourClientId}&client_secret=YOUR_CLIENT_SECRET&code=YOUR_AUTHORIZATION_CODE&redirect_uri={https://yourApp/callback}" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -245,39 +266,34 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ## コード交換要求 - PKCEを使った認可コードフロー 認可コードは両方のパイプラインで同じ方法で交換できます。 -export const codeExample11 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=authorization_code \ --data 'client_id={yourClientId}' \ --data code_verifier=YOUR_GENERATED_CODE_VERIFIER \ --data code=YOUR_AUTHORIZATION_CODE \ - --data 'redirect_uri={https://yourApp/callback}'`; -export const codeExample12 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data 'redirect_uri={https://yourApp/callback}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=authorization_code&client_id={yourClientId}&code_verifier=YOUR_GENERATED_CODE_VERIFIER&code=YOUR_AUTHORIZATION_CODE&redirect_uri={https://yourApp/callback}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample13 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -304,12 +320,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample14 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=authorization_code&client_id={yourClientId}&code_verifier=YOUR_GENERATED_CODE_VERIFIER&code=YOUR_AUTHORIZATION_CODE&redirect_uri={https://yourApp/callback}") - .asString();`; -export const codeExample15 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -328,8 +348,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample16 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -356,8 +378,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -382,8 +406,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -396,8 +422,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -412,8 +440,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=authorization_code&client_id={yourClientId}&code_verifier=YOUR_GENERATED_CODE_VERIFIER&code=YOUR_AUTHORIZATION_CODE&redirect_uri={https://yourApp/callback}" response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -440,20 +470,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ## コード交換応答 diff --git a/main/docs/ja-jp/authenticate/passwordless/authentication-methods/use-sms-gateway-passwordless.mdx b/main/docs/ja-jp/authenticate/passwordless/authentication-methods/use-sms-gateway-passwordless.mdx index 6b8ab6def..778432b58 100644 --- a/main/docs/ja-jp/authenticate/passwordless/authentication-methods/use-sms-gateway-passwordless.mdx +++ b/main/docs/ja-jp/authenticate/passwordless/authentication-methods/use-sms-gateway-passwordless.mdx @@ -9,6 +9,9 @@ permalink: "use-sms-gateway-passwordless" 'twitter:description': "パスワードレス接続のためにカスタムSMSゲートウェイをセットアップする方法を学びます。" --- + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + このガイドでは、1回限り使用できるコードを送信するためにカスタムSMSゲートウェイを使用する方法について説明します。 デフォルトでは、[パスワードレスSMS接続](/docs/ja-jp/authenticate/passwordless/authentication-methods/sms-otp)は、[Twilio](https://www.twilio.com)を使用して1回限り使用できるコードを送信します。ただし、カスタムSMSゲートウェイがある場合は、代わりにそれを使用するために接続を変更できます。 @@ -23,7 +26,7 @@ Auth0は、基本的なSMS認証に対応していません。 2. [Management APIのアクセストークンを取得](/docs/ja-jp/secure/tokens/access-tokens/management-api-access-tokens)します。これは、パスワードレス接続を更新するために、Mangement APIを呼び出すために必要です。 3. [GET接続](/docs/ja-jp/api/management/v2#!/Connections/get_connections)エンドポイントを使用して、テナントに関する接続についての情報を取得します。より具体的には、パスワードレスSMS接続のIDを取得する必要があります。そうすることで、接続自体を更新する後のAPI呼び出しでそれを使用できます。Management APIに以下の呼び出しを行う前に、`ACCESS_TOKEN`を手順1で取得したトークンに置き換えてください。 - + ```bash cURL lines curl --request GET \ --url https://your-auth0-tenant.com/api/v2/connections \ @@ -190,7 +193,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + エンドポイントからの応答は、オブジェクトの配列です。各オブジェクトは、テナントと関係がある1つの接続を表しています。 4. 接続IDを特定します。手順2で[GET接続エンドポイント](/docs/ja-jp/api/management/v2#!/Connections/get_connections)から返されたオブジェクトの配列を確認して、パスワードレス接続と関係があるIDを見つけることができます。パスワードレス接続のある特定のオブジェクトを見つけるには、`"name": "sms"`プロパティを検索できます。接続で、セットアッププロセス中にあなたが提供したTwilio情報が現在表示されていることに注目してください。 diff --git a/main/docs/ja-jp/authenticate/passwordless/implement-login/embedded-login/native.mdx b/main/docs/ja-jp/authenticate/passwordless/implement-login/embedded-login/native.mdx index 4f91f5885..d2e614eb1 100644 --- a/main/docs/ja-jp/authenticate/passwordless/implement-login/embedded-login/native.mdx +++ b/main/docs/ja-jp/authenticate/passwordless/implement-login/embedded-login/native.mdx @@ -10,6 +10,7 @@ permalink: "native" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; ネイティブアプリケーションで埋め込み型パスワードレスAPIを使用するには、[[Auth0 Dashboard]>[Applications(アプリケーション)]>[Applications(アプリケーション)]](https://manage.auth0.com/#/applications)に移動して、アプリケーション設定の **[Advanced Settings(高度な設定]** > **[Grant Types(付与タイプ)]** で **[Passwordless OTP(パスワードレスOTP)]** の付与を有効にしなければなりません。 @@ -22,16 +23,22 @@ import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; **メールで一回限り使用できるパスワードを送信する** -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/passwordless/start' \ --header 'content-type: application/json' \ - --data '{"client_id": "{yourClientId}", "connection": "email", "email": "USER_EMAIL", "send": "code"}'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/passwordless/start"); + --data '{"client_id": "{yourClientId}", "connection": "email", "email": "USER_EMAIL", "send": "code"}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/passwordless/start"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\"client_id\": \"{yourClientId}\", \"connection\": \"email\", \"email\": \"USER_EMAIL\", \"send\": \"code\"}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{"client_id": "{yourClientId}", "connection": "email", "email": "USER_EMAIL", "send": "code"}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -44,7 +51,7 @@ func main() { url := "https://{yourDomain}/passwordless/start" - payload := strings.NewReader("{\"client_id\": \"{yourClientId}\", \"connection\": \"email\", \"email\": \"USER_EMAIL\", \"send\": \"code\"}") + payload := strings.NewReader("{"client_id": "{yourClientId}", "connection": "email", "email": "USER_EMAIL", "send": "code"}") req, _ := http.NewRequest("POST", url, payload) @@ -58,12 +65,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/passwordless/start") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/passwordless/start") .header("content-type", "application/json") - .body("{\"client_id\": \"{yourClientId}\", \"connection\": \"email\", \"email\": \"USER_EMAIL\", \"send\": \"code\"}") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{"client_id": "{yourClientId}", "connection": "email", "email": "USER_EMAIL", "send": "code"}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -81,8 +92,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json" }; NSDictionary *parameters = @{ @"client_id": @"{yourClientId}", @@ -109,8 +122,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/passwordless/start", @@ -120,7 +135,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{\"client_id\": \"{yourClientId}\", \"connection\": \"email\", \"email\": \"USER_EMAIL\", \"send\": \"code\"}", + CURLOPT_POSTFIELDS => "{"client_id": "{yourClientId}", "connection": "email", "email": "USER_EMAIL", "send": "code"}", CURLOPT_HTTPHEADER => [ "content-type: application/json" ], @@ -135,12 +150,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"client_id\": \"{yourClientId}\", \"connection\": \"email\", \"email\": \"USER_EMAIL\", \"send\": \"code\"}" +payload = "{"client_id": "{yourClientId}", "connection": "email", "email": "USER_EMAIL", "send": "code"}" headers = { 'content-type': "application/json" } @@ -149,8 +166,10 @@ conn.request("POST", "/{yourDomain}/passwordless/start", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -162,11 +181,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["content-type"] = 'application/json' -request.body = "{\"client_id\": \"{yourClientId}\", \"connection\": \"email\", \"email\": \"USER_EMAIL\", \"send\": \"code\"}" +request.body = "{"client_id": "{yourClientId}", "connection": "email", "email": "USER_EMAIL", "send": "code"}" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/json"] let parameters = [ @@ -195,33 +216,28 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + **メールでマジックリンクを送信する** -export const codeExample11 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/passwordless/start' \ --header 'content-type: application/json' \ - --data '{ "client_id": "{yourClientId}", "connection": "email", "email": "USER_EMAIL", "send": "link"}'`; -export const codeExample12 = `var client = new RestClient("https://{yourDomain}/passwordless/start"); + --data '{ "client_id": "{yourClientId}", "connection": "email", "email": "USER_EMAIL", "send": "link"}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/passwordless/start"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{ \"client_id\": \"{yourClientId}\", \"connection\": \"email\", \"email\": \"USER_EMAIL\", \"send\": \"link\"}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample13 = `package main +request.AddParameter("application/json", "{ "client_id": "{yourClientId}", "connection": "email", "email": "USER_EMAIL", "send": "link"}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -234,7 +250,7 @@ func main() { url := "https://{yourDomain}/passwordless/start" - payload := strings.NewReader("{ \"client_id\": \"{yourClientId}\", \"connection\": \"email\", \"email\": \"USER_EMAIL\", \"send\": \"link\"}") + payload := strings.NewReader("{ "client_id": "{yourClientId}", "connection": "email", "email": "USER_EMAIL", "send": "link"}") req, _ := http.NewRequest("POST", url, payload) @@ -248,12 +264,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample14 = `HttpResponse response = Unirest.post("https://{yourDomain}/passwordless/start") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/passwordless/start") .header("content-type", "application/json") - .body("{ \"client_id\": \"{yourClientId}\", \"connection\": \"email\", \"email\": \"USER_EMAIL\", \"send\": \"link\"}") - .asString();`; -export const codeExample15 = `var axios = require("axios").default; + .body("{ "client_id": "{yourClientId}", "connection": "email", "email": "USER_EMAIL", "send": "link"}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -271,8 +291,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample16 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json" }; NSDictionary *parameters = @{ @"client_id": @"{yourClientId}", @@ -299,8 +321,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/passwordless/start", @@ -310,7 +334,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{ \"client_id\": \"{yourClientId}\", \"connection\": \"email\", \"email\": \"USER_EMAIL\", \"send\": \"link\"}", + CURLOPT_POSTFIELDS => "{ "client_id": "{yourClientId}", "connection": "email", "email": "USER_EMAIL", "send": "link"}", CURLOPT_HTTPHEADER => [ "content-type: application/json" ], @@ -325,12 +349,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"client_id\": \"{yourClientId}\", \"connection\": \"email\", \"email\": \"USER_EMAIL\", \"send\": \"link\"}" +payload = "{ "client_id": "{yourClientId}", "connection": "email", "email": "USER_EMAIL", "send": "link"}" headers = { 'content-type': "application/json" } @@ -339,8 +365,10 @@ conn.request("POST", "/{yourDomain}/passwordless/start", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -352,11 +380,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["content-type"] = 'application/json' -request.body = "{ \"client_id\": \"{yourClientId}\", \"connection\": \"email\", \"email\": \"USER_EMAIL\", \"send\": \"link\"}" +request.body = "{ "client_id": "{yourClientId}", "connection": "email", "email": "USER_EMAIL", "send": "link"}" response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/json"] let parameters = [ @@ -385,33 +415,28 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + **SMSで一回限り使用できるパスワードを送信する** -export const codeExample21 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/passwordless/start' \ --header 'content-type: application/json' \ - --data '{ "client_id": "{yourClientId}", "connection": "sms", "phone_number": "USER_PHONE_NUMBER", "send": "code"}'`; -export const codeExample22 = `var client = new RestClient("https://{yourDomain}/passwordless/start"); + --data '{ "client_id": "{yourClientId}", "connection": "sms", "phone_number": "USER_PHONE_NUMBER", "send": "code"}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/passwordless/start"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{ \"client_id\": \"{yourClientId}\", \"connection\": \"sms\", \"phone_number\": \"USER_PHONE_NUMBER\", \"send\": \"code\"}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample23 = `package main +request.AddParameter("application/json", "{ "client_id": "{yourClientId}", "connection": "sms", "phone_number": "USER_PHONE_NUMBER", "send": "code"}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -424,7 +449,7 @@ func main() { url := "https://{yourDomain}/passwordless/start" - payload := strings.NewReader("{ \"client_id\": \"{yourClientId}\", \"connection\": \"sms\", \"phone_number\": \"USER_PHONE_NUMBER\", \"send\": \"code\"}") + payload := strings.NewReader("{ "client_id": "{yourClientId}", "connection": "sms", "phone_number": "USER_PHONE_NUMBER", "send": "code"}") req, _ := http.NewRequest("POST", url, payload) @@ -438,12 +463,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample24 = `HttpResponse response = Unirest.post("https://{yourDomain}/passwordless/start") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/passwordless/start") .header("content-type", "application/json") - .body("{ \"client_id\": \"{yourClientId}\", \"connection\": \"sms\", \"phone_number\": \"USER_PHONE_NUMBER\", \"send\": \"code\"}") - .asString();`; -export const codeExample25 = `var axios = require("axios").default; + .body("{ "client_id": "{yourClientId}", "connection": "sms", "phone_number": "USER_PHONE_NUMBER", "send": "code"}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -461,8 +490,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample26 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json" }; NSDictionary *parameters = @{ @"client_id": @"{yourClientId}", @@ -489,8 +520,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample27 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/passwordless/start", @@ -500,7 +533,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{ \"client_id\": \"{yourClientId}\", \"connection\": \"sms\", \"phone_number\": \"USER_PHONE_NUMBER\", \"send\": \"code\"}", + CURLOPT_POSTFIELDS => "{ "client_id": "{yourClientId}", "connection": "sms", "phone_number": "USER_PHONE_NUMBER", "send": "code"}", CURLOPT_HTTPHEADER => [ "content-type: application/json" ], @@ -515,12 +548,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample28 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"client_id\": \"{yourClientId}\", \"connection\": \"sms\", \"phone_number\": \"USER_PHONE_NUMBER\", \"send\": \"code\"}" +payload = "{ "client_id": "{yourClientId}", "connection": "sms", "phone_number": "USER_PHONE_NUMBER", "send": "code"}" headers = { 'content-type': "application/json" } @@ -529,8 +564,10 @@ conn.request("POST", "/{yourDomain}/passwordless/start", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample29 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -542,11 +579,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["content-type"] = 'application/json' -request.body = "{ \"client_id\": \"{yourClientId}\", \"connection\": \"sms\", \"phone_number\": \"USER_PHONE_NUMBER\", \"send\": \"code\"}" +request.body = "{ "client_id": "{yourClientId}", "connection": "sms", "phone_number": "USER_PHONE_NUMBER", "send": "code"}" response = http.request(request) -puts response.read_body`; -export const codeExample30 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/json"] let parameters = [ @@ -575,33 +614,28 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + **SMSユーザーを認証する** -export const codeExample31 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/json' \ - --data '{ "grant_type": "http://auth0.com/oauth/grant-type/passwordless/otp", "client_id": "{yourClientId}", "username": "USER_PHONE_NUMBER", "otp": "code", "realm": "sms", "audience": "your-api-audience", "scope": "openid profile email"}'`; -export const codeExample32 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data '{ "grant_type": "http://auth0.com/oauth/grant-type/passwordless/otp", "client_id": "{yourClientId}", "username": "USER_PHONE_NUMBER", "otp": "code", "realm": "sms", "audience": "your-api-audience", "scope": "openid profile email"}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{ \"grant_type\": \"http://auth0.com/oauth/grant-type/passwordless/otp\", \"client_id\": \"{yourClientId}\", \"username\": \"USER_PHONE_NUMBER\", \"otp\": \"code\", \"realm\": \"sms\", \"audience\": \"your-api-audience\", \"scope\": \"openid profile email\"}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample33 = `package main +request.AddParameter("application/json", "{ "grant_type": "http://auth0.com/oauth/grant-type/passwordless/otp", "client_id": "{yourClientId}", "username": "USER_PHONE_NUMBER", "otp": "code", "realm": "sms", "audience": "your-api-audience", "scope": "openid profile email"}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -614,7 +648,7 @@ func main() { url := "https://{yourDomain}/oauth/token" - payload := strings.NewReader("{ \"grant_type\": \"http://auth0.com/oauth/grant-type/passwordless/otp\", \"client_id\": \"{yourClientId}\", \"username\": \"USER_PHONE_NUMBER\", \"otp\": \"code\", \"realm\": \"sms\", \"audience\": \"your-api-audience\", \"scope\": \"openid profile email\"}") + payload := strings.NewReader("{ "grant_type": "http://auth0.com/oauth/grant-type/passwordless/otp", "client_id": "{yourClientId}", "username": "USER_PHONE_NUMBER", "otp": "code", "realm": "sms", "audience": "your-api-audience", "scope": "openid profile email"}") req, _ := http.NewRequest("POST", url, payload) @@ -628,8 +662,10 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample34 = `var axios = require("axios").default; +} +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -650,8 +686,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample35 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json" }; NSDictionary *parameters = @{ @"grant_type": @"http://auth0.com/oauth/grant-type/passwordless/otp", @@ -681,8 +719,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample36 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -692,7 +732,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{ \"grant_type\": \"http://auth0.com/oauth/grant-type/passwordless/otp\", \"client_id\": \"{yourClientId}\", \"username\": \"USER_PHONE_NUMBER\", \"otp\": \"code\", \"realm\": \"sms\", \"audience\": \"your-api-audience\", \"scope\": \"openid profile email\"}", + CURLOPT_POSTFIELDS => "{ "grant_type": "http://auth0.com/oauth/grant-type/passwordless/otp", "client_id": "{yourClientId}", "username": "USER_PHONE_NUMBER", "otp": "code", "realm": "sms", "audience": "your-api-audience", "scope": "openid profile email"}", CURLOPT_HTTPHEADER => [ "content-type: application/json" ], @@ -707,12 +747,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample37 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"grant_type\": \"http://auth0.com/oauth/grant-type/passwordless/otp\", \"client_id\": \"{yourClientId}\", \"username\": \"USER_PHONE_NUMBER\", \"otp\": \"code\", \"realm\": \"sms\", \"audience\": \"your-api-audience\", \"scope\": \"openid profile email\"}" +payload = "{ "grant_type": "http://auth0.com/oauth/grant-type/passwordless/otp", "client_id": "{yourClientId}", "username": "USER_PHONE_NUMBER", "otp": "code", "realm": "sms", "audience": "your-api-audience", "scope": "openid profile email"}" headers = { 'content-type': "application/json" } @@ -721,8 +763,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample38 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -734,11 +778,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["content-type"] = 'application/json' -request.body = "{ \"grant_type\": \"http://auth0.com/oauth/grant-type/passwordless/otp\", \"client_id\": \"{yourClientId}\", \"username\": \"USER_PHONE_NUMBER\", \"otp\": \"code\", \"realm\": \"sms\", \"audience\": \"your-api-audience\", \"scope\": \"openid profile email\"}" +request.body = "{ "grant_type": "http://auth0.com/oauth/grant-type/passwordless/otp", "client_id": "{yourClientId}", "username": "USER_PHONE_NUMBER", "otp": "code", "realm": "sms", "audience": "your-api-audience", "scope": "openid profile email"}" response = http.request(request) -puts response.read_body`; -export const codeExample39 = `imimport Foundation +puts response.read_body +``` +```swift Swift +imimport Foundation let headers = ["content-type": "application/json"] let parameters = [ @@ -770,32 +816,28 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - +dataTask.resume() +``` + **メールユーザーを認証する** -export const codeExample40 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/json' \ - --data '{"grant_type": "http://auth0.com/oauth/grant-type/passwordless/otp", "client_id": "{yourClientId}", "username": "USER_EMAIL", "otp": "code", "realm": "email", "audience": "your-api-audience", "scope": "openid profile email"}'`; -export const codeExample41 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data '{"grant_type": "http://auth0.com/oauth/grant-type/passwordless/otp", "client_id": "{yourClientId}", "username": "USER_EMAIL", "otp": "code", "realm": "email", "audience": "your-api-audience", "scope": "openid profile email"}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\"grant_type\": \"http://auth0.com/oauth/grant-type/passwordless/otp\", \"client_id\": \"{yourClientId}\", \"username\": \"USER_EMAIL\", \"otp\": \"code\", \"realm\": \"email\", \"audience\": \"your-api-audience\", \"scope\": \"openid profile email\"}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample42 = `package main +request.AddParameter("application/json", "{"grant_type": "http://auth0.com/oauth/grant-type/passwordless/otp", "client_id": "{yourClientId}", "username": "USER_EMAIL", "otp": "code", "realm": "email", "audience": "your-api-audience", "scope": "openid profile email"}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -808,7 +850,7 @@ func main() { url := "https://{yourDomain}/oauth/token" - payload := strings.NewReader("{\"grant_type\": \"http://auth0.com/oauth/grant-type/passwordless/otp\", \"client_id\": \"{yourClientId}\", \"username\": \"USER_EMAIL\", \"otp\": \"code\", \"realm\": \"email\", \"audience\": \"your-api-audience\", \"scope\": \"openid profile email\"}") + payload := strings.NewReader("{"grant_type": "http://auth0.com/oauth/grant-type/passwordless/otp", "client_id": "{yourClientId}", "username": "USER_EMAIL", "otp": "code", "realm": "email", "audience": "your-api-audience", "scope": "openid profile email"}") req, _ := http.NewRequest("POST", url, payload) @@ -822,12 +864,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample43 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/json") - .body("{\"grant_type\": \"http://auth0.com/oauth/grant-type/passwordless/otp\", \"client_id\": \"{yourClientId}\", \"username\": \"USER_EMAIL\", \"otp\": \"code\", \"realm\": \"email\", \"audience\": \"your-api-audience\", \"scope\": \"openid profile email\"}") - .asString();`; -export const codeExample44 = `var axios = require("axios").default; + .body("{"grant_type": "http://auth0.com/oauth/grant-type/passwordless/otp", "client_id": "{yourClientId}", "username": "USER_EMAIL", "otp": "code", "realm": "email", "audience": "your-api-audience", "scope": "openid profile email"}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -848,8 +894,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample45 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json" }; NSDictionary *parameters = @{ @"grant_type": @"http://auth0.com/oauth/grant-type/passwordless/otp", @@ -879,8 +927,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample46 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -890,7 +940,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{\"grant_type\": \"http://auth0.com/oauth/grant-type/passwordless/otp\", \"client_id\": \"{yourClientId}\", \"username\": \"USER_EMAIL\", \"otp\": \"code\", \"realm\": \"email\", \"audience\": \"your-api-audience\", \"scope\": \"openid profile email\"}", + CURLOPT_POSTFIELDS => "{"grant_type": "http://auth0.com/oauth/grant-type/passwordless/otp", "client_id": "{yourClientId}", "username": "USER_EMAIL", "otp": "code", "realm": "email", "audience": "your-api-audience", "scope": "openid profile email"}", CURLOPT_HTTPHEADER => [ "content-type: application/json" ], @@ -905,12 +955,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample47 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"grant_type\": \"http://auth0.com/oauth/grant-type/passwordless/otp\", \"client_id\": \"{yourClientId}\", \"username\": \"USER_EMAIL\", \"otp\": \"code\", \"realm\": \"email\", \"audience\": \"your-api-audience\", \"scope\": \"openid profile email\"}" +payload = "{"grant_type": "http://auth0.com/oauth/grant-type/passwordless/otp", "client_id": "{yourClientId}", "username": "USER_EMAIL", "otp": "code", "realm": "email", "audience": "your-api-audience", "scope": "openid profile email"}" headers = { 'content-type': "application/json" } @@ -919,8 +971,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample48 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -932,11 +986,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["content-type"] = 'application/json' -request.body = "{\"grant_type\": \"http://auth0.com/oauth/grant-type/passwordless/otp\", \"client_id\": \"{yourClientId}\", \"username\": \"USER_EMAIL\", \"otp\": \"code\", \"realm\": \"email\", \"audience\": \"your-api-audience\", \"scope\": \"openid profile email\"}" +request.body = "{"grant_type": "http://auth0.com/oauth/grant-type/passwordless/otp", "client_id": "{yourClientId}", "username": "USER_EMAIL", "otp": "code", "realm": "email", "audience": "your-api-audience", "scope": "openid profile email"}" response = http.request(request) -puts response.read_body`; -export const codeExample49 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/json"] let parameters = [ @@ -968,20 +1024,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + 必要であれば、これらのAPIをプラットフォームに適した方法でラップするAndroidまたはiOSのSDKを使用できます。 diff --git a/main/docs/ja-jp/authenticate/passwordless/implement-login/embedded-login/webapps.mdx b/main/docs/ja-jp/authenticate/passwordless/implement-login/embedded-login/webapps.mdx index 1cdc49ad2..1fb9061a3 100644 --- a/main/docs/ja-jp/authenticate/passwordless/implement-login/embedded-login/webapps.mdx +++ b/main/docs/ja-jp/authenticate/passwordless/implement-login/embedded-login/webapps.mdx @@ -10,6 +10,7 @@ permalink: "webapps" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; 通常のWebアプリケーションで埋め込み型パスワードレスAPIを使用するには、[[Auth0 Dashboard]>[Applications(アプリケーション)]>[Applications(アプリケーション)]](https://manage.auth0.com/#/applications)に移動して、アプリケーション設定の **[Advanced Settings(高度な設定]** > **[Grant Types(付与タイプ)]** で **[Passwordless OTP(パスワードレスOTP)]** の付与を有効にしなければなりません。 @@ -24,16 +25,22 @@ import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; **メールで一回限り使用できるコードを送信する** -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/passwordless/start' \ --header 'content-type: application/json' \ - --data '{"client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "connection": "email", "email": "{userEmail}","send": "code"}'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/passwordless/start"); + --data '{"client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "connection": "email", "email": "{userEmail}","send": "code"}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/passwordless/start"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"connection\": \"email\", \"email\": \"{userEmail}\",\"send\": \"code\"}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{"client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "connection": "email", "email": "{userEmail}","send": "code"}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -46,7 +53,7 @@ func main() { url := "https://{yourDomain}/passwordless/start" - payload := strings.NewReader("{\"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"connection\": \"email\", \"email\": \"{userEmail}\",\"send\": \"code\"}") + payload := strings.NewReader("{"client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "connection": "email", "email": "{userEmail}","send": "code"}") req, _ := http.NewRequest("POST", url, payload) @@ -60,12 +67,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/passwordless/start") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/passwordless/start") .header("content-type", "application/json") - .body("{\"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"connection\": \"email\", \"email\": \"{userEmail}\",\"send\": \"code\"}") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{"client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "connection": "email", "email": "{userEmail}","send": "code"}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -84,8 +95,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json" }; NSDictionary *parameters = @{ @"client_id": @"{yourClientId}", @@ -113,8 +126,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/passwordless/start", @@ -124,7 +139,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{\"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"connection\": \"email\", \"email\": \"{userEmail}\",\"send\": \"code\"}", + CURLOPT_POSTFIELDS => "{"client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "connection": "email", "email": "{userEmail}","send": "code"}", CURLOPT_HTTPHEADER => [ "content-type: application/json" ], @@ -139,12 +154,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"connection\": \"email\", \"email\": \"{userEmail}\",\"send\": \"code\"}" +payload = "{"client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "connection": "email", "email": "{userEmail}","send": "code"}" headers = { 'content-type': "application/json" } @@ -153,8 +170,10 @@ conn.request("POST", "/{yourDomain}/passwordless/start", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -166,11 +185,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["content-type"] = 'application/json' -request.body = "{\"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"connection\": \"email\", \"email\": \"{userEmail}\",\"send\": \"code\"}" +request.body = "{"client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "connection": "email", "email": "{userEmail}","send": "code"}" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/json"] let parameters = [ @@ -200,35 +221,30 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + **メールでマジックリンクを送信する** `send: link`を指定する必要があります。 -export const codeExample11 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/passwordless/start' \ --header 'content-type: application/json' \ - --data '{"client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "connection": "email", "email": "{userEmail}","send": "link"}'`; -export const codeExample12 = `var client = new RestClient("https://{yourDomain}/passwordless/start"); + --data '{"client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "connection": "email", "email": "{userEmail}","send": "link"}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/passwordless/start"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"connection\": \"email\", \"email\": \"{userEmail}\",\"send\": \"link\"}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample13 = `package main +request.AddParameter("application/json", "{"client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "connection": "email", "email": "{userEmail}","send": "link"}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -241,7 +257,7 @@ func main() { url := "https://{yourDomain}/passwordless/start" - payload := strings.NewReader("{\"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"connection\": \"email\", \"email\": \"{userEmail}\",\"send\": \"link\"}") + payload := strings.NewReader("{"client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "connection": "email", "email": "{userEmail}","send": "link"}") req, _ := http.NewRequest("POST", url, payload) @@ -255,12 +271,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample14 = `HttpResponse response = Unirest.post("https://{yourDomain}/passwordless/start") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/passwordless/start") .header("content-type", "application/json") - .body("{\"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"connection\": \"email\", \"email\": \"{userEmail}\",\"send\": \"link\"}") - .asString();`; -export const codeExample15 = `var axios = require("axios").default; + .body("{"client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "connection": "email", "email": "{userEmail}","send": "link"}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -279,8 +299,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample16 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json" }; NSDictionary *parameters = @{ @"client_id": @"{yourClientId}", @@ -308,8 +330,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/passwordless/start", @@ -319,7 +343,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{\"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"connection\": \"email\", \"email\": \"{userEmail}\",\"send\": \"link\"}", + CURLOPT_POSTFIELDS => "{"client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "connection": "email", "email": "{userEmail}","send": "link"}", CURLOPT_HTTPHEADER => [ "content-type: application/json" ], @@ -334,12 +358,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"connection\": \"email\", \"email\": \"{userEmail}\",\"send\": \"link\"}" +payload = "{"client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "connection": "email", "email": "{userEmail}","send": "link"}" headers = { 'content-type': "application/json" } @@ -348,8 +374,10 @@ conn.request("POST", "/{yourDomain}/passwordless/start", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -361,11 +389,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["content-type"] = 'application/json' -request.body = "{\"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"connection\": \"email\", \"email\": \"{userEmail}\",\"send\": \"link\"}" +request.body = "{"client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "connection": "email", "email": "{userEmail}","send": "link"}" response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/json"] let parameters = [ @@ -395,33 +425,28 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + **SMSで一回限り使用できるパスワードを送信する** -export const codeExample21 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/passwordless/start' \ --header 'content-type: application/json' \ - --data '{"client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "connection": "sms", "phone_number": "{userPhoneNumber}","send": "code"}'`; -export const codeExample22 = `var client = new RestClient("https://{yourDomain}/passwordless/start"); + --data '{"client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "connection": "sms", "phone_number": "{userPhoneNumber}","send": "code"}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/passwordless/start"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"connection\": \"sms\", \"phone_number\": \"{userPhoneNumber}\",\"send\": \"code\"}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample23 = `package main +request.AddParameter("application/json", "{"client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "connection": "sms", "phone_number": "{userPhoneNumber}","send": "code"}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -434,7 +459,7 @@ func main() { url := "https://{yourDomain}/passwordless/start" - payload := strings.NewReader("{\"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"connection\": \"sms\", \"phone_number\": \"{userPhoneNumber}\",\"send\": \"code\"}") + payload := strings.NewReader("{"client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "connection": "sms", "phone_number": "{userPhoneNumber}","send": "code"}") req, _ := http.NewRequest("POST", url, payload) @@ -448,12 +473,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample24 = `HttpResponse response = Unirest.post("https://{yourDomain}/passwordless/start") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/passwordless/start") .header("content-type", "application/json") - .body("{\"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"connection\": \"sms\", \"phone_number\": \"{userPhoneNumber}\",\"send\": \"code\"}") - .asString();`; -export const codeExample25 = `var axios = require("axios").default; + .body("{"client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "connection": "sms", "phone_number": "{userPhoneNumber}","send": "code"}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -472,8 +501,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample26 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json" }; NSDictionary *parameters = @{ @"client_id": @"{yourClientId}", @@ -501,8 +532,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample27 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/passwordless/start", @@ -512,7 +545,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{\"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"connection\": \"sms\", \"phone_number\": \"{userPhoneNumber}\",\"send\": \"code\"}", + CURLOPT_POSTFIELDS => "{"client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "connection": "sms", "phone_number": "{userPhoneNumber}","send": "code"}", CURLOPT_HTTPHEADER => [ "content-type: application/json" ], @@ -527,12 +560,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample28 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"connection\": \"sms\", \"phone_number\": \"{userPhoneNumber}\",\"send\": \"code\"}" +payload = "{"client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "connection": "sms", "phone_number": "{userPhoneNumber}","send": "code"}" headers = { 'content-type': "application/json" } @@ -541,8 +576,10 @@ conn.request("POST", "/{yourDomain}/passwordless/start", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample29 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -554,11 +591,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["content-type"] = 'application/json' -request.body = "{\"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"connection\": \"sms\", \"phone_number\": \"{userPhoneNumber}\",\"send\": \"code\"}" +request.body = "{"client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "connection": "sms", "phone_number": "{userPhoneNumber}","send": "code"}" response = http.request(request) -puts response.read_body`; -export const codeExample30 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/json"] let parameters = [ @@ -588,33 +627,28 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + **SMSユーザーを認証する** -export const codeExample31 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/json' \ - --data '{"grant_type": "http://auth0.com/oauth/grant-type/passwordless/otp", "client_id": "{yourClientId}", "client_secret": "YOUR_CLIENT_SECRET", "username": "USER_PHONE_NUMBER", "otp": "code", "realm": "sms", "audience": "your-api-audience","scope": "openid profile email"}'`; -export const codeExample32 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data '{"grant_type": "http://auth0.com/oauth/grant-type/passwordless/otp", "client_id": "{yourClientId}", "client_secret": "YOUR_CLIENT_SECRET", "username": "USER_PHONE_NUMBER", "otp": "code", "realm": "sms", "audience": "your-api-audience","scope": "openid profile email"}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\"grant_type\": \"http://auth0.com/oauth/grant-type/passwordless/otp\", \"client_id\": \"{yourClientId}\", \"client_secret\": \"YOUR_CLIENT_SECRET\", \"username\": \"USER_PHONE_NUMBER\", \"otp\": \"code\", \"realm\": \"sms\", \"audience\": \"your-api-audience\",\"scope\": \"openid profile email\"}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample33 = `package main +request.AddParameter("application/json", "{"grant_type": "http://auth0.com/oauth/grant-type/passwordless/otp", "client_id": "{yourClientId}", "client_secret": "YOUR_CLIENT_SECRET", "username": "USER_PHONE_NUMBER", "otp": "code", "realm": "sms", "audience": "your-api-audience","scope": "openid profile email"}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -627,7 +661,7 @@ func main() { url := "https://{yourDomain}/oauth/token" - payload := strings.NewReader("{\"grant_type\": \"http://auth0.com/oauth/grant-type/passwordless/otp\", \"client_id\": \"{yourClientId}\", \"client_secret\": \"YOUR_CLIENT_SECRET\", \"username\": \"USER_PHONE_NUMBER\", \"otp\": \"code\", \"realm\": \"sms\", \"audience\": \"your-api-audience\",\"scope\": \"openid profile email\"}") + payload := strings.NewReader("{"grant_type": "http://auth0.com/oauth/grant-type/passwordless/otp", "client_id": "{yourClientId}", "client_secret": "YOUR_CLIENT_SECRET", "username": "USER_PHONE_NUMBER", "otp": "code", "realm": "sms", "audience": "your-api-audience","scope": "openid profile email"}") req, _ := http.NewRequest("POST", url, payload) @@ -641,12 +675,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample34 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/json") - .body("{\"grant_type\": \"http://auth0.com/oauth/grant-type/passwordless/otp\", \"client_id\": \"{yourClientId}\", \"client_secret\": \"YOUR_CLIENT_SECRET\", \"username\": \"USER_PHONE_NUMBER\", \"otp\": \"code\", \"realm\": \"sms\", \"audience\": \"your-api-audience\",\"scope\": \"openid profile email\"}") - .asString();`; -export const codeExample35 = `var axios = require("axios").default; + .body("{"grant_type": "http://auth0.com/oauth/grant-type/passwordless/otp", "client_id": "{yourClientId}", "client_secret": "YOUR_CLIENT_SECRET", "username": "USER_PHONE_NUMBER", "otp": "code", "realm": "sms", "audience": "your-api-audience","scope": "openid profile email"}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -668,8 +706,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample36 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json" }; NSDictionary *parameters = @{ @"grant_type": @"http://auth0.com/oauth/grant-type/passwordless/otp", @@ -700,8 +740,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample37 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -711,7 +753,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{\"grant_type\": \"http://auth0.com/oauth/grant-type/passwordless/otp\", \"client_id\": \"{yourClientId}\", \"client_secret\": \"YOUR_CLIENT_SECRET\", \"username\": \"USER_PHONE_NUMBER\", \"otp\": \"code\", \"realm\": \"sms\", \"audience\": \"your-api-audience\",\"scope\": \"openid profile email\"}", + CURLOPT_POSTFIELDS => "{"grant_type": "http://auth0.com/oauth/grant-type/passwordless/otp", "client_id": "{yourClientId}", "client_secret": "YOUR_CLIENT_SECRET", "username": "USER_PHONE_NUMBER", "otp": "code", "realm": "sms", "audience": "your-api-audience","scope": "openid profile email"}", CURLOPT_HTTPHEADER => [ "content-type: application/json" ], @@ -726,12 +768,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample38 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"grant_type\": \"http://auth0.com/oauth/grant-type/passwordless/otp\", \"client_id\": \"{yourClientId}\", \"client_secret\": \"YOUR_CLIENT_SECRET\", \"username\": \"USER_PHONE_NUMBER\", \"otp\": \"code\", \"realm\": \"sms\", \"audience\": \"your-api-audience\",\"scope\": \"openid profile email\"}" +payload = "{"grant_type": "http://auth0.com/oauth/grant-type/passwordless/otp", "client_id": "{yourClientId}", "client_secret": "YOUR_CLIENT_SECRET", "username": "USER_PHONE_NUMBER", "otp": "code", "realm": "sms", "audience": "your-api-audience","scope": "openid profile email"}" headers = { 'content-type': "application/json" } @@ -740,8 +784,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample39 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -753,11 +799,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["content-type"] = 'application/json' -request.body = "{\"grant_type\": \"http://auth0.com/oauth/grant-type/passwordless/otp\", \"client_id\": \"{yourClientId}\", \"client_secret\": \"YOUR_CLIENT_SECRET\", \"username\": \"USER_PHONE_NUMBER\", \"otp\": \"code\", \"realm\": \"sms\", \"audience\": \"your-api-audience\",\"scope\": \"openid profile email\"}" +request.body = "{"grant_type": "http://auth0.com/oauth/grant-type/passwordless/otp", "client_id": "{yourClientId}", "client_secret": "YOUR_CLIENT_SECRET", "username": "USER_PHONE_NUMBER", "otp": "code", "realm": "sms", "audience": "your-api-audience","scope": "openid profile email"}" response = http.request(request) -puts response.read_body`; -export const codeExample40 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/json"] let parameters = [ @@ -790,33 +838,28 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + **メールユーザーを認証する** -export const codeExample41 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/json' \ - --data '{"grant_type": "http://auth0.com/oauth/grant-type/passwordless/otp", "client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "username": "{userPhoneNumber}", "otp": "code", "realm": "email", "audience": "your-api-audience", "scope": "openid profile email"}'`; -export const codeExample42 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data '{"grant_type": "http://auth0.com/oauth/grant-type/passwordless/otp", "client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "username": "{userPhoneNumber}", "otp": "code", "realm": "email", "audience": "your-api-audience", "scope": "openid profile email"}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\"grant_type\": \"http://auth0.com/oauth/grant-type/passwordless/otp\", \"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"username\": \"{userPhoneNumber}\", \"otp\": \"code\", \"realm\": \"email\", \"audience\": \"your-api-audience\", \"scope\": \"openid profile email\"}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample43 = `package main +request.AddParameter("application/json", "{"grant_type": "http://auth0.com/oauth/grant-type/passwordless/otp", "client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "username": "{userPhoneNumber}", "otp": "code", "realm": "email", "audience": "your-api-audience", "scope": "openid profile email"}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -829,7 +872,7 @@ func main() { url := "https://{yourDomain}/oauth/token" - payload := strings.NewReader("{\"grant_type\": \"http://auth0.com/oauth/grant-type/passwordless/otp\", \"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"username\": \"{userPhoneNumber}\", \"otp\": \"code\", \"realm\": \"email\", \"audience\": \"your-api-audience\", \"scope\": \"openid profile email\"}") + payload := strings.NewReader("{"grant_type": "http://auth0.com/oauth/grant-type/passwordless/otp", "client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "username": "{userPhoneNumber}", "otp": "code", "realm": "email", "audience": "your-api-audience", "scope": "openid profile email"}") req, _ := http.NewRequest("POST", url, payload) @@ -843,12 +886,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample44 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/json") - .body("{\"grant_type\": \"http://auth0.com/oauth/grant-type/passwordless/otp\", \"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"username\": \"{userPhoneNumber}\", \"otp\": \"code\", \"realm\": \"email\", \"audience\": \"your-api-audience\", \"scope\": \"openid profile email\"}") - .asString();`; -export const codeExample45 = `var axios = require("axios").default; + .body("{"grant_type": "http://auth0.com/oauth/grant-type/passwordless/otp", "client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "username": "{userPhoneNumber}", "otp": "code", "realm": "email", "audience": "your-api-audience", "scope": "openid profile email"}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -870,8 +917,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample46 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json" }; NSDictionary *parameters = @{ @"grant_type": @"http://auth0.com/oauth/grant-type/passwordless/otp", @@ -902,8 +951,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample47 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -913,7 +964,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{\"grant_type\": \"http://auth0.com/oauth/grant-type/passwordless/otp\", \"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"username\": \"{userPhoneNumber}\", \"otp\": \"code\", \"realm\": \"email\", \"audience\": \"your-api-audience\", \"scope\": \"openid profile email\"}", + CURLOPT_POSTFIELDS => "{"grant_type": "http://auth0.com/oauth/grant-type/passwordless/otp", "client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "username": "{userPhoneNumber}", "otp": "code", "realm": "email", "audience": "your-api-audience", "scope": "openid profile email"}", CURLOPT_HTTPHEADER => [ "content-type: application/json" ], @@ -928,12 +979,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample48 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"grant_type\": \"http://auth0.com/oauth/grant-type/passwordless/otp\", \"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"username\": \"{userPhoneNumber}\", \"otp\": \"code\", \"realm\": \"email\", \"audience\": \"your-api-audience\", \"scope\": \"openid profile email\"}" +payload = "{"grant_type": "http://auth0.com/oauth/grant-type/passwordless/otp", "client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "username": "{userPhoneNumber}", "otp": "code", "realm": "email", "audience": "your-api-audience", "scope": "openid profile email"}" headers = { 'content-type': "application/json" } @@ -942,8 +995,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample49 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -955,11 +1010,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["content-type"] = 'application/json' -request.body = "{\"grant_type\": \"http://auth0.com/oauth/grant-type/passwordless/otp\", \"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"username\": \"{userPhoneNumber}\", \"otp\": \"code\", \"realm\": \"email\", \"audience\": \"your-api-audience\", \"scope\": \"openid profile email\"}" +request.body = "{"grant_type": "http://auth0.com/oauth/grant-type/passwordless/otp", "client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "username": "{userPhoneNumber}", "otp": "code", "realm": "email", "audience": "your-api-audience", "scope": "openid profile email"}" response = http.request(request) -puts response.read_body`; -export const codeExample50 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/json"] let parameters = [ @@ -992,20 +1049,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + **マジックリンクを通してユーザーを認証する** diff --git a/main/docs/ja-jp/authenticate/protocols/saml/saml-identity-provider-configuration-settings.mdx b/main/docs/ja-jp/authenticate/protocols/saml/saml-identity-provider-configuration-settings.mdx index fa72888a1..e461cb0cf 100644 --- a/main/docs/ja-jp/authenticate/protocols/saml/saml-identity-provider-configuration-settings.mdx +++ b/main/docs/ja-jp/authenticate/protocols/saml/saml-identity-provider-configuration-settings.mdx @@ -10,6 +10,7 @@ permalink: "saml-identity-provider-configuration-settings" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; ## 共通設定 @@ -53,14 +54,20 @@ urn:auth0:{yourTenant}:{yourConnectionName} カスタムエンティティIDは接続取得エンドポイントを用いて取得することができます。 -export const codeExample3 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/connections/%7ByourConnectionID%7D' \ - --header 'authorization: Bearer {yourAccessToken}'`; -export const codeExample4 = `var client = new RestClient("https://{yourDomain}/api/v2/connections/%7ByourConnectionID%7D"); + --header 'authorization: Bearer {yourAccessToken}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/connections/%7ByourConnectionID%7D"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer {yourAccessToken}"); -IRestResponse response = client.Execute(request);`; -export const codeExample5 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -84,11 +91,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample6 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/connections/%7ByourConnectionID%7D") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/connections/%7ByourConnectionID%7D") .header("authorization", "Bearer {yourAccessToken}") - .asString();`; -export const codeExample7 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -100,8 +111,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample8 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer {yourAccessToken}" }; @@ -121,8 +134,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample9 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/connections/%7ByourConnectionID%7D", @@ -146,8 +161,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample10 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -158,8 +175,10 @@ conn.request("GET", "/{yourDomain}/api/v2/connections/%7ByourConnectionID%7D", h res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample11 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -173,8 +192,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer {yourAccessToken}' response = http.request(request) -puts response.read_body`; -export const codeExample12 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer {yourAccessToken}"] @@ -194,20 +215,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + `ACCESS_TOKEN`ヘッダー値をManagement APIv2アクセストークンと置き換えます。 diff --git a/main/docs/ja-jp/authenticate/single-sign-on/native-to-web/configure-implement-native-to-web.mdx b/main/docs/ja-jp/authenticate/single-sign-on/native-to-web/configure-implement-native-to-web.mdx index 019902f20..c53356d4a 100644 --- a/main/docs/ja-jp/authenticate/single-sign-on/native-to-web/configure-implement-native-to-web.mdx +++ b/main/docs/ja-jp/authenticate/single-sign-on/native-to-web/configure-implement-native-to-web.mdx @@ -10,6 +10,7 @@ permalink: "configure-implement-native-to-web" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; @@ -66,8 +67,6 @@ You can configure your native application to exchange a Access Token with the [Update a Client](https://auth0.com/docs/api/management/v2/clients/patch-clients-by-id) endpoint: - - export const codeExample1 = `curl --request PATCH \ --url 'https://{yourDomain}/api/v2/clients/{yourClientId}' \ --header 'authorization: Bearer {yourMgmtApiAccessToken}' \ @@ -93,8 +92,6 @@ Before you enable Session Transfer Token, make sure you have configured your web * Update your web application using the Management API Access Token with the [Update a Client](https://auth0.com/docs/api/management/v2/clients/patch-clients-by-id) endpoint: - - export const codeExample3 = `curl --request PATCH \ --url '{yourDomain}/api/v2/clients//{yourClientId}' \ --header 'authorization: Bearer {yourMgmtApiAccessToken}' \ @@ -177,8 +174,6 @@ authentication * Exchange a refresh token for a session transfer token using HTTP: - - export const codeExample5 = `curl -X POST https://{yourDomain}/oauth/token \ -H 'Content-type: application/json' \ -d '{"grant_type":"refresh_token", @@ -238,7 +233,7 @@ If your web application does not support cookie injection, you can configure you * Open the web application using  WebView or browser. * Log the web application appending the `session_transfer_token` as a URL parameter to the [/authorize](https://auth0.com/docs/api/authentication/authorization-code-flow/authorize-application) endpoint. The Auth0 tenant authenticates the user without requiring first-factor authentication, as the session_transfer_token is valid and trusted - + ```bash cURL lines curl --request GET \ --url 'https://your_web_app_login_url/?session_transfer_token=YOUR_SESSION_TRANSFER_TOKEN' @@ -388,7 +383,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + ### In your web application @@ -404,12 +399,18 @@ Implement Native to Web Web Single SSO in your web application using URL paramet From the application login URL, redirect to the `/authorize` endpoint when the `session_transfer_token` is sent as a URL parameter. -export const codeExample7 = `curl --request GET \ - --url 'https://{yourDomain}/authorize?session_transfer_token=YOUR_SESSION_TRANSFER_TOKEN&client_ID={yourClientId}&redirect_uri=YOUR_REDIRECT_URI&response_type=code'`; -export const codeExample8 = `var client = new RestClient("https://{yourDomain}/authorize?session_transfer_token=YOUR_SESSION_TRANSFER_TOKEN&client_ID={yourClientId}&redirect_uri=YOUR_REDIRECT_URI&response_type=code"); + +```bash cURL +curl --request GET \ + --url 'https://{yourDomain}/authorize?session_transfer_token=YOUR_SESSION_TRANSFER_TOKEN&client_ID={yourClientId}&redirect_uri=YOUR_REDIRECT_URI&response_type=code' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/authorize?session_transfer_token=YOUR_SESSION_TRANSFER_TOKEN&client_ID={yourClientId}&redirect_uri=YOUR_REDIRECT_URI&response_type=code"); var request = new RestRequest(Method.GET); -IRestResponse response = client.Execute(request);`; -export const codeExample9 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -431,10 +432,14 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample10 = `HttpResponse response = Unirest.get("https://{yourDomain}/authorize?session_transfer_token=YOUR_SESSION_TRANSFER_TOKEN&client_ID={yourClientId}&redirect_uri=YOUR_REDIRECT_URI&response_type=code") - .asString();`; -export const codeExample11 = `var axios = require("axios").default; +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/authorize?session_transfer_token=YOUR_SESSION_TRANSFER_TOKEN&client_ID={yourClientId}&redirect_uri=YOUR_REDIRECT_URI&response_type=code") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -451,8 +456,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample12 = `#import +}); +``` +```obj-c Obj-C +#import NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://{yourDomain}/authorize?session_transfer_token=YOUR_SESSION_TRANSFER_TOKEN&client_ID={yourClientId}&redirect_uri=YOUR_REDIRECT_URI&response_type=code"] cachePolicy:NSURLRequestUseProtocolCachePolicy @@ -469,8 +476,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample13 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/authorize?session_transfer_token=YOUR_SESSION_TRANSFER_TOKEN&client_ID={yourClientId}&redirect_uri=YOUR_REDIRECT_URI&response_type=code", @@ -491,8 +500,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample14 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -501,8 +512,10 @@ conn.request("GET", "/{yourDomain}/authorize?session_transfer_token=YOUR_SESSION res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample15 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -515,8 +528,10 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Get.new(url) response = http.request(request) -puts response.read_body`; -export const codeExample16 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let request = NSMutableURLRequest(url: NSURL(string: "https://{yourDomain}/authorize?session_transfer_token=YOUR_SESSION_TRANSFER_TOKEN&client_ID={yourClientId}&redirect_uri=YOUR_REDIRECT_URI&response_type=code")! as URL, cachePolicy: .useProtocolCachePolicy, @@ -533,20 +548,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + #### Option 2: Add the Session Transfer Token to web applications using Auth0 SDKs @@ -585,15 +589,21 @@ app.use((req, res, next) => { If your web application uses SAML or WS-Fed service provider and Auth0 as the IdP, you can send the `session_transfer_token` as an URL parameter to the Auth0 `/authorize` endpoint and the `redirect_uri` is the SAML or WS-Fed sign-in URL. -export const codeExample17 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/samlp//{yourClientId}?session_transfer_token=YOUR_SESSION_TRANSFER_TOKEN' \ --header 'cookie: session_transfer_token=YOUR_SESSION_TRANSFER_TOKEN' \ - --cookie session_transfer_token=YOUR_SESSION_TRANSFER_TOKEN`; -export const codeExample18 = `var client = new RestClient("https://{yourDomain}/samlp//{yourClientId}?session_transfer_token=YOUR_SESSION_TRANSFER_TOKEN"); + --cookie session_transfer_token=YOUR_SESSION_TRANSFER_TOKEN +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/samlp//{yourClientId}?session_transfer_token=YOUR_SESSION_TRANSFER_TOKEN"); var request = new RestRequest(Method.GET); request.AddHeader("cookie", "session_transfer_token=YOUR_SESSION_TRANSFER_TOKEN"); -IRestResponse response = client.Execute(request);`; -export const codeExample19 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -616,11 +626,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample20 = `HttpResponse response = Unirest.get("https://{yourDomain}/samlp//{yourClientId}?session_transfer_token=YOUR_SESSION_TRANSFER_TOKEN") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/samlp//{yourClientId}?session_transfer_token=YOUR_SESSION_TRANSFER_TOKEN") .header("cookie", "session_transfer_token=YOUR_SESSION_TRANSFER_TOKEN") - .asString();`; -export const codeExample21 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -633,8 +647,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample22 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"cookie": @"session_transfer_token=YOUR_SESSION_TRANSFER_TOKEN" }; @@ -654,8 +670,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample23 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/samlp//{yourClientId}?session_transfer_token=YOUR_SESSION_TRANSFER_TOKEN", @@ -679,8 +697,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample24 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -691,8 +711,10 @@ conn.request("GET", "/{yourDomain}/samlp//{yourClientId}?session_transfer_token= res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample25 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -706,8 +728,10 @@ request = Net::HTTP::Get.new(url) request["cookie"] = 'session_transfer_token=YOUR_SESSION_TRANSFER_TOKEN' response = http.request(request) -puts response.read_body`; -export const codeExample26 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["cookie": "session_transfer_token=YOUR_SESSION_TRANSFER_TOKEN"] @@ -727,20 +751,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ## Session Transfer Token with Actions diff --git a/main/docs/ja-jp/customize/custom-domains/multiple-custom-domains.mdx b/main/docs/ja-jp/customize/custom-domains/multiple-custom-domains.mdx index c47ff76d6..3746f1c1e 100644 --- a/main/docs/ja-jp/customize/custom-domains/multiple-custom-domains.mdx +++ b/main/docs/ja-jp/customize/custom-domains/multiple-custom-domains.mdx @@ -10,6 +10,7 @@ permalink: "multiple-custom-domains" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; @@ -71,7 +72,9 @@ To create a custom domain with the Management API, you need a machine-to-machine You can create a new custom domain by sending a `POST` request to the `/api/v2/custom-domains` endpoint. See the example below to create a new custom domain using the Management API explorer, using the credentials retrieved above: -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/api/v2/custom-domains' \ --header 'accept: application/json' \ --header 'authorization: Bearer {yourMgmtApiAccessToken}' \ @@ -83,15 +86,26 @@ export const codeExample1 = `curl --request POST \ "custom_client_ip_header": "true-client-ip", "domain_metadata": { "environment": "development"} -}'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/custom-domains"); +}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/custom-domains"); var request = new RestRequest(Method.POST); request.AddHeader("authorization", "Bearer {yourMgmtApiAccessToken}"); request.AddHeader("content-type", "application/json"); request.AddHeader("accept", "application/json"); -request.AddParameter("application/json", "{ \n \"domain\": \"your.example-custom-domain.com\", \n \"type\": \"auth0_managed_certs\", \n \"tls_policy\": \"recommended\", \n \"custom_client_ip_header\": \"true-client-ip\", \n \"domain_metadata\": {\n \"environment\": \"development\"} \n}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ + "domain": "your.example-custom-domain.com", + "type": "auth0_managed_certs", + "tls_policy": "recommended", + "custom_client_ip_header": "true-client-ip", + "domain_metadata": { + "environment": "development"} +}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -104,7 +118,14 @@ func main() { url := "https://{yourDomain}/api/v2/custom-domains" - payload := strings.NewReader("{ \n \"domain\": \"your.example-custom-domain.com\", \n \"type\": \"auth0_managed_certs\", \n \"tls_policy\": \"recommended\", \n \"custom_client_ip_header\": \"true-client-ip\", \n \"domain_metadata\": {\n \"environment\": \"development\"} \n}") + payload := strings.NewReader("{ + "domain": "your.example-custom-domain.com", + "type": "auth0_managed_certs", + "tls_policy": "recommended", + "custom_client_ip_header": "true-client-ip", + "domain_metadata": { + "environment": "development"} +}") req, _ := http.NewRequest("POST", url, payload) @@ -120,14 +141,25 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/custom-domains") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/custom-domains") .header("authorization", "Bearer {yourMgmtApiAccessToken}") .header("content-type", "application/json") .header("accept", "application/json") - .body("{ \n \"domain\": \"your.example-custom-domain.com\", \n \"type\": \"auth0_managed_certs\", \n \"tls_policy\": \"recommended\", \n \"custom_client_ip_header\": \"true-client-ip\", \n \"domain_metadata\": {\n \"environment\": \"development\"} \n}") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ + "domain": "your.example-custom-domain.com", + "type": "auth0_managed_certs", + "tls_policy": "recommended", + "custom_client_ip_header": "true-client-ip", + "domain_metadata": { + "environment": "development"} +}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -150,8 +182,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer {yourMgmtApiAccessToken}", @"content-type": @"application/json", @@ -181,8 +215,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/custom-domains", @@ -192,7 +228,14 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{ \n \"domain\": \"your.example-custom-domain.com\", \n \"type\": \"auth0_managed_certs\", \n \"tls_policy\": \"recommended\", \n \"custom_client_ip_header\": \"true-client-ip\", \n \"domain_metadata\": {\n \"environment\": \"development\"} \n}", + CURLOPT_POSTFIELDS => "{ + "domain": "your.example-custom-domain.com", + "type": "auth0_managed_certs", + "tls_policy": "recommended", + "custom_client_ip_header": "true-client-ip", + "domain_metadata": { + "environment": "development"} +}", CURLOPT_HTTPHEADER => [ "accept: application/json", "authorization: Bearer {yourMgmtApiAccessToken}", @@ -209,12 +252,21 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \n \"domain\": \"your.example-custom-domain.com\", \n \"type\": \"auth0_managed_certs\", \n \"tls_policy\": \"recommended\", \n \"custom_client_ip_header\": \"true-client-ip\", \n \"domain_metadata\": {\n \"environment\": \"development\"} \n}" +payload = "{ + "domain": "your.example-custom-domain.com", + "type": "auth0_managed_certs", + "tls_policy": "recommended", + "custom_client_ip_header": "true-client-ip", + "domain_metadata": { + "environment": "development"} +}" headers = { 'authorization': "Bearer {yourMgmtApiAccessToken}", @@ -227,8 +279,10 @@ conn.request("POST", "/{yourDomain}/api/v2/custom-domains", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -242,11 +296,20 @@ request = Net::HTTP::Post.new(url) request["authorization"] = 'Bearer {yourMgmtApiAccessToken}' request["content-type"] = 'application/json' request["accept"] = 'application/json' -request.body = "{ \n \"domain\": \"your.example-custom-domain.com\", \n \"type\": \"auth0_managed_certs\", \n \"tls_policy\": \"recommended\", \n \"custom_client_ip_header\": \"true-client-ip\", \n \"domain_metadata\": {\n \"environment\": \"development\"} \n}" +request.body = "{ + "domain": "your.example-custom-domain.com", + "type": "auth0_managed_certs", + "tls_policy": "recommended", + "custom_client_ip_header": "true-client-ip", + "domain_metadata": { + "environment": "development"} +}" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "authorization": "Bearer {yourMgmtApiAccessToken}", @@ -280,20 +343,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + If successful, you should see the following returned with the details of your new custom domain, including it's verification status. The `status` is initially returned as `pending`. diff --git a/main/docs/ja-jp/customize/email/manage-email-flow.mdx b/main/docs/ja-jp/customize/email/manage-email-flow.mdx index ebb956798..b2ab203a1 100644 --- a/main/docs/ja-jp/customize/email/manage-email-flow.mdx +++ b/main/docs/ja-jp/customize/email/manage-email-flow.mdx @@ -10,6 +10,7 @@ permalink: "manage-email-flow" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; @@ -49,18 +50,24 @@ Auth0 response = Unirest.post("https://{yourDomain}/api/v2/jobs/verification-email") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/jobs/verification-email") .header("content-type", "application/json") .header("authorization", "Bearer {yourMgmtApiAccessToken}") - .body("{ \"user_id\": \"{userIdOfVerifyEmailRecipient}\", \"client_id\": \"{yourAppClientId}\",\"identity\": {\"user_id\": \"5457edea1b8f22891a000004\",\"provider\": \"google-oauth2\"}, \"organization_id\": \"{yourOrganizationId}\" }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "user_id": "{userIdOfVerifyEmailRecipient}", "client_id": "{yourAppClientId}","identity": {"user_id": "5457edea1b8f22891a000004","provider": "google-oauth2"}, "organization_id": "{yourOrganizationId}" }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -115,8 +126,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer {yourMgmtApiAccessToken}" }; @@ -144,8 +157,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/jobs/verification-email", @@ -155,7 +170,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{ \"user_id\": \"{userIdOfVerifyEmailRecipient}\", \"client_id\": \"{yourAppClientId}\",\"identity\": {\"user_id\": \"5457edea1b8f22891a000004\",\"provider\": \"google-oauth2\"}, \"organization_id\": \"{yourOrganizationId}\" }", + CURLOPT_POSTFIELDS => "{ "user_id": "{userIdOfVerifyEmailRecipient}", "client_id": "{yourAppClientId}","identity": {"user_id": "5457edea1b8f22891a000004","provider": "google-oauth2"}, "organization_id": "{yourOrganizationId}" }", CURLOPT_HTTPHEADER => [ "authorization: Bearer {yourMgmtApiAccessToken}", "content-type: application/json" @@ -171,12 +186,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"user_id\": \"{userIdOfVerifyEmailRecipient}\", \"client_id\": \"{yourAppClientId}\",\"identity\": {\"user_id\": \"5457edea1b8f22891a000004\",\"provider\": \"google-oauth2\"}, \"organization_id\": \"{yourOrganizationId}\" }" +payload = "{ "user_id": "{userIdOfVerifyEmailRecipient}", "client_id": "{yourAppClientId}","identity": {"user_id": "5457edea1b8f22891a000004","provider": "google-oauth2"}, "organization_id": "{yourOrganizationId}" }" headers = { 'content-type': "application/json", @@ -188,8 +205,10 @@ conn.request("POST", "/{yourDomain}/api/v2/jobs/verification-email", payload, he res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -202,11 +221,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer {yourMgmtApiAccessToken}' -request.body = "{ \"user_id\": \"{userIdOfVerifyEmailRecipient}\", \"client_id\": \"{yourAppClientId}\",\"identity\": {\"user_id\": \"5457edea1b8f22891a000004\",\"provider\": \"google-oauth2\"}, \"organization_id\": \"{yourOrganizationId}\" }" +request.body = "{ "user_id": "{userIdOfVerifyEmailRecipient}", "client_id": "{yourAppClientId}","identity": {"user_id": "5457edea1b8f22891a000004","provider": "google-oauth2"}, "organization_id": "{yourOrganizationId}" }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -241,20 +262,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + diff --git a/main/docs/ja-jp/customize/hooks/create-hooks.mdx b/main/docs/ja-jp/customize/hooks/create-hooks.mdx index b7e734eb9..37d0b18a5 100644 --- a/main/docs/ja-jp/customize/hooks/create-hooks.mdx +++ b/main/docs/ja-jp/customize/hooks/create-hooks.mdx @@ -10,6 +10,7 @@ permalink: "create-hooks" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; @@ -58,20 +59,26 @@ RulesからActionsへの移行方法については、「[RulesからActionsに [フック作成エンドポイント](/docs/ja-jp/api/management/v2/#!/Hooks/post_hooks)に`POST`呼び出しを行います。`MGMT_API_ACCESS_TOKEN`、`HOOK_NAME`、`HOOK_SCRIPT`、`EXTENSIBILITY_POINT_NAME`のプレースホルダーをそれぞれ実際のManagement APIのアクセストークン、フック名、フックスクリプト、および拡張ポイント名に置き換えます。 -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/api/v2/hooks' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{ "name": "HOOK_NAME", "script": "HOOK_SCRIPT", "triggerId": "EXTENSIBILITY_POINT_NAME" }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/hooks"); + --data '{ "name": "HOOK_NAME", "script": "HOOK_SCRIPT", "triggerId": "EXTENSIBILITY_POINT_NAME" }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/hooks"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{ \"name\": \"HOOK_NAME\", \"script\": \"HOOK_SCRIPT\", \"triggerId\": \"EXTENSIBILITY_POINT_NAME\" }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "name": "HOOK_NAME", "script": "HOOK_SCRIPT", "triggerId": "EXTENSIBILITY_POINT_NAME" }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -84,7 +91,7 @@ func main() { url := "https://{yourDomain}/api/v2/hooks" - payload := strings.NewReader("{ \"name\": \"HOOK_NAME\", \"script\": \"HOOK_SCRIPT\", \"triggerId\": \"EXTENSIBILITY_POINT_NAME\" }") + payload := strings.NewReader("{ "name": "HOOK_NAME", "script": "HOOK_SCRIPT", "triggerId": "EXTENSIBILITY_POINT_NAME" }") req, _ := http.NewRequest("POST", url, payload) @@ -100,14 +107,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/hooks") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/hooks") .header("content-type", "application/json") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ \"name\": \"HOOK_NAME\", \"script\": \"HOOK_SCRIPT\", \"triggerId\": \"EXTENSIBILITY_POINT_NAME\" }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "name": "HOOK_NAME", "script": "HOOK_SCRIPT", "triggerId": "EXTENSIBILITY_POINT_NAME" }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -128,8 +139,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @@ -157,8 +170,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/hooks", @@ -168,7 +183,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{ \"name\": \"HOOK_NAME\", \"script\": \"HOOK_SCRIPT\", \"triggerId\": \"EXTENSIBILITY_POINT_NAME\" }", + CURLOPT_POSTFIELDS => "{ "name": "HOOK_NAME", "script": "HOOK_SCRIPT", "triggerId": "EXTENSIBILITY_POINT_NAME" }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "cache-control: no-cache", @@ -185,12 +200,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"name\": \"HOOK_NAME\", \"script\": \"HOOK_SCRIPT\", \"triggerId\": \"EXTENSIBILITY_POINT_NAME\" }" +payload = "{ "name": "HOOK_NAME", "script": "HOOK_SCRIPT", "triggerId": "EXTENSIBILITY_POINT_NAME" }" headers = { 'content-type': "application/json", @@ -203,12 +220,14 @@ conn.request("POST", "/{yourDomain}/api/v2/hooks", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `import http.client +print(data.decode("utf-8")) +``` +```ruby Ruby +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"name\": \"HOOK_NAME\", \"script\": \"HOOK_SCRIPT\", \"triggerId\": \"EXTENSIBILITY_POINT_NAME\" }" +payload = "{ "name": "HOOK_NAME", "script": "HOOK_SCRIPT", "triggerId": "EXTENSIBILITY_POINT_NAME" }" headers = { 'content-type': "application/json", @@ -221,8 +240,10 @@ conn.request("POST", "/{yourDomain}/api/v2/hooks", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample10 = `import Foundation +print(data.decode("utf-8")) +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -254,20 +275,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
    diff --git a/main/docs/ja-jp/customize/hooks/delete-hooks.mdx b/main/docs/ja-jp/customize/hooks/delete-hooks.mdx index 546ce8632..7f590f4f2 100644 --- a/main/docs/ja-jp/customize/hooks/delete-hooks.mdx +++ b/main/docs/ja-jp/customize/hooks/delete-hooks.mdx @@ -10,6 +10,7 @@ permalink: "delete-hooks" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; @@ -42,14 +43,20 @@ RulesからActionsへの移行方法については、「[RulesからActionsに [[Delete a Hook endpoint(フックエンドポイントの削除)]](/docs/ja-jp/api/management/v2/#!/Hooks/delete_hooks_by_id)に対して、`[DELETE(削除)]`呼び出しを行います。`HOOK_ID`と`MGMT_API_ACCESS_TOKEN`のプレースホルダーの値を、それぞれフックIDとManagement APIのアクセストークンに置き換えてください。 -export const codeExample1 = `curl --request DELETE \ + +```bash cURL +curl --request DELETE \ --url 'https://{yourDomain}/api/v2/hooks/HOOK_ID' \ - --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/hooks/HOOK_ID"); + --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/hooks/HOOK_ID"); var request = new RestRequest(Method.DELETE); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -73,11 +80,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.delete("https://{yourDomain}/api/v2/hooks/HOOK_ID") +} +``` +```java Java +HttpResponse response = Unirest.delete("https://{yourDomain}/api/v2/hooks/HOOK_ID") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'DELETE', @@ -89,8 +100,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN" }; @@ -110,8 +123,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/hooks/HOOK_ID", @@ -135,8 +150,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -147,8 +164,10 @@ conn.request("DELETE", "/{yourDomain}/api/v2/hooks/HOOK_ID", headers=headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -162,8 +181,10 @@ request = Net::HTTP::Delete.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer MGMT_API_ACCESS_TOKEN"] @@ -183,20 +204,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
    diff --git a/main/docs/ja-jp/customize/hooks/enable-disable-hooks.mdx b/main/docs/ja-jp/customize/hooks/enable-disable-hooks.mdx index 2ec3d76ee..a8aeaf96a 100644 --- a/main/docs/ja-jp/customize/hooks/enable-disable-hooks.mdx +++ b/main/docs/ja-jp/customize/hooks/enable-disable-hooks.mdx @@ -10,6 +10,7 @@ permalink: "enable-disable-hooks" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; @@ -60,20 +61,26 @@ RulesからActionsへの移行方法については、「[RulesからActionsに [フック更新エンドポイント](/docs/ja-jp/api/management/v2/#!/Hooks/patch_hooks_by_id)に`PATCH`呼び出しを行います。`HOOK_ID`と`MGMT_API_ACCESS_TOKEN`のプレースホルダーの値を、それぞれフックIDとManagement APIのアクセストークンに置き換えてください。 -export const codeExample1 = `curl --request PATCH \ + +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/hooks/HOOK_ID' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{ "enabled": "true" }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/hooks/HOOK_ID"); + --data '{ "enabled": "true" }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/hooks/HOOK_ID"); var request = new RestRequest(Method.PATCH); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{ \"enabled\": \"true\" }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "enabled": "true" }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -86,7 +93,7 @@ func main() { url := "https://{yourDomain}/api/v2/hooks/HOOK_ID" - payload := strings.NewReader("{ \"enabled\": \"true\" }") + payload := strings.NewReader("{ "enabled": "true" }") req, _ := http.NewRequest("PATCH", url, payload) @@ -102,14 +109,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/hooks/HOOK_ID") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/hooks/HOOK_ID") .header("content-type", "application/json") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ \"enabled\": \"true\" }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "enabled": "true" }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -126,8 +137,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @@ -153,8 +166,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/hooks/HOOK_ID", @@ -164,7 +179,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{ \"enabled\": \"true\" }", + CURLOPT_POSTFIELDS => "{ "enabled": "true" }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "cache-control: no-cache", @@ -181,12 +196,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"enabled\": \"true\" }" +payload = "{ "enabled": "true" }" headers = { 'content-type': "application/json", @@ -199,8 +216,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/hooks/HOOK_ID", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -214,11 +233,13 @@ request = Net::HTTP::Patch.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ \"enabled\": \"true\" }" +request.body = "{ "enabled": "true" }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -246,20 +267,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
    diff --git a/main/docs/ja-jp/customize/hooks/hook-secrets/create-hook-secrets.mdx b/main/docs/ja-jp/customize/hooks/hook-secrets/create-hook-secrets.mdx index a6f394695..249891683 100644 --- a/main/docs/ja-jp/customize/hooks/hook-secrets/create-hook-secrets.mdx +++ b/main/docs/ja-jp/customize/hooks/hook-secrets/create-hook-secrets.mdx @@ -10,6 +10,7 @@ permalink: "create-hook-secrets" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; @@ -52,20 +53,26 @@ Dashboardや +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/api/v2/hooks/HOOK_ID/secrets' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{ [ "HOOK_SECRET_KEY", "HOOK_SECRET_VALUE" ], [ "HOOK_SECRET_KEY", "HOOK_SECRET_VALUE" ] }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/hooks/HOOK_ID/secrets"); + --data '{ [ "HOOK_SECRET_KEY", "HOOK_SECRET_VALUE" ], [ "HOOK_SECRET_KEY", "HOOK_SECRET_VALUE" ] }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/hooks/HOOK_ID/secrets"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{ [ \"HOOK_SECRET_KEY\", \"HOOK_SECRET_VALUE\" ], [ \"HOOK_SECRET_KEY\", \"HOOK_SECRET_VALUE\" ] }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ [ "HOOK_SECRET_KEY", "HOOK_SECRET_VALUE" ], [ "HOOK_SECRET_KEY", "HOOK_SECRET_VALUE" ] }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -78,7 +85,7 @@ func main() { url := "https://{yourDomain}/api/v2/hooks/HOOK_ID/secrets" - payload := strings.NewReader("{ [ \"HOOK_SECRET_KEY\", \"HOOK_SECRET_VALUE\" ], [ \"HOOK_SECRET_KEY\", \"HOOK_SECRET_VALUE\" ] }") + payload := strings.NewReader("{ [ "HOOK_SECRET_KEY", "HOOK_SECRET_VALUE" ], [ "HOOK_SECRET_KEY", "HOOK_SECRET_VALUE" ] }") req, _ := http.NewRequest("POST", url, payload) @@ -94,14 +101,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/hooks/HOOK_ID/secrets") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/hooks/HOOK_ID/secrets") .header("content-type", "application/json") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ [ \"HOOK_SECRET_KEY\", \"HOOK_SECRET_VALUE\" ], [ \"HOOK_SECRET_KEY\", \"HOOK_SECRET_VALUE\" ] }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ [ "HOOK_SECRET_KEY", "HOOK_SECRET_VALUE" ], [ "HOOK_SECRET_KEY", "HOOK_SECRET_VALUE" ] }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -118,8 +129,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @@ -144,8 +157,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/hooks/HOOK_ID/secrets", @@ -155,7 +170,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{ [ \"HOOK_SECRET_KEY\", \"HOOK_SECRET_VALUE\" ], [ \"HOOK_SECRET_KEY\", \"HOOK_SECRET_VALUE\" ] }", + CURLOPT_POSTFIELDS => "{ [ "HOOK_SECRET_KEY", "HOOK_SECRET_VALUE" ], [ "HOOK_SECRET_KEY", "HOOK_SECRET_VALUE" ] }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "cache-control: no-cache", @@ -172,12 +187,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ [ \"HOOK_SECRET_KEY\", \"HOOK_SECRET_VALUE\" ], [ \"HOOK_SECRET_KEY\", \"HOOK_SECRET_VALUE\" ] }" +payload = "{ [ "HOOK_SECRET_KEY", "HOOK_SECRET_VALUE" ], [ "HOOK_SECRET_KEY", "HOOK_SECRET_VALUE" ] }" headers = { 'content-type': "application/json", @@ -190,8 +207,10 @@ conn.request("POST", "/{yourDomain}/api/v2/hooks/HOOK_ID/secrets", payload, head res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -205,11 +224,13 @@ request = Net::HTTP::Post.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ [ \"HOOK_SECRET_KEY\", \"HOOK_SECRET_VALUE\" ], [ \"HOOK_SECRET_KEY\", \"HOOK_SECRET_VALUE\" ] }" +request.body = "{ [ "HOOK_SECRET_KEY", "HOOK_SECRET_VALUE" ], [ "HOOK_SECRET_KEY", "HOOK_SECRET_VALUE" ] }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -236,20 +257,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
    diff --git a/main/docs/ja-jp/customize/hooks/hook-secrets/delete-hook-secrets.mdx b/main/docs/ja-jp/customize/hooks/hook-secrets/delete-hook-secrets.mdx index c6bf765ae..db3328ff6 100644 --- a/main/docs/ja-jp/customize/hooks/hook-secrets/delete-hook-secrets.mdx +++ b/main/docs/ja-jp/customize/hooks/hook-secrets/delete-hook-secrets.mdx @@ -10,6 +10,7 @@ permalink: "delete-hook-secrets" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; @@ -45,16 +46,22 @@ RulesからActionsへの移行方法については、「[RulesからActionsに [フックシークレット削除エンドポイント](/docs/ja-jp/api/management/v2/#!/Hooks/delete_secrets)に対して`DELETE`呼び出しを行います。`HOOK_ID`、`HOOK_SECRET_NAME`、および`MGMT_API_ACCESS_TOKEN`プレースホルダーの値を、それぞれ実際のフックID、フックシークレット名、Management APIのアクセストークンに必ず置き換えてください。 -export const codeExample1 = `curl --request DELETE \ + +```bash cURL +curl --request DELETE \ --url 'https://{yourDomain}/api/v2/hooks/HOOK_ID/secrets' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ - --data '{ [ "HOOK_SECRET_NAME", "HOOK_SECRET_NAME" ] }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/hooks/HOOK_ID/secrets"); + --data '{ [ "HOOK_SECRET_NAME", "HOOK_SECRET_NAME" ] }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/hooks/HOOK_ID/secrets"); var request = new RestRequest(Method.DELETE); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); -request.AddParameter("undefined", "{ [ \"HOOK_SECRET_NAME\", \"HOOK_SECRET_NAME\" ] }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("undefined", "{ [ "HOOK_SECRET_NAME", "HOOK_SECRET_NAME" ] }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -67,7 +74,7 @@ func main() { url := "https://{yourDomain}/api/v2/hooks/HOOK_ID/secrets" - payload := strings.NewReader("{ [ \"HOOK_SECRET_NAME\", \"HOOK_SECRET_NAME\" ] }") + payload := strings.NewReader("{ [ "HOOK_SECRET_NAME", "HOOK_SECRET_NAME" ] }") req, _ := http.NewRequest("DELETE", url, payload) @@ -81,12 +88,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.delete("https://{yourDomain}/api/v2/hooks/HOOK_ID/secrets") +} +``` +```java Java +HttpResponse response = Unirest.delete("https://{yourDomain}/api/v2/hooks/HOOK_ID/secrets") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") - .body("{ [ \"HOOK_SECRET_NAME\", \"HOOK_SECRET_NAME\" ] }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ [ "HOOK_SECRET_NAME", "HOOK_SECRET_NAME" ] }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'DELETE', @@ -99,8 +110,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN" }; @@ -123,8 +136,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/hooks/HOOK_ID/secrets", @@ -134,7 +149,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "DELETE", - CURLOPT_POSTFIELDS => "{ [ \"HOOK_SECRET_NAME\", \"HOOK_SECRET_NAME\" ] }", + CURLOPT_POSTFIELDS => "{ [ "HOOK_SECRET_NAME", "HOOK_SECRET_NAME" ] }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN" ], @@ -149,12 +164,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ [ \"HOOK_SECRET_NAME\", \"HOOK_SECRET_NAME\" ] }" +payload = "{ [ "HOOK_SECRET_NAME", "HOOK_SECRET_NAME" ] }" headers = { 'authorization': "Bearer MGMT_API_ACCESS_TOKEN" } @@ -163,8 +180,10 @@ conn.request("DELETE", "/{yourDomain}/api/v2/hooks/HOOK_ID/secrets", payload, he res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -176,11 +195,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Delete.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' -request.body = "{ [ \"HOOK_SECRET_NAME\", \"HOOK_SECRET_NAME\" ] }" +request.body = "{ [ "HOOK_SECRET_NAME", "HOOK_SECRET_NAME" ] }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer MGMT_API_ACCESS_TOKEN"] @@ -203,20 +224,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
    diff --git a/main/docs/ja-jp/customize/hooks/hook-secrets/update-hook-secrets.mdx b/main/docs/ja-jp/customize/hooks/hook-secrets/update-hook-secrets.mdx index a3ea0abf4..dea869cb3 100644 --- a/main/docs/ja-jp/customize/hooks/hook-secrets/update-hook-secrets.mdx +++ b/main/docs/ja-jp/customize/hooks/hook-secrets/update-hook-secrets.mdx @@ -10,6 +10,7 @@ permalink: "update-hook-secrets" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; @@ -46,20 +47,26 @@ Hook Secretsは、Deploy コマンドラインインターフェイス(CLI) `PATCH`呼び出しをして、[Hook Secretsエンドポイントを更新](/docs/ja-jp/api/management/v2/#!/Hooks/patch_secrets)します。`HOOK_ID`と`MGMT_API_ACCESS_TOKEN`プレースホルダー値をフックIDとManagement APIアクセストークンに必ず置き換えてください。 -export const codeExample1 = `curl --request PATCH \ + +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/hooks/HOOK_ID/secrets' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{ [ "HOOK_SECRET_KEY", "HOOK_SECRET_VALUE" ], [ "HOOK_SECRET_KEY", "HOOK_SECRET_VALUE" ] }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/hooks/HOOK_ID/secrets"); + --data '{ [ "HOOK_SECRET_KEY", "HOOK_SECRET_VALUE" ], [ "HOOK_SECRET_KEY", "HOOK_SECRET_VALUE" ] }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/hooks/HOOK_ID/secrets"); var request = new RestRequest(Method.PATCH); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{ [ \"HOOK_SECRET_KEY\", \"HOOK_SECRET_VALUE\" ], [ \"HOOK_SECRET_KEY\", \"HOOK_SECRET_VALUE\" ] }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ [ "HOOK_SECRET_KEY", "HOOK_SECRET_VALUE" ], [ "HOOK_SECRET_KEY", "HOOK_SECRET_VALUE" ] }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -72,7 +79,7 @@ func main() { url := "https://{yourDomain}/api/v2/hooks/HOOK_ID/secrets" - payload := strings.NewReader("{ [ \"HOOK_SECRET_KEY\", \"HOOK_SECRET_VALUE\" ], [ \"HOOK_SECRET_KEY\", \"HOOK_SECRET_VALUE\" ] }") + payload := strings.NewReader("{ [ "HOOK_SECRET_KEY", "HOOK_SECRET_VALUE" ], [ "HOOK_SECRET_KEY", "HOOK_SECRET_VALUE" ] }") req, _ := http.NewRequest("PATCH", url, payload) @@ -88,14 +95,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/hooks/HOOK_ID/secrets") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/hooks/HOOK_ID/secrets") .header("content-type", "application/json") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ [ \"HOOK_SECRET_KEY\", \"HOOK_SECRET_VALUE\" ], [ \"HOOK_SECRET_KEY\", \"HOOK_SECRET_VALUE\" ] }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ [ "HOOK_SECRET_KEY", "HOOK_SECRET_VALUE" ], [ "HOOK_SECRET_KEY", "HOOK_SECRET_VALUE" ] }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -112,8 +123,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @@ -138,8 +151,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/hooks/HOOK_ID/secrets", @@ -149,7 +164,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{ [ \"HOOK_SECRET_KEY\", \"HOOK_SECRET_VALUE\" ], [ \"HOOK_SECRET_KEY\", \"HOOK_SECRET_VALUE\" ] }", + CURLOPT_POSTFIELDS => "{ [ "HOOK_SECRET_KEY", "HOOK_SECRET_VALUE" ], [ "HOOK_SECRET_KEY", "HOOK_SECRET_VALUE" ] }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "cache-control: no-cache", @@ -166,12 +181,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ [ \"HOOK_SECRET_KEY\", \"HOOK_SECRET_VALUE\" ], [ \"HOOK_SECRET_KEY\", \"HOOK_SECRET_VALUE\" ] }" +payload = "{ [ "HOOK_SECRET_KEY", "HOOK_SECRET_VALUE" ], [ "HOOK_SECRET_KEY", "HOOK_SECRET_VALUE" ] }" headers = { 'content-type': "application/json", @@ -184,8 +201,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/hooks/HOOK_ID/secrets", payload, hea res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -199,11 +218,13 @@ request = Net::HTTP::Patch.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ [ \"HOOK_SECRET_KEY\", \"HOOK_SECRET_VALUE\" ], [ \"HOOK_SECRET_KEY\", \"HOOK_SECRET_VALUE\" ] }" +request.body = "{ [ "HOOK_SECRET_KEY", "HOOK_SECRET_VALUE" ], [ "HOOK_SECRET_KEY", "HOOK_SECRET_VALUE" ] }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -230,20 +251,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
    diff --git a/main/docs/ja-jp/customize/hooks/hook-secrets/view-hook-secrets.mdx b/main/docs/ja-jp/customize/hooks/hook-secrets/view-hook-secrets.mdx index 523495139..859863a48 100644 --- a/main/docs/ja-jp/customize/hooks/hook-secrets/view-hook-secrets.mdx +++ b/main/docs/ja-jp/customize/hooks/hook-secrets/view-hook-secrets.mdx @@ -10,6 +10,7 @@ permalink: "view-hook-secrets" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; @@ -44,14 +45,20 @@ Dashboardを使用してフックに構成済みのフックシークレット `GET`呼び出しを[フックシークレット取得エンドポイント](/docs/ja-jp/api/management/v2/#!/Hooks/get_secrets)に対して行います。`HOOK_ID`と`MGMT_API_ACCESS_TOKEN`のプレースホルダーの値を、それぞれフックのIDとManagement APIのアクセストークンに置き換えてください。 -export const codeExample1 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/hooks/HOOK_ID/secrets' \ - --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/hooks/HOOK_ID/secrets"); + --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/hooks/HOOK_ID/secrets"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -75,11 +82,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/hooks/HOOK_ID/secrets") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/hooks/HOOK_ID/secrets") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -91,8 +102,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN" }; @@ -112,8 +125,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/hooks/HOOK_ID/secrets", @@ -137,8 +152,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -149,8 +166,10 @@ conn.request("GET", "/{yourDomain}/api/v2/hooks/HOOK_ID/secrets", headers=header res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -164,8 +183,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer MGMT_API_ACCESS_TOKEN"] @@ -185,20 +206,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
    diff --git a/main/docs/ja-jp/customize/hooks/update-hooks.mdx b/main/docs/ja-jp/customize/hooks/update-hooks.mdx index 70703be58..bccc387ad 100644 --- a/main/docs/ja-jp/customize/hooks/update-hooks.mdx +++ b/main/docs/ja-jp/customize/hooks/update-hooks.mdx @@ -10,6 +10,7 @@ permalink: "update-hooks" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; @@ -63,20 +64,26 @@ Hooksは、Dashboardまたは response = Unirest.patch("https://{yourDomain}/api/v2/hooks/HOOK_ID") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/hooks/HOOK_ID") .header("content-type", "application/json") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ \"name\": \"HOOK_NAME\", \"script\": \"HOOK_SCRIPT\", \"enabled\": \"true\" }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "name": "HOOK_NAME", "script": "HOOK_SCRIPT", "enabled": "true" }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -129,8 +140,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @@ -158,8 +171,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/hooks/HOOK_ID", @@ -169,7 +184,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{ \"name\": \"HOOK_NAME\", \"script\": \"HOOK_SCRIPT\", \"enabled\": \"true\" }", + CURLOPT_POSTFIELDS => "{ "name": "HOOK_NAME", "script": "HOOK_SCRIPT", "enabled": "true" }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "cache-control: no-cache", @@ -186,12 +201,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"name\": \"HOOK_NAME\", \"script\": \"HOOK_SCRIPT\", \"enabled\": \"true\" }" +payload = "{ "name": "HOOK_NAME", "script": "HOOK_SCRIPT", "enabled": "true" }" headers = { 'content-type': "application/json", @@ -204,8 +221,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/hooks/HOOK_ID", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -219,11 +238,13 @@ request = Net::HTTP::Patch.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ \"name\": \"HOOK_NAME\", \"script\": \"HOOK_SCRIPT\", \"enabled\": \"true\" }" +request.body = "{ "name": "HOOK_NAME", "script": "HOOK_SCRIPT", "enabled": "true" }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -255,20 +276,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
    diff --git a/main/docs/ja-jp/customize/hooks/view-hooks.mdx b/main/docs/ja-jp/customize/hooks/view-hooks.mdx index 113597087..8eaf3bef9 100644 --- a/main/docs/ja-jp/customize/hooks/view-hooks.mdx +++ b/main/docs/ja-jp/customize/hooks/view-hooks.mdx @@ -10,6 +10,7 @@ permalink: "view-hooks" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; @@ -43,14 +44,20 @@ RulesからActionsへの移行方法については、「[RulesからActionsに [フック取得エンドポイント](/docs/ja-jp/api/management/v2/#!/Hooks/get_hooks)に`GET`呼び出しを行います。`MGMT_API_ACCESS_TOKEN`プレースホルダーの値をManagement APIのアクセストークンで置き換えてください。 -export const codeExample1 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/hooks' \ - --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/hooks"); + --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/hooks"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -74,11 +81,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/hooks") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/hooks") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -90,8 +101,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN" }; @@ -111,8 +124,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/hooks", @@ -136,8 +151,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -148,8 +165,10 @@ conn.request("GET", "/{yourDomain}/api/v2/hooks", headers=headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -163,8 +182,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer MGMT_API_ACCESS_TOKEN"] @@ -184,20 +205,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
    diff --git a/main/docs/ja-jp/customize/integrations/aws/aws-api-gateway-custom-authorizers.mdx b/main/docs/ja-jp/customize/integrations/aws/aws-api-gateway-custom-authorizers.mdx index a84913dc8..2599a42a3 100644 --- a/main/docs/ja-jp/customize/integrations/aws/aws-api-gateway-custom-authorizers.mdx +++ b/main/docs/ja-jp/customize/integrations/aws/aws-api-gateway-custom-authorizers.mdx @@ -11,6 +11,8 @@ permalink: "aws-api-gateway-custom-authorizers" import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + AWS Lambda関数(カスタムオーソライザーを含む)を作成・構成してAPIエンドポイントを保護し、認可フローを実装します。これにより、ユーザーはAuth0からAPIへのアクセス取得に必要なアクセストークンを取得できるようになります。 詳細は、[AWS API Gateway](https://aws.amazon.com/api-gateway/)にログインして、「[AWS Lambdaの概要](https://aws.amazon.com/lambda/)」をご覧ください。 @@ -523,7 +525,7 @@ APIのエンドポイントを保護する方法については、Amazon API Gat 詳細は、「[アクセストークンを取得する](/docs/ja-jp/secure/tokens/access-tokens/get-access-tokens)」でご覧ください。 - + ```bash cURL lines curl --request GET \ --url https://%7ByourInvokeUrl%7D/pets @@ -642,5 +644,5 @@ print(httpResponse) }) dataTask.resume() ``` - + diff --git a/main/docs/ja-jp/customize/integrations/google-cloud-endpoints.mdx b/main/docs/ja-jp/customize/integrations/google-cloud-endpoints.mdx index 41b5998d1..1d9620364 100644 --- a/main/docs/ja-jp/customize/integrations/google-cloud-endpoints.mdx +++ b/main/docs/ja-jp/customize/integrations/google-cloud-endpoints.mdx @@ -11,6 +11,8 @@ permalink: "google-cloud-endpoints" import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + [Google Cloud Endpoints(GCE)](https://cloud.google.com/endpoints/)は、APIの作成、維持、およびセキュリティ保護などの機能を提供するAPI管理システムです。GCEは[OpenAPI](https://www.openapis.org/)を使用して、APIのエンドポイント、入出力、エラー、およびセキュリティ記述を定義します。 OpenAPI仕様の詳細については、GitHubの[OpenAPI Specification(OpenAPIの仕様)](https://github.com/OAI/OpenAPI-Specification)リポジトリを参照してください。 @@ -23,7 +25,7 @@ OpenAPI仕様の詳細については、GitHubの[OpenAPI Specification(OpenAP このクイックスタートでは、3文字の[IATAコード](https://en.wikipedia.org/wiki/IATA_airport_code)から空港名を返す`/airportName`という単一のエンドポイントを持つ簡単なGCE APIを作成する手順を説明しています。 - + ```bash cURL lines curl --request GET \ --url 'https://%7ByourGceProject%7D.appspot.com/airportName?iataCode=SFO' @@ -173,7 +175,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + ## Auth0でAPIを定義する @@ -324,7 +326,7 @@ cd endpoints-quickstart/scripts 再デプロイが完了したら、セキュリティなしでAPIを再度呼び出します。 - + ```bash cURL lines curl --request GET \ --url 'https://%7ByourGceProject%7D.appspot.com/airportName?iataCode=SFO' @@ -474,7 +476,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + 以下のような応答が返されます。 @@ -498,7 +500,7 @@ dataTask.resume() Authorization Header(認可ヘッダー)に`Bearer {ACCESS_TOKEN}`を設定し、APIに対して`GET`要求を実行することで、認可されたアクセスを取得します。 - + ```bash cURL lines curl --request GET \ --url 'https://%7ByourGceProject%7D.appspot.com/airportName?iataCode=SFO' \ @@ -666,6 +668,6 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + これで作業完了です。 \ No newline at end of file diff --git a/main/docs/ja-jp/customize/integrations/marketing-tool-integrations/marketo.mdx b/main/docs/ja-jp/customize/integrations/marketing-tool-integrations/marketo.mdx index 1615cbd07..6ce3e99ef 100644 --- a/main/docs/ja-jp/customize/integrations/marketing-tool-integrations/marketo.mdx +++ b/main/docs/ja-jp/customize/integrations/marketing-tool-integrations/marketo.mdx @@ -9,6 +9,9 @@ permalink: "marketo" 'twitter:description': "Auth0のユーザーデータのエクスポートとMarketoへのインポート方法について説明します。" --- + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + この記事では、Auth0のユーザーデータをCSVファイルにエクスポートし、Market REST APIの[一括リードエンドポイント](http://developers.marketo.com/rest-api/endpoint-reference/lead-database-endpoint-reference/#/Bulk_Leads)を使用してMarketoにインポートする方法について説明します。 ## ユーザーデータファイルを作成する @@ -53,7 +56,7 @@ Dashboardの[[Extensions(拡張機能)]](https://manage.auth0.com/#/exte ユーザーデータファイルをMarketoにインポートするには、[一括リードエンドポイント](http://developers.marketo.com/rest-api/endpoint-reference/lead-database-endpoint-reference/#/Bulk_Leads)に対してPOST要求を実行します。要求のcontent-typeヘッダーを`multipart/form-data`に設定し、エクスポートしたCSVファイルを含む`file`パラメーターと、formatパラメーターを`csv`に設定します。例: - + ```bash cURL lines curl --request POST \ --url https://marketo_rest_api_base_url/bulk/v1/leads.json \ @@ -305,7 +308,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + 応答はこのようになっているはずです。 @@ -322,7 +325,7 @@ dataTask.resume() インポートのステータスは、[Get Import Lead Status API](/docs/ja-jp/)とインポートジョブの`batchId`を使用して確認できます。例: - + ```bash cURL lines curl --request GET \ --url https://marketo_rest_api_base_url/bulk/v1/leads/batch/BATCH_ID.json \ @@ -489,7 +492,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + 応答は次のようになります。 diff --git a/main/docs/ja-jp/customize/internationalization-and-localization/universal-login-internationalization.mdx b/main/docs/ja-jp/customize/internationalization-and-localization/universal-login-internationalization.mdx index 3ed2f1bc1..ac2245384 100644 --- a/main/docs/ja-jp/customize/internationalization-and-localization/universal-login-internationalization.mdx +++ b/main/docs/ja-jp/customize/internationalization-and-localization/universal-login-internationalization.mdx @@ -10,6 +10,7 @@ permalink: "universal-login-internationalization" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; ## ユニバーサルログインのローカライズ @@ -340,18 +341,24 @@ import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; Management APIを使用して、[Update Tenant Settingsエンドポイント](/docs/ja-jp/api/management/v2#!/Tenants/patch_settings)からテナントの有効な言語を指定することもできます。リストの最初の言語がデフォルトの言語になります。 -export const codeExample1 = `curl --request PATCH \ + +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/tenants/settings' \ --header 'authorization: Bearer API2_ACCESS_TOKEN' \ --header 'content-type: application/json' \ - --data '{ "enabled_locales" : [ "en", "es"]}'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/tenants/settings"); + --data '{ "enabled_locales" : [ "en", "es"]}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/tenants/settings"); var request = new RestRequest(Method.PATCH); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer API2_ACCESS_TOKEN"); -request.AddParameter("application/json", "{ \"enabled_locales\" : [ \"en\", \"es\"]}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "enabled_locales" : [ "en", "es"]}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -364,7 +371,7 @@ func main() { url := "https://{yourDomain}/api/v2/tenants/settings" - payload := strings.NewReader("{ \"enabled_locales\" : [ \"en\", \"es\"]}") + payload := strings.NewReader("{ "enabled_locales" : [ "en", "es"]}") req, _ := http.NewRequest("PATCH", url, payload) @@ -379,13 +386,17 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/tenants/settings") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/tenants/settings") .header("content-type", "application/json") .header("authorization", "Bearer API2_ACCESS_TOKEN") - .body("{ \"enabled_locales\" : [ \"en\", \"es\"]}") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "enabled_locales" : [ "en", "es"]}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -398,8 +409,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer API2_ACCESS_TOKEN" }; @@ -424,8 +437,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/tenants/settings", @@ -435,7 +450,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{ \"enabled_locales\" : [ \"en\", \"es\"]}", + CURLOPT_POSTFIELDS => "{ "enabled_locales" : [ "en", "es"]}", CURLOPT_HTTPHEADER => [ "authorization: Bearer API2_ACCESS_TOKEN", "content-type: application/json" @@ -451,12 +466,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"enabled_locales\" : [ \"en\", \"es\"]}" +payload = "{ "enabled_locales" : [ "en", "es"]}" headers = { 'content-type': "application/json", @@ -468,8 +485,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/tenants/settings", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -482,11 +501,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Patch.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer API2_ACCESS_TOKEN' -request.body = "{ \"enabled_locales\" : [ \"en\", \"es\"]}" +request.body = "{ "enabled_locales" : [ "en", "es"]}" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -513,20 +534,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ### 制限事項 diff --git a/main/docs/ja-jp/customize/login-pages/custom-error-pages.mdx b/main/docs/ja-jp/customize/login-pages/custom-error-pages.mdx index 76892f5e7..55a1c71c1 100644 --- a/main/docs/ja-jp/customize/login-pages/custom-error-pages.mdx +++ b/main/docs/ja-jp/customize/login-pages/custom-error-pages.mdx @@ -10,6 +10,7 @@ permalink: "custom-error-pages" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; 認可エラーが発生し、コールバックURLが有効な場合、認可サーバーは適切なエラーパラメーターと状態パラメーターをコールバックURLに返します。コールバックURLが無効な場合、アプリケーションは[デフォルトのAuth0エラーページ](/docs/ja-jp/authenticate/login/auth0-universal-login/error-pages)を表示します。 @@ -79,18 +80,24 @@ Dashboardを使用して、ユーザーをカスタムエラーページにリ Management APIの[テナント設定更新](/docs/ja-jp/api/management/v2/#!/Tenants/patch_settings)エンドポイントを使用します。`{mgmtApiAccessToken}`プレースホルダー値をManagement APIのアクセストークンに置き換え、JSON本文の`url`フィールドの値をエラーページの場所をポイントするように更新します。 -export const codeExample1 = `curl --request PATCH \ + +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/tenants/settings' \ --header 'authorization: Bearer {mgmtApiAccessToken}' \ --header 'content-type: application/json' \ - --data '{"error_page": {"html": "", "show_log_link":false, "url": "http://www.example.com"}}'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/tenants/settings"); + --data '{"error_page": {"html": "", "show_log_link":false, "url": "http://www.example.com"}}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/tenants/settings"); var request = new RestRequest(Method.PATCH); request.AddHeader("authorization", "Bearer {mgmtApiAccessToken}"); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\"error_page\": {\"html\": \"\", \"show_log_link\":false, \"url\": \"http://www.example.com\"}}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{"error_page": {"html": "", "show_log_link":false, "url": "http://www.example.com"}}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -103,7 +110,7 @@ func main() { url := "https://{yourDomain}/api/v2/tenants/settings" - payload := strings.NewReader("{\"error_page\": {\"html\": \"\", \"show_log_link\":false, \"url\": \"http://www.example.com\"}}") + payload := strings.NewReader("{"error_page": {"html": "", "show_log_link":false, "url": "http://www.example.com"}}") req, _ := http.NewRequest("PATCH", url, payload) @@ -118,13 +125,17 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/tenants/settings") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/tenants/settings") .header("authorization", "Bearer {mgmtApiAccessToken}") .header("content-type", "application/json") - .body("{\"error_page\": {\"html\": \"\", \"show_log_link\":false, \"url\": \"http://www.example.com\"}}") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{"error_page": {"html": "", "show_log_link":false, "url": "http://www.example.com"}}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -140,8 +151,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer {mgmtApiAccessToken}", @"content-type": @"application/json" }; @@ -166,8 +179,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/tenants/settings", @@ -177,7 +192,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{\"error_page\": {\"html\": \"\", \"show_log_link\":false, \"url\": \"http://www.example.com\"}}", + CURLOPT_POSTFIELDS => "{"error_page": {"html": "", "show_log_link":false, "url": "http://www.example.com"}}", CURLOPT_HTTPHEADER => [ "authorization: Bearer {mgmtApiAccessToken}", "content-type: application/json" @@ -193,12 +208,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"error_page\": {\"html\": \"\", \"show_log_link\":false, \"url\": \"http://www.example.com\"}}" +payload = "{"error_page": {"html": "", "show_log_link":false, "url": "http://www.example.com"}}" headers = { 'authorization': "Bearer {mgmtApiAccessToken}", @@ -210,8 +227,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/tenants/settings", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -224,11 +243,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Patch.new(url) request["authorization"] = 'Bearer {mgmtApiAccessToken}' request["content-type"] = 'application/json' -request.body = "{\"error_page\": {\"html\": \"\", \"show_log_link\":false, \"url\": \"http://www.example.com\"}}" +request.body = "{"error_page": {"html": "", "show_log_link":false, "url": "http://www.example.com"}}" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "authorization": "Bearer {mgmtApiAccessToken}", @@ -259,20 +280,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
    @@ -315,7 +325,7 @@ Liquid構文を使用して、次の変数を含めることができます。 * `{error_description}` * `{tracking}` - + ```bash cURL lines curl --request PATCH \ --url https://login.auth0.com/api/v2/tenants/settings \ @@ -531,7 +541,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - +
    diff --git a/main/docs/ja-jp/customize/login-pages/customize-consent-prompts.mdx b/main/docs/ja-jp/customize/login-pages/customize-consent-prompts.mdx index 701840207..953491c83 100644 --- a/main/docs/ja-jp/customize/login-pages/customize-consent-prompts.mdx +++ b/main/docs/ja-jp/customize/login-pages/customize-consent-prompts.mdx @@ -10,6 +10,7 @@ permalink: "customize-consent-prompts" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; サードパーティーアプリケーションがスコープを要求するとき、ユーザーには同意プロンプトが表示されます。デフォルトでは、このプロンプトはスコープの**名前** を使用してテキストを生成し、リソースのアクションを1行に表示してリソースのすべてのスコープをグループ化します。 @@ -30,20 +31,26 @@ import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; 以下のAPI呼び出しを行って、テナントの**[use_scope_descriptions_for_consent]** フラグを`true`に設定します。 -export const codeExample1 = `curl --request PATCH \ + +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/tenants/settings' \ --header 'authorization: Bearer API_ACCESS_TOKEN' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{ "flags": { "use_scope_descriptions_for_consent": true } }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/tenants/settings"); + --data '{ "flags": { "use_scope_descriptions_for_consent": true } }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/tenants/settings"); var request = new RestRequest(Method.PATCH); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer API_ACCESS_TOKEN"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{ \"flags\": { \"use_scope_descriptions_for_consent\": true } }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "flags": { "use_scope_descriptions_for_consent": true } }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -56,7 +63,7 @@ func main() { url := "https://{yourDomain}/api/v2/tenants/settings" - payload := strings.NewReader("{ \"flags\": { \"use_scope_descriptions_for_consent\": true } }") + payload := strings.NewReader("{ "flags": { "use_scope_descriptions_for_consent": true } }") req, _ := http.NewRequest("PATCH", url, payload) @@ -72,14 +79,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/tenants/settings") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/tenants/settings") .header("content-type", "application/json") .header("authorization", "Bearer API_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ \"flags\": { \"use_scope_descriptions_for_consent\": true } }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "flags": { "use_scope_descriptions_for_consent": true } }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -96,8 +107,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer API_ACCESS_TOKEN", @@ -123,8 +136,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/tenants/settings", @@ -134,7 +149,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{ \"flags\": { \"use_scope_descriptions_for_consent\": true } }", + CURLOPT_POSTFIELDS => "{ "flags": { "use_scope_descriptions_for_consent": true } }", CURLOPT_HTTPHEADER => [ "authorization: Bearer API_ACCESS_TOKEN", "cache-control: no-cache", @@ -151,12 +166,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"flags\": { \"use_scope_descriptions_for_consent\": true } }" +payload = "{ "flags": { "use_scope_descriptions_for_consent": true } }" headers = { 'content-type': "application/json", @@ -169,8 +186,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/tenants/settings", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -184,11 +203,13 @@ request = Net::HTTP::Patch.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer API_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ \"flags\": { \"use_scope_descriptions_for_consent\": true } }" +request.body = "{ "flags": { "use_scope_descriptions_for_consent": true } }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -216,39 +237,34 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ## スコープの名前を使って同意プロンプトのテキストを生成する 以下のAPI呼び出しを行って、テナントの**[use_scope_descriptions_for_consent]** フラグを`false`に設定します。 -export const codeExample11 = `curl --request PATCH \ + +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/tenants/settings' \ --header 'authorization: Bearer API_ACCESS_TOKEN' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{ "flags": { "use_scope_descriptions_for_consent": false } }'`; -export const codeExample12 = `var client = new RestClient("https://{yourDomain}/api/v2/tenants/settings"); + --data '{ "flags": { "use_scope_descriptions_for_consent": false } }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/tenants/settings"); var request = new RestRequest(Method.PATCH); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer API_ACCESS_TOKEN"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{ \"flags\": { \"use_scope_descriptions_for_consent\": false } }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample13 = `package main +request.AddParameter("application/json", "{ "flags": { "use_scope_descriptions_for_consent": false } }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -261,7 +277,7 @@ func main() { url := "https://{yourDomain}/api/v2/tenants/settings" - payload := strings.NewReader("{ \"flags\": { \"use_scope_descriptions_for_consent\": false } }") + payload := strings.NewReader("{ "flags": { "use_scope_descriptions_for_consent": false } }") req, _ := http.NewRequest("PATCH", url, payload) @@ -277,14 +293,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample14 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/tenants/settings") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/tenants/settings") .header("content-type", "application/json") .header("authorization", "Bearer API_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ \"flags\": { \"use_scope_descriptions_for_consent\": false } }") - .asString();`; -export const codeExample15 = `var axios = require("axios").default; + .body("{ "flags": { "use_scope_descriptions_for_consent": false } }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -301,8 +321,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample16 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer API_ACCESS_TOKEN", @@ -328,8 +350,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/tenants/settings", @@ -339,7 +363,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{ \"flags\": { \"use_scope_descriptions_for_consent\": false } }", + CURLOPT_POSTFIELDS => "{ "flags": { "use_scope_descriptions_for_consent": false } }", CURLOPT_HTTPHEADER => [ "authorization: Bearer API_ACCESS_TOKEN", "cache-control: no-cache", @@ -356,12 +380,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"flags\": { \"use_scope_descriptions_for_consent\": false } }" +payload = "{ "flags": { "use_scope_descriptions_for_consent": false } }" headers = { 'content-type': "application/json", @@ -374,8 +400,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/tenants/settings", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -389,11 +417,13 @@ request = Net::HTTP::Patch.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer API_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ \"flags\": { \"use_scope_descriptions_for_consent\": false } }" +request.body = "{ "flags": { "use_scope_descriptions_for_consent": false } }" response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -421,20 +451,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ## もっと詳しく diff --git a/main/docs/ja-jp/customize/login-pages/universal-login/customize-signup-and-login-prompts/connection-switching.mdx b/main/docs/ja-jp/customize/login-pages/universal-login/customize-signup-and-login-prompts/connection-switching.mdx index c60008e03..d40cca3ef 100644 --- a/main/docs/ja-jp/customize/login-pages/universal-login/customize-signup-and-login-prompts/connection-switching.mdx +++ b/main/docs/ja-jp/customize/login-pages/universal-login/customize-signup-and-login-prompts/connection-switching.mdx @@ -10,6 +10,7 @@ permalink: "connection-switching" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Flexible connection switching is an optional feature that allows users to choose their method of authentication when logging in to an application. When implemented, your application's login screen presents users with the option to authenticate with either traditional database credentials or a passwordless connection. Users who select a [passwordless connection](/docs/ja-jp/authenticate/passwordless) receive a one-time password (OTP) through email or SMS that they can use to log in to your application. @@ -69,18 +70,24 @@ In the code samples below, ensure you replace the placeholders with the appropri You can configure the `signup-password` prompt using the [Set partials for a prompt](/docs/api/management/v2/prompts/put-partials) endpoint: -export const codeExample1 = `curl --request PUT \ + +```bash cURL +curl --request PUT \ --url 'https://{yourDomain}/api/v2/prompts/signup-password/partials' \ --header 'authorization: Bearer {mgmtApiToken}' \ --header 'content-type: application/json' \ ---data '{"signup-password":{"form-footer-start":" Send a secure code by email "}}'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/prompts/signup-password/partials"); +--data '{"signup-password":{"form-footer-start":" Send a secure code by email "}}' +``` lines +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/prompts/signup-password/partials"); var request = new RestRequest(Method.PUT); request.AddHeader("authorization", "Bearer {mgmtApiToken}"); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\"signup-password\":{\"form-footer-start\":\" Send a secure code by email \"}}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{"signup-password":{"form-footer-start":" Send a secure code by email "}}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" "strings" @@ -89,7 +96,7 @@ import ( ) func main() { url := "https://{yourDomain}/api/v2/prompts/signup-password/partials" -payload := strings.NewReader("{\"signup-password\":{\"form-footer-start\":\" Send a secure code by email \"}}") +payload := strings.NewReader("{"signup-password":{"form-footer-start":" Send a secure code by email "}}") req, _ := http.NewRequest("PUT", url, payload) req.Header.Add("authorization", "Bearer {mgmtApiToken}") req.Header.Add("content-type", "application/json") @@ -98,13 +105,17 @@ defer res.Body.Close() body, _ := ioutil.ReadAll(res.Body) fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.put("https://{yourDomain}/api/v2/prompts/signup-password/partials") +} +``` lines +```java Java +HttpResponse response = Unirest.put("https://{yourDomain}/api/v2/prompts/signup-password/partials") .header("authorization", "Bearer {mgmtApiToken}") .header("content-type", "application/json") -.body("{\"signup-password\":{\"form-footer-start\":\" Send a secure code by email \"}}") -.asString();`; -export const codeExample5 = `var axios = require("axios").default; +.body("{"signup-password":{"form-footer-start":" Send a secure code by email "}}") +.asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PUT', url: 'https://{yourDomain}/api/v2/prompts/signup-password/partials', @@ -119,8 +130,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` lines +```obj-c Obj-C +#import NSDictionary \*headers = @{ @"authorization": @"Bearer {mgmtApiToken}", @"content-type": @"application/json" }; NSDictionary \*parameters = @{ @"signup-password": @{ @"form-footer-start": @" Send a secure code by email " } }; @@ -141,8 +154,10 @@ NSHTTPURLResponse \*httpResponse = (NSHTTPURLResponse \*) response; NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/prompts/signup-password/partials", CURLOPT_RETURNTRANSFER => true, @@ -151,7 +166,7 @@ CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PUT", -CURLOPT_POSTFIELDS => "{\"signup-password\":{\"form-footer-start\":\" Send a secure code by email \"}}", +CURLOPT_POSTFIELDS => "{"signup-password":{"form-footer-start":" Send a secure code by email "}}", CURLOPT_HTTPHEADER => [ "authorization: Bearer {mgmtApiToken}", "content-type: application/json" @@ -164,10 +179,12 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` lines +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"signup-password\":{\"form-footer-start\":\" Send a secure code by email \"}}" +payload = "{"signup-password":{"form-footer-start":" Send a secure code by email "}}" headers = { 'authorization': "Bearer {mgmtApiToken}", 'content-type': "application/json" @@ -175,8 +192,10 @@ headers = { conn.request("PUT", "/{yourDomain}/api/v2/prompts/signup-password/partials", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' url = URI("https://{yourDomain}/api/v2/prompts/signup-password/partials") @@ -186,10 +205,12 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Put.new(url) request["authorization"] = 'Bearer {mgmtApiToken}' request["content-type"] = 'application/json' -request.body = "{\"signup-password\":{\"form-footer-start\":\" Send a secure code by email \"}}" +request.body = "{"signup-password":{"form-footer-start":" Send a secure code by email "}}" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` lines +```swift Swift +import Foundation let headers = [ "authorization": "Bearer {mgmtApiToken}", "content-type": "application/json" @@ -211,20 +232,9 @@ let httpResponse = response as? HTTPURLResponse print(httpResponse) } }) -dataTask.resume()`; - - - lines - - lines - - lines - - lines - - lines - - +dataTask.resume() +``` + As a result, a **Send a secure code by email button** is added to the `signup-password` screen. When a user selects this button, it submits a form body containing the login state parameter and the name of the desired connection. @@ -234,18 +244,24 @@ For best results, configuring the login prompt for both password and passwordles You can configure the `login-password` prompt using the [Set partials for a prompt](/docs/api/management/v2/prompts/put-partials) endpoint: -export const codeExample11 = `curl --request PUT \ + +```bash cURL +curl --request PUT \ --url 'https://{yourDomain}/api/v2/prompts/login-password/partials' \ --header 'authorization: Bearer {mgmtApiToken}' \ --header 'content-type: application/json' \ ---data '{"login-password":{"form-footer-start":" Send a secure code by email "}}'`; -export const codeExample12 = `var client = new RestClient("https://{yourDomain}/api/v2/prompts/login-password/partials"); +--data '{"login-password":{"form-footer-start":" Send a secure code by email "}}' +``` lines +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/prompts/login-password/partials"); var request = new RestRequest(Method.PUT); request.AddHeader("authorization", "Bearer {mgmtApiToken}"); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\"login-password\":{\"form-footer-start\":\" Send a secure code by email \"}}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample13 = `package main +request.AddParameter("application/json", "{"login-password":{"form-footer-start":" Send a secure code by email "}}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" "strings" @@ -254,7 +270,7 @@ import ( ) func main() { url := "https://{yourDomain}/api/v2/prompts/login-password/partials" -payload := strings.NewReader("{\"login-password\":{\"form-footer-start\":\" Send a secure code by email \"}}") +payload := strings.NewReader("{"login-password":{"form-footer-start":" Send a secure code by email "}}") req, _ := http.NewRequest("PUT", url, payload) req.Header.Add("authorization", "Bearer {mgmtApiToken}") req.Header.Add("content-type", "application/json") @@ -263,13 +279,17 @@ defer res.Body.Close() body, _ := ioutil.ReadAll(res.Body) fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample14 = `HttpResponse response = Unirest.put("https://{yourDomain}/api/v2/prompts/login-password/partials") +} +``` lines +```java Java +HttpResponse response = Unirest.put("https://{yourDomain}/api/v2/prompts/login-password/partials") .header("authorization", "Bearer {mgmtApiToken}") .header("content-type", "application/json") -.body("{\"login-password\":{\"form-footer-start\":\" Send a secure code by email \"}}") -.asString();`; -export const codeExample15 = `var axios = require("axios").default; +.body("{"login-password":{"form-footer-start":" Send a secure code by email "}}") +.asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PUT', url: 'https://{yourDomain}/api/v2/prompts/login-password/partials', @@ -284,8 +304,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample16 = `#import +}); +``` lines +```obj-c Obj-C +#import NSDictionary \*headers = @{ @"authorization": @"Bearer {mgmtApiToken}", @"content-type": @"application/json" }; NSDictionary \*parameters = @{ @"login-password": @{ @"form-footer-start": @" Send a secure code by email " } }; @@ -306,8 +328,10 @@ NSHTTPURLResponse \*httpResponse = (NSHTTPURLResponse \*) response; NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/prompts/login-password/partials", CURLOPT_RETURNTRANSFER => true, @@ -316,7 +340,7 @@ CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PUT", -CURLOPT_POSTFIELDS => "{\"login-password\":{\"form-footer-start\":\" Send a secure code by email \"}}", +CURLOPT_POSTFIELDS => "{"login-password":{"form-footer-start":" Send a secure code by email "}}", CURLOPT_HTTPHEADER => [ "authorization: Bearer {mgmtApiToken}", "content-type: application/json" @@ -329,10 +353,12 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `import http.client +} +``` lines +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"login-password\":{\"form-footer-start\":\" Send a secure code by email \"}}" +payload = "{"login-password":{"form-footer-start":" Send a secure code by email "}}" headers = { 'authorization': "Bearer {mgmtApiToken}", 'content-type': "application/json" @@ -340,8 +366,10 @@ headers = { conn.request("PUT", "/{yourDomain}/api/v2/prompts/login-password/partials", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' url = URI("https://{yourDomain}/api/v2/prompts/login-password/partials") @@ -351,10 +379,12 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Put.new(url) request["authorization"] = 'Bearer {mgmtApiToken}' request["content-type"] = 'application/json' -request.body = "{\"login-password\":{\"form-footer-start\":\" Send a secure code by email \"}}" +request.body = "{"login-password":{"form-footer-start":" Send a secure code by email "}}" response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` lines +```swift Swift +import Foundation let headers = [ "authorization": "Bearer {mgmtApiToken}", "content-type": "application/json" @@ -376,37 +406,32 @@ let httpResponse = response as? HTTPURLResponse print(httpResponse) } }) -dataTask.resume()`; - - - lines - - lines - - lines - - lines - - lines - - +dataTask.resume() +``` + As a result, a **Send a secure code by email button** is added to the `login-password` screen. When a user selects this button, it submits a form body containing the login state parameter and the name of the desired connection. Similarly, you can configure the `login-passwordless` prompt using the [Set partials for a prompt](/docs/api/management/v2/prompts/put-partials) endpoint: -export const codeExample21 = `curl --request PUT \ + +```bash cURL +curl --request PUT \ --url 'https://{yourDomain}/api/v2/prompts/login-passwordless/partials' \ --header 'authorization: Bearer {mgmtApiToken}' \ --header 'content-type: application/json' \ ---data '{"login-passwordless-email-code":{"form-footer-start":" Use Password Instead "}}'`; -export const codeExample22 = `var client = new RestClient("https://{yourDomain}/api/v2/prompts/login-passwordless/partials"); +--data '{"login-passwordless-email-code":{"form-footer-start":" Use Password Instead "}}' +``` lines +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/prompts/login-passwordless/partials"); var request = new RestRequest(Method.PUT); request.AddHeader("authorization", "Bearer {mgmtApiToken}"); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\"login-passwordless-email-code\":{\"form-footer-start\":\" Use Password Instead \"}}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample23 = `package main +request.AddParameter("application/json", "{"login-passwordless-email-code":{"form-footer-start":" Use Password Instead "}}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" "strings" @@ -415,7 +440,7 @@ import ( ) func main() { url := "https://{yourDomain}/api/v2/prompts/login-passwordless/partials" -payload := strings.NewReader("{\"login-passwordless-email-code\":{\"form-footer-start\":\" Use Password Instead \"}}") +payload := strings.NewReader("{"login-passwordless-email-code":{"form-footer-start":" Use Password Instead "}}") req, _ := http.NewRequest("PUT", url, payload) req.Header.Add("authorization", "Bearer {mgmtApiToken}") req.Header.Add("content-type", "application/json") @@ -424,13 +449,17 @@ defer res.Body.Close() body, _ := ioutil.ReadAll(res.Body) fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample24 = `HttpResponse response = Unirest.put("https://{yourDomain}/api/v2/prompts/login-passwordless/partials") +} +``` lines +```java Java +HttpResponse response = Unirest.put("https://{yourDomain}/api/v2/prompts/login-passwordless/partials") .header("authorization", "Bearer {mgmtApiToken}") .header("content-type", "application/json") -.body("{\"login-passwordless-email-code\":{\"form-footer-start\":\" Use Password Instead \"}}") -.asString();`; -export const codeExample25 = `var axios = require("axios").default; +.body("{"login-passwordless-email-code":{"form-footer-start":" Use Password Instead "}}") +.asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PUT', url: 'https://{yourDomain}/api/v2/prompts/login-passwordless/partials', @@ -445,8 +474,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample26 = `#import +}); +``` lines +```obj-c Obj-C +#import NSDictionary \*headers = @{ @"authorization": @"Bearer {mgmtApiToken}", @"content-type": @"application/json" }; NSDictionary \*parameters = @{ @"login-passwordless-email-code": @{ @"form-footer-start": @" Use Password Instead " } }; @@ -467,8 +498,10 @@ NSHTTPURLResponse \*httpResponse = (NSHTTPURLResponse \*) response; NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample27 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/prompts/login-passwordless/partials", CURLOPT_RETURNTRANSFER => true, @@ -477,7 +510,7 @@ CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PUT", -CURLOPT_POSTFIELDS => "{\"login-passwordless-email-code\":{\"form-footer-start\":\" Use Password Instead \"}}", +CURLOPT_POSTFIELDS => "{"login-passwordless-email-code":{"form-footer-start":" Use Password Instead "}}", CURLOPT_HTTPHEADER => [ "authorization: Bearer {mgmtApiToken}", "content-type: application/json" @@ -490,10 +523,12 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample28 = `import http.client +} +``` lines +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"login-passwordless-email-code\":{\"form-footer-start\":\" Use Password Instead \"}}" +payload = "{"login-passwordless-email-code":{"form-footer-start":" Use Password Instead "}}" headers = { 'authorization': "Bearer {mgmtApiToken}", 'content-type': "application/json" @@ -501,8 +536,10 @@ headers = { conn.request("PUT", "/{yourDomain}/api/v2/prompts/login-passwordless/partials", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample29 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' url = URI("https://{yourDomain}/api/v2/prompts/login-passwordless/partials") @@ -512,10 +549,12 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Put.new(url) request["authorization"] = 'Bearer {mgmtApiToken}' request["content-type"] = 'application/json' -request.body = "{\"login-passwordless-email-code\":{\"form-footer-start\":\" Use Password Instead \"}}" +request.body = "{"login-passwordless-email-code":{"form-footer-start":" Use Password Instead "}}" response = http.request(request) -puts response.read_body`; -export const codeExample30 = `import Foundation +puts response.read_body +``` lines +```swift Swift +import Foundation let headers = [ "authorization": "Bearer {mgmtApiToken}", "content-type": "application/json" @@ -537,18 +576,7 @@ let httpResponse = response as? HTTPURLResponse print(httpResponse) } }) -dataTask.resume()`; - - - lines - - lines - - lines - - lines - - lines - - +dataTask.resume() +``` + diff --git a/main/docs/ja-jp/customize/login-pages/universal-login/customize-signup-and-login-prompts/language-selection.mdx b/main/docs/ja-jp/customize/login-pages/universal-login/customize-signup-and-login-prompts/language-selection.mdx index 74531e0e4..14b19a5b3 100644 --- a/main/docs/ja-jp/customize/login-pages/universal-login/customize-signup-and-login-prompts/language-selection.mdx +++ b/main/docs/ja-jp/customize/login-pages/universal-login/customize-signup-and-login-prompts/language-selection.mdx @@ -10,6 +10,7 @@ permalink: "language-selection" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Flexible language selection is an optional feature that allows users to select their preferred language on Universal Login prompts associated with your application, such as the login screen. You can configure this feature individually for different Universal Login prompts. @@ -70,7 +71,9 @@ Be aware that this call will **overwrite any existing configurations** you have -export const codeExample1 = `curl --request PUT \ + +```bash cURL +curl --request PUT \ --url 'https://{yourDomain}/api/v2/branding/templates/universal-login' \ --header 'authorization: Bearer MANAGEMENT_API_TOKEN' \ --header 'content-type: text/html' \ @@ -78,15 +81,22 @@ export const codeExample1 = `curl --request PUT \ {%- auth0:head -%} {%- auth0:widget -%} -'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/branding/templates/universal-login"); +' +``` lines +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/branding/templates/universal-login"); var request = new RestRequest(Method.PUT); request.AddHeader("content-type", "text/html"); request.AddHeader("authorization", "Bearer MANAGEMENT_API_TOKEN"); request.AddParameter("text/html", " -\n\n{%- auth0:head -%}\n{%- auth0:widget -%}\n", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main + +{%- auth0:head -%} +{%- auth0:widget -%} +", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" "strings" @@ -96,7 +106,10 @@ import ( func main() { url := "https://{yourDomain}/api/v2/branding/templates/universal-login" payload := strings.NewReader(" -\n\n{%- auth0:head -%}\n{%- auth0:widget -%}\n") + +{%- auth0:head -%} +{%- auth0:widget -%} +") req, _ := http.NewRequest("PUT", url, payload) req.Header.Add("content-type", "text/html") req.Header.Add("authorization", "Bearer MANAGEMENT_API_TOKEN") @@ -105,27 +118,39 @@ defer res.Body.Close() body, _ := ioutil.ReadAll(res.Body) fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.put("https://{yourDomain}/api/v2/branding/templates/universal-login") +} +``` lines +```java Java +HttpResponse response = Unirest.put("https://{yourDomain}/api/v2/branding/templates/universal-login") .header("content-type", "text/html") .header("authorization", "Bearer MANAGEMENT_API_TOKEN") .body(" -\n\n{%- auth0:head -%}\n{%- auth0:widget -%}\n") -.asString();`; -export const codeExample5 = `var axios = require("axios").default; + +{%- auth0:head -%} +{%- auth0:widget -%} +") +.asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PUT', url: 'https://{yourDomain}/api/v2/branding/templates/universal-login', headers: {'content-type': 'text/html', authorization: 'Bearer MANAGEMENT_API_TOKEN'}, data: ' -\n\n{%- auth0:head -%}\n{%- auth0:widget -%}\n' + +{%- auth0:head -%} +{%- auth0:widget -%} +' }; axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` lines +```obj-c Obj-C +#import NSDictionary \*headers = @{ @"content-type": @"text/html", @"authorization": @"Bearer MANAGEMENT_API_TOKEN" }; NSData \*postData = [[NSData alloc] initWithData:[@" @@ -149,8 +174,10 @@ NSHTTPURLResponse \*httpResponse = (NSHTTPURLResponse \*) response; NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/branding/templates/universal-login", CURLOPT_RETURNTRANSFER => true, @@ -160,7 +187,10 @@ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PUT", CURLOPT_POSTFIELDS => " -\n\n{%- auth0:head -%}\n{%- auth0:widget -%}\n", + +{%- auth0:head -%} +{%- auth0:widget -%} +", CURLOPT_HTTPHEADER => [ "authorization: Bearer MANAGEMENT_API_TOKEN", "content-type: text/html" @@ -173,11 +203,16 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` lines +```python Python +import http.client conn = http.client.HTTPSConnection("") payload = " -\n\n{%- auth0:head -%}\n{%- auth0:widget -%}\n" + +{%- auth0:head -%} +{%- auth0:widget -%} +" headers = { 'content-type': "text/html", 'authorization': "Bearer MANAGEMENT_API_TOKEN" @@ -185,8 +220,10 @@ headers = { conn.request("PUT", "/{yourDomain}/api/v2/branding/templates/universal-login", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' url = URI("https://{yourDomain}/api/v2/branding/templates/universal-login") @@ -197,10 +234,15 @@ request = Net::HTTP::Put.new(url) request["content-type"] = 'text/html' request["authorization"] = 'Bearer MANAGEMENT_API_TOKEN' request.body = " -\n\n{%- auth0:head -%}\n{%- auth0:widget -%}\n" + +{%- auth0:head -%} +{%- auth0:widget -%} +" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` lines +```swift Swift +import Foundation let headers = [ "content-type": "text/html", "authorization": "Bearer MANAGEMENT_API_TOKEN" @@ -225,20 +267,9 @@ let httpResponse = response as? HTTPURLResponse print(httpResponse) } }) -dataTask.resume()`; - - - lines - - lines - - lines - - lines - - lines - - +dataTask.resume() +``` + ### Configure individual Universal Login prompts @@ -289,7 +320,9 @@ accordion.expand_all/accordion.collapse_all To add language selection to the `signup` prompt, use the [Set partials for a prompt](/docs/ja-jp/api/management/v2/prompts/put-partials) endpoint: -export const codeExample11 = `curl --request PUT \ + +```bash cURL +curl --request PUT \ --url 'https://{yourDomain}/api/v2/prompts/signup/partials' \ --header 'authorization: Bearer {mgmtApiToken}' \ --header 'content-type: application/json' \ @@ -301,18 +334,26 @@ Preferred LanguageEnglishFrenchSpanish " } -}'`; -export const codeExample12 = `var client = new RestClient("https://{yourDomain}/api/v2/prompts/signup/partials"); +}' +``` lines +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/prompts/signup/partials"); var request = new RestRequest(Method.PUT); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer {mgmtApiToken}"); -request.AddParameter("application/json", "{\n \"signup\": {\n \"form-content-start\": \" +request.AddParameter("application/json", "{ + "signup": { + "form-content-start": " Preferred LanguageEnglishFrenchSpanish -\"\n }\n}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample13 = `package main +" + } +}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" "strings" @@ -321,11 +362,15 @@ import ( ) func main() { url := "https://{yourDomain}/api/v2/prompts/signup/partials" -payload := strings.NewReader("{\n \"signup\": {\n \"form-content-start\": \" +payload := strings.NewReader("{ + "signup": { + "form-content-start": " Preferred LanguageEnglishFrenchSpanish -\"\n }\n}") +" + } +}") req, _ := http.NewRequest("PUT", url, payload) req.Header.Add("content-type", "application/json") req.Header.Add("authorization", "Bearer {mgmtApiToken}") @@ -334,17 +379,25 @@ defer res.Body.Close() body, _ := ioutil.ReadAll(res.Body) fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample14 = `HttpResponse response = Unirest.put("https://{yourDomain}/api/v2/prompts/signup/partials") +} +``` lines +```java Java +HttpResponse response = Unirest.put("https://{yourDomain}/api/v2/prompts/signup/partials") .header("content-type", "application/json") .header("authorization", "Bearer {mgmtApiToken}") -.body("{\n \"signup\": {\n \"form-content-start\": \" +.body("{ + "signup": { + "form-content-start": " Preferred LanguageEnglishFrenchSpanish -\"\n }\n}") -.asString();`; -export const codeExample15 = `var axios = require("axios").default; +" + } +}") +.asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PUT', url: 'https://{yourDomain}/api/v2/prompts/signup/partials', @@ -363,8 +416,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample16 = `#import +}); +``` lines +```obj-c Obj-C +#import NSDictionary \*headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer {mgmtApiToken}" }; NSDictionary \*parameters = @{ @"signup": @{ @"form-content-start": @" @@ -389,8 +444,10 @@ NSHTTPURLResponse \*httpResponse = (NSHTTPURLResponse \*) response; NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/prompts/signup/partials", CURLOPT_RETURNTRANSFER => true, @@ -399,11 +456,15 @@ CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PUT", -CURLOPT_POSTFIELDS => "{\n \"signup\": {\n \"form-content-start\": \" +CURLOPT_POSTFIELDS => "{ + "signup": { + "form-content-start": " Preferred LanguageEnglishFrenchSpanish -\"\n }\n}", +" + } +}", CURLOPT_HTTPHEADER => [ "authorization: Bearer {mgmtApiToken}", "content-type: application/json" @@ -416,14 +477,20 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `import http.client +} +``` lines +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\n \"signup\": {\n \"form-content-start\": \" +payload = "{ + "signup": { + "form-content-start": " Preferred LanguageEnglishFrenchSpanish -\"\n }\n}" +" + } +}" headers = { 'content-type': "application/json", 'authorization': "Bearer {mgmtApiToken}" @@ -431,8 +498,10 @@ headers = { conn.request("PUT", "/{yourDomain}/api/v2/prompts/signup/partials", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' url = URI("https://{yourDomain}/api/v2/prompts/signup/partials") @@ -442,14 +511,20 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Put.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer {mgmtApiToken}' -request.body = "{\n \"signup\": {\n \"form-content-start\": \" +request.body = "{ + "signup": { + "form-content-start": " Preferred LanguageEnglishFrenchSpanish -\"\n }\n}" +" + } +}" response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` lines +```swift Swift +import Foundation let headers = [ "content-type": "application/json", "authorization": "Bearer {mgmtApiToken}" @@ -475,20 +550,9 @@ let httpResponse = response as? HTTPURLResponse print(httpResponse) } }) -dataTask.resume()`; - - - lines - - lines - - lines - - lines - - lines - - +dataTask.resume() +``` + @@ -496,7 +560,9 @@ dataTask.resume()`; To add language selection to the `login-id` prompt, use the [Set partials for a prompt](/docs/ja-jp/api/management/v2/prompts/put-partials) endpoint: -export const codeExample21 = `curl --request PUT \ + +```bash cURL +curl --request PUT \ --url 'https://{yourDomain}/api/v2/prompts/login-id/partials' \ --header 'authorization: Bearer {mgmtApiToken}' \ --header 'content-type: application/json' \ @@ -508,18 +574,26 @@ Preferred LanguageEnglishFrenchSpanish " } -}'`; -export const codeExample22 = `var client = new RestClient("https://{yourDomain}/api/v2/prompts/login-id/partials"); +}' +``` lines +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/prompts/login-id/partials"); var request = new RestRequest(Method.PUT); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer {mgmtApiToken}"); -request.AddParameter("application/json", "{\n \"login-id\": {\n \"form-content-start\": \" +request.AddParameter("application/json", "{ + "login-id": { + "form-content-start": " Preferred LanguageEnglishFrenchSpanish -\"\n }\n}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample23 = `package main +" + } +}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" "strings" @@ -528,11 +602,15 @@ import ( ) func main() { url := "https://{yourDomain}/api/v2/prompts/login-id/partials" -payload := strings.NewReader("{\n \"login-id\": {\n \"form-content-start\": \" +payload := strings.NewReader("{ + "login-id": { + "form-content-start": " Preferred LanguageEnglishFrenchSpanish -\"\n }\n}") +" + } +}") req, _ := http.NewRequest("PUT", url, payload) req.Header.Add("content-type", "application/json") req.Header.Add("authorization", "Bearer {mgmtApiToken}") @@ -541,17 +619,25 @@ defer res.Body.Close() body, _ := ioutil.ReadAll(res.Body) fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample24 = `HttpResponse response = Unirest.put("https://{yourDomain}/api/v2/prompts/login-id/partials") +} +``` lines +```java Java +HttpResponse response = Unirest.put("https://{yourDomain}/api/v2/prompts/login-id/partials") .header("content-type", "application/json") .header("authorization", "Bearer {mgmtApiToken}") -.body("{\n \"login-id\": {\n \"form-content-start\": \" +.body("{ + "login-id": { + "form-content-start": " Preferred LanguageEnglishFrenchSpanish -\"\n }\n}") -.asString();`; -export const codeExample25 = `var axios = require("axios").default; +" + } +}") +.asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PUT', url: 'https://{yourDomain}/api/v2/prompts/login-id/partials', @@ -570,8 +656,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample26 = `#import +}); +``` lines +```obj-c Obj-C +#import NSDictionary \*headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer {mgmtApiToken}" }; NSDictionary \*parameters = @{ @"login-id": @{ @"form-content-start": @" @@ -596,8 +684,10 @@ NSHTTPURLResponse \*httpResponse = (NSHTTPURLResponse \*) response; NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample27 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/prompts/login-id/partials", CURLOPT_RETURNTRANSFER => true, @@ -606,11 +696,15 @@ CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PUT", -CURLOPT_POSTFIELDS => "{\n \"login-id\": {\n \"form-content-start\": \" +CURLOPT_POSTFIELDS => "{ + "login-id": { + "form-content-start": " Preferred LanguageEnglishFrenchSpanish -\"\n }\n}", +" + } +}", CURLOPT_HTTPHEADER => [ "authorization: Bearer {mgmtApiToken}", "content-type: application/json" @@ -623,14 +717,20 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample28 = `import http.client +} +``` lines +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\n \"login-id\": {\n \"form-content-start\": \" +payload = "{ + "login-id": { + "form-content-start": " Preferred LanguageEnglishFrenchSpanish -\"\n }\n}" +" + } +}" headers = { 'content-type': "application/json", 'authorization': "Bearer {mgmtApiToken}" @@ -638,8 +738,10 @@ headers = { conn.request("PUT", "/{yourDomain}/api/v2/prompts/login-id/partials", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample29 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' url = URI("https://{yourDomain}/api/v2/prompts/login-id/partials") @@ -649,14 +751,20 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Put.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer {mgmtApiToken}' -request.body = "{\n \"login-id\": {\n \"form-content-start\": \" +request.body = "{ + "login-id": { + "form-content-start": " Preferred LanguageEnglishFrenchSpanish -\"\n }\n}" +" + } +}" response = http.request(request) -puts response.read_body`; -export const codeExample30 = `import Foundation +puts response.read_body +``` lines +```swift Swift +import Foundation let headers = [ "content-type": "application/json", "authorization": "Bearer {mgmtApiToken}" @@ -682,20 +790,9 @@ let httpResponse = response as? HTTPURLResponse print(httpResponse) } }) -dataTask.resume()`; - - - lines - - lines - - lines - - lines - - lines - - +dataTask.resume() +``` + @@ -703,7 +800,9 @@ dataTask.resume()`; To add language selection to the `login-passwordless-email-code` prompt, use the [Set partials for a prompt](/docs/ja-jp/api/management/v2/prompts/put-partials) endpoint: -export const codeExample31 = `curl --request PUT \ + +```bash cURL +curl --request PUT \ --url 'https://{yourDomain}/api/v2/prompts/login-passwordless/partials' \ --header 'authorization: Bearer {mgmtApiToken}' \ --header 'content-type: application/json' \ @@ -715,18 +814,26 @@ Preferred LanguageEnglishFrenchSpanish " } -}'`; -export const codeExample32 = `var client = new RestClient("https://{yourDomain}/api/v2/prompts/login-passwordless/partials"); +}' +``` lines +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/prompts/login-passwordless/partials"); var request = new RestRequest(Method.PUT); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer {mgmtApiToken}"); -request.AddParameter("application/json", "{\n \"login-passwordless-email-code\": {\n \"form-content-start\": \" +request.AddParameter("application/json", "{ + "login-passwordless-email-code": { + "form-content-start": " Preferred LanguageEnglishFrenchSpanish -\"\n }\n}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample33 = `package main +" + } +}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" "strings" @@ -735,11 +842,15 @@ import ( ) func main() { url := "https://{yourDomain}/api/v2/prompts/login-passwordless/partials" -payload := strings.NewReader("{\n \"login-passwordless-email-code\": {\n \"form-content-start\": \" +payload := strings.NewReader("{ + "login-passwordless-email-code": { + "form-content-start": " Preferred LanguageEnglishFrenchSpanish -\"\n }\n}") +" + } +}") req, _ := http.NewRequest("PUT", url, payload) req.Header.Add("content-type", "application/json") req.Header.Add("authorization", "Bearer {mgmtApiToken}") @@ -748,17 +859,25 @@ defer res.Body.Close() body, _ := ioutil.ReadAll(res.Body) fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample34 = `HttpResponse response = Unirest.put("https://{yourDomain}/api/v2/prompts/login-passwordless/partials") +} +``` lines +```java Java +HttpResponse response = Unirest.put("https://{yourDomain}/api/v2/prompts/login-passwordless/partials") .header("content-type", "application/json") .header("authorization", "Bearer {mgmtApiToken}") -.body("{\n \"login-passwordless-email-code\": {\n \"form-content-start\": \" +.body("{ + "login-passwordless-email-code": { + "form-content-start": " Preferred LanguageEnglishFrenchSpanish -\"\n }\n}") -.asString();`; -export const codeExample35 = `var axios = require("axios").default; +" + } +}") +.asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PUT', url: 'https://{yourDomain}/api/v2/prompts/login-passwordless/partials', @@ -777,8 +896,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample36 = `#import +}); +``` lines +```obj-c Obj-C +#import NSDictionary \*headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer {mgmtApiToken}" }; NSDictionary \*parameters = @{ @"login-passwordless-email-code": @{ @"form-content-start": @" @@ -803,8 +924,10 @@ NSHTTPURLResponse \*httpResponse = (NSHTTPURLResponse \*) response; NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample37 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/prompts/login-passwordless/partials", CURLOPT_RETURNTRANSFER => true, @@ -813,11 +936,15 @@ CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PUT", -CURLOPT_POSTFIELDS => "{\n \"login-passwordless-email-code\": {\n \"form-content-start\": \" +CURLOPT_POSTFIELDS => "{ + "login-passwordless-email-code": { + "form-content-start": " Preferred LanguageEnglishFrenchSpanish -\"\n }\n}", +" + } +}", CURLOPT_HTTPHEADER => [ "authorization: Bearer {mgmtApiToken}", "content-type: application/json" @@ -830,14 +957,20 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample38 = `import http.client +} +``` lines +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\n \"login-passwordless-email-code\": {\n \"form-content-start\": \" +payload = "{ + "login-passwordless-email-code": { + "form-content-start": " Preferred LanguageEnglishFrenchSpanish -\"\n }\n}" +" + } +}" headers = { 'content-type': "application/json", 'authorization': "Bearer {mgmtApiToken}" @@ -845,8 +978,10 @@ headers = { conn.request("PUT", "/{yourDomain}/api/v2/prompts/login-passwordless/partials", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample39 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' url = URI("https://{yourDomain}/api/v2/prompts/login-passwordless/partials") @@ -856,14 +991,20 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Put.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer {mgmtApiToken}' -request.body = "{\n \"login-passwordless-email-code\": {\n \"form-content-start\": \" +request.body = "{ + "login-passwordless-email-code": { + "form-content-start": " Preferred LanguageEnglishFrenchSpanish -\"\n }\n}" +" + } +}" response = http.request(request) -puts response.read_body`; -export const codeExample40 = `import Foundation +puts response.read_body +``` lines +```swift Swift +import Foundation let headers = [ "content-type": "application/json", "authorization": "Bearer {mgmtApiToken}" @@ -889,20 +1030,9 @@ let httpResponse = response as? HTTPURLResponse print(httpResponse) } }) -dataTask.resume()`; - - - lines - - lines - - lines - - lines - - lines - - +dataTask.resume() +``` + diff --git a/main/docs/ja-jp/customize/login-pages/universal-login/customize-templates.mdx b/main/docs/ja-jp/customize/login-pages/universal-login/customize-templates.mdx index 7d882fb55..7bc012129 100644 --- a/main/docs/ja-jp/customize/login-pages/universal-login/customize-templates.mdx +++ b/main/docs/ja-jp/customize/login-pages/universal-login/customize-templates.mdx @@ -10,6 +10,7 @@ permalink: "customize-templates" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; [Liquidテンプレート言語](https://shopify.github.io/liquid/basics/introduction/)で作成したページテンプレートを提供することで、ユニバーサルログインページをカスタマイズできます。ページテンプレートを使用して、ログインボックスやMFAチャレンジなどの、ユニバーサルログインプロンプトに関して表示するコンテンツを定義できます。同じページテンプレートがすべてのログインフローページに使用されるため、このカスタマイズ手法は、ユーザーに対して一貫性のあるブランドエクスペリエンスの実装を簡単にします。 @@ -6204,19 +6205,25 @@ accordion.expand_all/accordion.collapse_all テンプレートを設定するには、以下のエンドポイントを使用する必要があります。 -export const codeExample1 = `curl --request PUT \ + +```bash cURL +curl --request PUT \ --url 'https://{yourDomain}/api/v2/branding/templates/universal-login' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'content-type: text/html' \ - --data '{%- auth0:head -%}{%- auth0:widget -%}'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/branding/templates/universal-login"); + --data '{%- auth0:head -%}{%- auth0:widget -%}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/branding/templates/universal-login"); var request = new RestRequest(Method.PUT); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("content-type", "text/html"); request.AddParameter("text/html", " {%- auth0:head -%}{%- auth0:widget -%}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -6244,13 +6251,17 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.put("https://{yourDomain}/api/v2/branding/templates/universal-login") +} +``` +```java Java +HttpResponse response = Unirest.put("https://{yourDomain}/api/v2/branding/templates/universal-login") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("content-type", "text/html") .body("{%- auth0:head -%}{%- auth0:widget -%}") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PUT', @@ -6263,8 +6274,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @"content-type": @"text/html" }; @@ -6288,8 +6301,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/branding/templates/universal-login", @@ -6315,8 +6330,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -6332,8 +6349,10 @@ conn.request("PUT", "/{yourDomain}/api/v2/branding/templates/universal-login", p res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -6349,8 +6368,10 @@ request["content-type"] = 'text/html' request.body = "{%- auth0:head -%}{%- auth0:widget -%}" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "authorization": "Bearer MGMT_API_ACCESS_TOKEN", @@ -6376,31 +6397,26 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + テンプレートを取得するには、以下のエンドポイントを使用する必要があります。 -export const codeExample11 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/branding/templates/universal-login' \ - --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN'`; -export const codeExample12 = `var client = new RestClient("https://{yourDomain}/api/v2/branding/templates/universal-login"); + --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/branding/templates/universal-login"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); -IRestResponse response = client.Execute(request);`; -export const codeExample13 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -6424,11 +6440,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample14 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/branding/templates/universal-login") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/branding/templates/universal-login") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") - .asString();`; -export const codeExample15 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -6440,8 +6460,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample16 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN" }; @@ -6461,8 +6483,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/branding/templates/universal-login", @@ -6486,8 +6510,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -6498,8 +6524,10 @@ conn.request("GET", "/{yourDomain}/api/v2/branding/templates/universal-login", h res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -6513,8 +6541,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer MGMT_API_ACCESS_TOKEN"] @@ -6534,31 +6564,26 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + テンプレートを削除するには、以下のエンドポイントを使用する必要があります。 -export const codeExample21 = `curl --request DELETE \ + +```bash cURL +curl --request DELETE \ --url 'https://{yourDomain}/api/v2/branding/templates/universal-login' \ - --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN'`; -export const codeExample22 = `var client = new RestClient("https://{yourDomain}/api/v2/branding/templates/universal-login"); + --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/branding/templates/universal-login"); var request = new RestRequest(Method.DELETE); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); -IRestResponse response = client.Execute(request);`; -export const codeExample23 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -6582,11 +6607,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample24 = `HttpResponse response = Unirest.delete("https://{yourDomain}/api/v2/branding/templates/universal-login") +} +``` +```java Java +HttpResponse response = Unirest.delete("https://{yourDomain}/api/v2/branding/templates/universal-login") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") - .asString();`; -export const codeExample25 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'DELETE', @@ -6598,8 +6627,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample26 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN" }; @@ -6619,8 +6650,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample27 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/branding/templates/universal-login", @@ -6644,8 +6677,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample28 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -6656,8 +6691,10 @@ conn.request("DELETE", "/{yourDomain}/api/v2/branding/templates/universal-login" res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample29 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -6671,8 +6708,10 @@ request = Net::HTTP::Delete.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' response = http.request(request) -puts response.read_body`; -export const codeExample30 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer MGMT_API_ACCESS_TOKEN"] @@ -6692,20 +6731,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ページテンプレートの最大サイズは100KBです。これが十分でない場合は、画像/cssファイルをページテンプレートコードの外に出すことを検討してください。 diff --git a/main/docs/ja-jp/customize/login-pages/universal-login/customize-text-elements.mdx b/main/docs/ja-jp/customize/login-pages/universal-login/customize-text-elements.mdx index 282dd68df..5d03d746c 100644 --- a/main/docs/ja-jp/customize/login-pages/universal-login/customize-text-elements.mdx +++ b/main/docs/ja-jp/customize/login-pages/universal-login/customize-text-elements.mdx @@ -10,6 +10,7 @@ permalink: "customize-text-elements" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; ユニバーサルログインは、ログイン、MFA要素の登録、パスワードのリセットなど、アカウントに関連したさまざまな操作を実行できる一連のページで構成されています。Auth0はそれらのページに複数の言語でテキストを提供しています。 @@ -50,18 +51,24 @@ Management APIを使用して、ユニバーサルログインテキストプロ Management APIの[指定プロンプトにカスタムテキスト設定](https://auth0.com/docs/api/management/v2#!/Prompts/put_custom_text_by_language)エンドポイントを呼び出し、 `Log in to ACME's website`の`login`プロンプトの`login`画面に使用する`description`テキストコンポーネントを設定することができます。次のようなものです: -export const codeExample1 = `curl --request PUT \ + +```bash cURL +curl --request PUT \ --url 'https://{yourDomain}/api/v2/prompts/login/custom-text/en' \ --header 'authorization: Bearer {yourMgmtApiAccessToken}' \ --header 'content-type: application/json' \ - --data '{ "login": { "description": "Login to ACME'\''s Website" } }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/prompts/login/custom-text/en"); + --data '{ "login": { "description": "Login to ACME'''s Website" } }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/prompts/login/custom-text/en"); var request = new RestRequest(Method.PUT); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer {yourMgmtApiAccessToken}"); -request.AddParameter("application/json", "{ \"login\": { \"description\": \"Login to ACME's Website\" } }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "login": { "description": "Login to ACME's Website" } }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -74,7 +81,7 @@ func main() { url := "https://{yourDomain}/api/v2/prompts/login/custom-text/en" - payload := strings.NewReader("{ \"login\": { \"description\": \"Login to ACME's Website\" } }") + payload := strings.NewReader("{ "login": { "description": "Login to ACME's Website" } }") req, _ := http.NewRequest("PUT", url, payload) @@ -89,13 +96,17 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.put("https://{yourDomain}/api/v2/prompts/login/custom-text/en") +} +``` +```java Java +HttpResponse response = Unirest.put("https://{yourDomain}/api/v2/prompts/login/custom-text/en") .header("content-type", "application/json") .header("authorization", "Bearer {yourMgmtApiAccessToken}") - .body("{ \"login\": { \"description\": \"Login to ACME's Website\" } }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "login": { "description": "Login to ACME's Website" } }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PUT', @@ -104,15 +115,17 @@ var options = { 'content-type': 'application/json', authorization: 'Bearer {yourMgmtApiAccessToken}' }, - data: {login: {description: 'Login to ACME\'s Website'}} + data: {login: {description: 'Login to ACME's Website'}} }; axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer {yourMgmtApiAccessToken}" }; @@ -137,8 +150,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/prompts/login/custom-text/en", @@ -148,7 +163,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PUT", - CURLOPT_POSTFIELDS => "{ \"login\": { \"description\": \"Login to ACME's Website\" } }", + CURLOPT_POSTFIELDS => "{ "login": { "description": "Login to ACME's Website" } }", CURLOPT_HTTPHEADER => [ "authorization: Bearer {yourMgmtApiAccessToken}", "content-type: application/json" @@ -164,12 +179,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"login\": { \"description\": \"Login to ACME's Website\" } }" +payload = "{ "login": { "description": "Login to ACME's Website" } }" headers = { 'content-type': "application/json", @@ -181,8 +198,10 @@ conn.request("PUT", "/{yourDomain}/api/v2/prompts/login/custom-text/en", payload res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -195,11 +214,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Put.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer {yourMgmtApiAccessToken}' -request.body = "{ \"login\": { \"description\": \"Login to ACME's Website\" } }" +request.body = "{ "login": { "description": "Login to ACME's Website" } }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -226,37 +247,32 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + #### プロンプトのカスタムテキストの削除 プロンプトのすべてのカスタムテキストを削除したい場合、Management APIの[指定プロンプトにカスタムテキストの設定](https://auth0.com/docs/api/management/v2#!/Prompts/put_custom_text_by_language)エンドポイントを呼び出し、`body`パラメーターとして空のオブジェクト(`{}`)を指定してください。 -export const codeExample11 = `curl --request PUT \ + +```bash cURL +curl --request PUT \ --url 'https://{yourDomain}/api/v2/prompts/login/custom-text/en' \ --header 'authorization: Bearer {yourMgmtApiAccessToken}' \ --header 'content-type: application/json' \ - --data '{}'`; -export const codeExample12 = `var client = new RestClient("https://{yourDomain}/api/v2/prompts/login/custom-text/en"); + --data '{}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/prompts/login/custom-text/en"); var request = new RestRequest(Method.PUT); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer {yourMgmtApiAccessToken}"); request.AddParameter("application/json", "{}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample13 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -284,13 +300,17 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample14 = `HttpResponse response = Unirest.put("https://{yourDomain}/api/v2/prompts/login/custom-text/en") +} +``` +```java Java +HttpResponse response = Unirest.put("https://{yourDomain}/api/v2/prompts/login/custom-text/en") .header("content-type", "application/json") .header("authorization", "Bearer {yourMgmtApiAccessToken}") .body("{}") - .asString();`; -export const codeExample15 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PUT', @@ -306,8 +326,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample16 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer {yourMgmtApiAccessToken}" }; @@ -332,8 +354,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/prompts/login/custom-text/en", @@ -359,8 +383,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -376,8 +402,10 @@ conn.request("PUT", "/{yourDomain}/api/v2/prompts/login/custom-text/en", payload res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -393,8 +421,10 @@ request["authorization"] = 'Bearer {yourMgmtApiAccessToken}' request.body = "{}" response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -421,20 +451,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + diff --git a/main/docs/ja-jp/customize/rules/create-rules.mdx b/main/docs/ja-jp/customize/rules/create-rules.mdx index e64c3eeb9..a8fa85371 100644 --- a/main/docs/ja-jp/customize/rules/create-rules.mdx +++ b/main/docs/ja-jp/customize/rules/create-rules.mdx @@ -10,6 +10,7 @@ permalink: "create-rules" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; @@ -68,20 +69,26 @@ RulesからActionsへの移行方法については、「[RulesからActionsに [ルール作成エンドポイント](/docs/ja-jp/api/management/v2#!/Rules/post_rules)に`POST`呼び出しを行います。`MGMT_API_ACCESS_TOKEN`、`RULE_NAME`、`RULE_SCRIPT`、`RULE_ORDER`、および`RULE_ENABLED`のプレースホルダーの値をそれぞれ、実際のManagement APIのアクセストークン、ルール名、ルールスクリプト、ルールの順序、ルールの有効化の値に置き換えてください。 -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/api/v2/rules' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{ "name": "RULE_NAME", "script": "RULE_SCRIPT" }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/rules"); + --data '{ "name": "RULE_NAME", "script": "RULE_SCRIPT" }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/rules"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{ \"name\": \"RULE_NAME\", \"script\": \"RULE_SCRIPT\" }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "name": "RULE_NAME", "script": "RULE_SCRIPT" }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -94,7 +101,7 @@ func main() { url := "https://{yourDomain}/api/v2/rules" - payload := strings.NewReader("{ \"name\": \"RULE_NAME\", \"script\": \"RULE_SCRIPT\" }") + payload := strings.NewReader("{ "name": "RULE_NAME", "script": "RULE_SCRIPT" }") req, _ := http.NewRequest("POST", url, payload) @@ -110,14 +117,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/rules") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/rules") .header("content-type", "application/json") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ \"name\": \"RULE_NAME\", \"script\": \"RULE_SCRIPT\" }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "name": "RULE_NAME", "script": "RULE_SCRIPT" }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -134,8 +145,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @@ -162,8 +175,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/rules", @@ -173,7 +188,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{ \"name\": \"RULE_NAME\", \"script\": \"RULE_SCRIPT\" }", + CURLOPT_POSTFIELDS => "{ "name": "RULE_NAME", "script": "RULE_SCRIPT" }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "cache-control: no-cache", @@ -190,12 +205,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"name\": \"RULE_NAME\", \"script\": \"RULE_SCRIPT\" }" +payload = "{ "name": "RULE_NAME", "script": "RULE_SCRIPT" }" headers = { 'content-type': "application/json", @@ -208,8 +225,10 @@ conn.request("POST", "/{yourDomain}/api/v2/rules", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -223,11 +242,13 @@ request = Net::HTTP::Post.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ \"name\": \"RULE_NAME\", \"script\": \"RULE_SCRIPT\" }" +request.body = "{ "name": "RULE_NAME", "script": "RULE_SCRIPT" }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -258,20 +279,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
    diff --git a/main/docs/ja-jp/get-started/apis/add-api-permissions.mdx b/main/docs/ja-jp/get-started/apis/add-api-permissions.mdx index 00f6addea..6d34b3d98 100644 --- a/main/docs/ja-jp/get-started/apis/add-api-permissions.mdx +++ b/main/docs/ja-jp/get-started/apis/add-api-permissions.mdx @@ -10,6 +10,7 @@ permalink: "add-api-permissions" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Auth0 DashboardまたはManagement APIを使用してAPIにアクセス許可を追加できます。 @@ -41,20 +42,26 @@ import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; [Update Resource Server(リソースサーバー更新)エンドポイント](https://auth0.com/docs/api/management/v2/resource-servers/patch-resource-servers-by-id)に対して`PATCH`呼び出しを行います。`API_ID`、`MGMT_API_ACCESS_TOKEN`、`PERMISSION_NAME`、`PERMISSION_DESC`のプレースホルダー値をそれぞれAPI ID、Management APIのアクセストークン、アクセス許可名、アクセス許可の説明に置き換えます。予約されたアクセス許可名は使用しないでください(予約名セクションを参照)。 -export const codeExample1 = `curl --request PATCH \ + +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/resource-servers/API_ID' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{ "scopes": [ { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" }, { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" } ] }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/resource-servers/API_ID"); + --data '{ "scopes": [ { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" }, { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" } ] }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/resource-servers/API_ID"); var request = new RestRequest(Method.PATCH); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{ \"scopes\": [ { \"value\": \"PERMISSION_NAME\", \"description\": \"PERMISSION_DESC\" }, { \"value\": \"PERMISSION_NAME\", \"description\": \"PERMISSION_DESC\" } ] }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "scopes": [ { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" }, { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" } ] }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -67,7 +74,7 @@ func main() { url := "https://{yourDomain}/api/v2/resource-servers/API_ID" - payload := strings.NewReader("{ \"scopes\": [ { \"value\": \"PERMISSION_NAME\", \"description\": \"PERMISSION_DESC\" }, { \"value\": \"PERMISSION_NAME\", \"description\": \"PERMISSION_DESC\" } ] }") + payload := strings.NewReader("{ "scopes": [ { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" }, { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" } ] }") req, _ := http.NewRequest("PATCH", url, payload) @@ -83,14 +90,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/resource-servers/API_ID") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/resource-servers/API_ID") .header("content-type", "application/json") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ \"scopes\": [ { \"value\": \"PERMISSION_NAME\", \"description\": \"PERMISSION_DESC\" }, { \"value\": \"PERMISSION_NAME\", \"description\": \"PERMISSION_DESC\" } ] }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "scopes": [ { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" }, { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" } ] }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -112,8 +123,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @@ -139,8 +152,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/resource-servers/API_ID", @@ -150,7 +165,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{ \"scopes\": [ { \"value\": \"PERMISSION_NAME\", \"description\": \"PERMISSION_DESC\" }, { \"value\": \"PERMISSION_NAME\", \"description\": \"PERMISSION_DESC\" } ] }", + CURLOPT_POSTFIELDS => "{ "scopes": [ { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" }, { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" } ] }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "cache-control: no-cache", @@ -167,12 +182,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"scopes\": [ { \"value\": \"PERMISSION_NAME\", \"description\": \"PERMISSION_DESC\" }, { \"value\": \"PERMISSION_NAME\", \"description\": \"PERMISSION_DESC\" } ] }" +payload = "{ "scopes": [ { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" }, { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" } ] }" headers = { 'content-type': "application/json", @@ -185,8 +202,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/resource-servers/API_ID", payload, h res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -200,11 +219,13 @@ request = Net::HTTP::Patch.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ \"scopes\": [ { \"value\": \"PERMISSION_NAME\", \"description\": \"PERMISSION_DESC\" }, { \"value\": \"PERMISSION_NAME\", \"description\": \"PERMISSION_DESC\" } ] }" +request.body = "{ "scopes": [ { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" }, { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" } ] }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -241,20 +262,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + diff --git a/main/docs/ja-jp/get-started/apis/delete-api-permissions.mdx b/main/docs/ja-jp/get-started/apis/delete-api-permissions.mdx index 95365b1fb..79e5f75a1 100644 --- a/main/docs/ja-jp/get-started/apis/delete-api-permissions.mdx +++ b/main/docs/ja-jp/get-started/apis/delete-api-permissions.mdx @@ -10,6 +10,7 @@ permalink: "delete-api-permissions" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Auth0 DashboardまたはManagement APIを使用してAPIからアクセス許可を削除できます。 @@ -27,20 +28,26 @@ import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; 維持したい権限を含み、削除したい権限をすべて除外する[アップデートリソースサーバーエンドポイント](https://auth0.com/docs/api/management/v2#!/Resource_Servers/patch_resource_servers_by_id)にPATCH呼び出しを行います。`API_ID`、`MGMT_API_ACCESS_TOKEN`、API_ID、`PERMISSION_NAME`、 `PERMISSION_DESC`のプレースホルダー値をそれぞれAPI ID、Management APIのアクセストークン、権限名、権限の説明に置き換えます。 -export const codeExample1 = `curl --request PATCH \ + +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/resource-servers/API_ID' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{ "scopes": [ { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" }, { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" } ] }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/resource-servers/API_ID"); + --data '{ "scopes": [ { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" }, { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" } ] }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/resource-servers/API_ID"); var request = new RestRequest(Method.PATCH); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{ \"scopes\": [ { \"value\": \"PERMISSION_NAME\", \"description\": \"PERMISSION_DESC\" }, { \"value\": \"PERMISSION_NAME\", \"description\": \"PERMISSION_DESC\" } ] }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "scopes": [ { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" }, { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" } ] }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -53,7 +60,7 @@ func main() { url := "https://{yourDomain}/api/v2/resource-servers/API_ID" - payload := strings.NewReader("{ \"scopes\": [ { \"value\": \"PERMISSION_NAME\", \"description\": \"PERMISSION_DESC\" }, { \"value\": \"PERMISSION_NAME\", \"description\": \"PERMISSION_DESC\" } ] }") + payload := strings.NewReader("{ "scopes": [ { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" }, { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" } ] }") req, _ := http.NewRequest("PATCH", url, payload) @@ -69,14 +76,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/resource-servers/API_ID") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/resource-servers/API_ID") .header("content-type", "application/json") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ \"scopes\": [ { \"value\": \"PERMISSION_NAME\", \"description\": \"PERMISSION_DESC\" }, { \"value\": \"PERMISSION_NAME\", \"description\": \"PERMISSION_DESC\" } ] }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "scopes": [ { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" }, { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" } ] }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -98,8 +109,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @@ -125,8 +138,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/resource-servers/API_ID", @@ -136,7 +151,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{ \"scopes\": [ { \"value\": \"PERMISSION_NAME\", \"description\": \"PERMISSION_DESC\" }, { \"value\": \"PERMISSION_NAME\", \"description\": \"PERMISSION_DESC\" } ] }", + CURLOPT_POSTFIELDS => "{ "scopes": [ { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" }, { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" } ] }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "cache-control: no-cache", @@ -153,12 +168,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"scopes\": [ { \"value\": \"PERMISSION_NAME\", \"description\": \"PERMISSION_DESC\" }, { \"value\": \"PERMISSION_NAME\", \"description\": \"PERMISSION_DESC\" } ] }" +payload = "{ "scopes": [ { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" }, { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" } ] }" headers = { 'content-type': "application/json", @@ -171,8 +188,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/resource-servers/API_ID", payload, h res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -186,11 +205,13 @@ request = Net::HTTP::Patch.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ \"scopes\": [ { \"value\": \"PERMISSION_NAME\", \"description\": \"PERMISSION_DESC\" }, { \"value\": \"PERMISSION_NAME\", \"description\": \"PERMISSION_DESC\" } ] }" +request.body = "{ "scopes": [ { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" }, { "value": "PERMISSION_NAME", "description": "PERMISSION_DESC" } ] }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -227,20 +248,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
    diff --git a/main/docs/ja-jp/get-started/apis/enable-role-based-access-control-for-apis.mdx b/main/docs/ja-jp/get-started/apis/enable-role-based-access-control-for-apis.mdx index 0e17500d4..3c9f47837 100644 --- a/main/docs/ja-jp/get-started/apis/enable-role-based-access-control-for-apis.mdx +++ b/main/docs/ja-jp/get-started/apis/enable-role-based-access-control-for-apis.mdx @@ -10,6 +10,7 @@ permalink: "enable-role-based-access-control-for-apis" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Auth0 DashboardまたはManagement使用して、APIに[ロールベースのアクセス制御(RBAC)](/docs/ja-jp/manage-users/access-control/rbac)を有効化することができます。これにより、APIの認可コア機能セットが有効になります。 @@ -42,20 +43,26 @@ RBACを有効にすると、アクセストークンに権限が含まれてい Management APIを使用してRBACを有効にするには、[リソースサーバー更新エンドポイント](https://auth0.com/docs/api/management/v2/resource-servers/patch-resource-servers-by-id)にPATCH要求を行います。PATCH要求で、`enforce_policies`を`true`に設定します。 -export const codeExample1 = `curl --request PATCH \ + +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/resource-servers/API_ID' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{ "enforce_policies": "true", "token_dialect": "TOKEN_DIALECT" }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/resource-servers/API_ID"); + --data '{ "enforce_policies": "true", "token_dialect": "TOKEN_DIALECT" }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/resource-servers/API_ID"); var request = new RestRequest(Method.PATCH); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{ \"enforce_policies\": \"true\", \"token_dialect\": \"TOKEN_DIALECT\" }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "enforce_policies": "true", "token_dialect": "TOKEN_DIALECT" }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -68,7 +75,7 @@ func main() { url := "https://{yourDomain}/api/v2/resource-servers/API_ID" - payload := strings.NewReader("{ \"enforce_policies\": \"true\", \"token_dialect\": \"TOKEN_DIALECT\" }") + payload := strings.NewReader("{ "enforce_policies": "true", "token_dialect": "TOKEN_DIALECT" }") req, _ := http.NewRequest("PATCH", url, payload) @@ -84,14 +91,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/resource-servers/API_ID") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/resource-servers/API_ID") .header("content-type", "application/json") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ \"enforce_policies\": \"true\", \"token_dialect\": \"TOKEN_DIALECT\" }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "enforce_policies": "true", "token_dialect": "TOKEN_DIALECT" }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -108,8 +119,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @@ -136,8 +149,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/resource-servers/API_ID", @@ -147,7 +162,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{ \"enforce_policies\": \"true\", \"token_dialect\": \"TOKEN_DIALECT\" }", + CURLOPT_POSTFIELDS => "{ "enforce_policies": "true", "token_dialect": "TOKEN_DIALECT" }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "cache-control: no-cache", @@ -164,12 +179,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"enforce_policies\": \"true\", \"token_dialect\": \"TOKEN_DIALECT\" }" +payload = "{ "enforce_policies": "true", "token_dialect": "TOKEN_DIALECT" }" headers = { 'content-type': "application/json", @@ -182,8 +199,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/resource-servers/API_ID", payload, h res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -197,11 +216,13 @@ request = Net::HTTP::Patch.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ \"enforce_policies\": \"true\", \"token_dialect\": \"TOKEN_DIALECT\" }" +request.body = "{ "enforce_policies": "true", "token_dialect": "TOKEN_DIALECT" }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -232,20 +253,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + 以下の表が示すように、`API_ID`、`MGMT_API_ACCESS_TOKEN`、`TOKEN_DIALECT`をそれぞれの値に置き換えます。 diff --git a/main/docs/ja-jp/get-started/applications/confidential-and-public-applications/update-application-ownership.mdx b/main/docs/ja-jp/get-started/applications/confidential-and-public-applications/update-application-ownership.mdx index 4f713339d..882a83315 100644 --- a/main/docs/ja-jp/get-started/applications/confidential-and-public-applications/update-application-ownership.mdx +++ b/main/docs/ja-jp/get-started/applications/confidential-and-public-applications/update-application-ownership.mdx @@ -10,25 +10,32 @@ permalink: "update-application-ownership" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Auth0のManagement APIを使用して、アプリケーションの所有権を更新することができます。これにより、アプリケーションをAuth0にファーストパーティーアプリケーションとして登録するのか、サードパーティーアプリケーションとして登録するのかを指定できます。 [クライアント更新エンドポイント](/docs/ja-jp/api/management/v2#!/Clients/patch_clients_by_id)に`PATCH`呼び出しを行います。必ず、`{yourClientId}`、`{yourMgmtApiAccessToken}`、および`{ownershipBoolean}`のプレースホルダーの値を、それぞれご自身のクライアントID、Management APIのアクセストークン、アプリケーションの所有権を表すブール値に置き換えてください。 -export const codeExample1 = `curl --request PATCH \ + +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/clients/%7ByourClientId%7D' \ --header 'authorization: Bearer {yourMgmtApiAccessToken}' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{ "is_first_party": "{ownershipBoolean}" }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/clients/%7ByourClientId%7D"); + --data '{ "is_first_party": "{ownershipBoolean}" }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/clients/%7ByourClientId%7D"); var request = new RestRequest(Method.PATCH); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer {yourMgmtApiAccessToken}"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{ \"is_first_party\": \"{ownershipBoolean}\" }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "is_first_party": "{ownershipBoolean}" }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -41,7 +48,7 @@ func main() { url := "https://{yourDomain}/api/v2/clients/%7ByourClientId%7D" - payload := strings.NewReader("{ \"is_first_party\": \"{ownershipBoolean}\" }") + payload := strings.NewReader("{ "is_first_party": "{ownershipBoolean}" }") req, _ := http.NewRequest("PATCH", url, payload) @@ -57,14 +64,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/clients/%7ByourClientId%7D") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/clients/%7ByourClientId%7D") .header("content-type", "application/json") .header("authorization", "Bearer {yourMgmtApiAccessToken}") .header("cache-control", "no-cache") - .body("{ \"is_first_party\": \"{ownershipBoolean}\" }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "is_first_party": "{ownershipBoolean}" }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -81,8 +92,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer {yourMgmtApiAccessToken}", @@ -108,8 +121,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/clients/%7ByourClientId%7D", @@ -119,7 +134,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{ \"is_first_party\": \"{ownershipBoolean}\" }", + CURLOPT_POSTFIELDS => "{ "is_first_party": "{ownershipBoolean}" }", CURLOPT_HTTPHEADER => [ "authorization: Bearer {yourMgmtApiAccessToken}", "cache-control: no-cache", @@ -136,12 +151,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"is_first_party\": \"{ownershipBoolean}\" }" +payload = "{ "is_first_party": "{ownershipBoolean}" }" headers = { 'content-type': "application/json", @@ -154,8 +171,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/clients/%7ByourClientId%7D", payload res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -169,11 +188,13 @@ request = Net::HTTP::Patch.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer {yourMgmtApiAccessToken}' request["cache-control"] = 'no-cache' -request.body = "{ \"is_first_party\": \"{ownershipBoolean}\" }" +request.body = "{ "is_first_party": "{ownershipBoolean}" }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -201,20 +222,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
    diff --git a/main/docs/ja-jp/get-started/applications/confidential-and-public-applications/user-consent-and-third-party-applications.mdx b/main/docs/ja-jp/get-started/applications/confidential-and-public-applications/user-consent-and-third-party-applications.mdx index c829e7cae..eac11fef0 100644 --- a/main/docs/ja-jp/get-started/applications/confidential-and-public-applications/user-consent-and-third-party-applications.mdx +++ b/main/docs/ja-jp/get-started/applications/confidential-and-public-applications/user-consent-and-third-party-applications.mdx @@ -10,6 +10,7 @@ permalink: "user-consent-and-third-party-applications" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; [OIDC](/docs/ja-jp/authenticate/protocols/openid-connect-protocol)準拠の認証パイプラインでは、リソースサーバー(APIなど)をアプリケーションとは別のエンティティとして定義することができます。そうすることで、APIを使用するアプリケーションからAPIを切り離すだけでなく、[サードパーティアプリケーション](/docs/ja-jp/get-started/applications/confidential-and-public-applications/first-party-and-third-party-applications)を定義して、外部パーティに対し、APIの内部で保護されているリソースへの安全なアクセスを許可することができます。 @@ -50,20 +51,26 @@ client_id=some_third_party_client **use_scope_descriptions_for_consent** フラグを設定するには、APIに適切な呼び出しをする必要があります。 -export const codeExample1 = `curl --request PATCH \ + +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/tenants/settings' \ --header 'authorization: Bearer API2_ACCESS_TOKEN' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{ "flags": { "use_scope_descriptions_for_consent": true } }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/tenants/settings"); + --data '{ "flags": { "use_scope_descriptions_for_consent": true } }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/tenants/settings"); var request = new RestRequest(Method.PATCH); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer API2_ACCESS_TOKEN"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{ \"flags\": { \"use_scope_descriptions_for_consent\": true } }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "flags": { "use_scope_descriptions_for_consent": true } }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -76,7 +83,7 @@ func main() { url := "https://{yourDomain}/api/v2/tenants/settings" - payload := strings.NewReader("{ \"flags\": { \"use_scope_descriptions_for_consent\": true } }") + payload := strings.NewReader("{ "flags": { "use_scope_descriptions_for_consent": true } }") req, _ := http.NewRequest("PATCH", url, payload) @@ -92,14 +99,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/tenants/settings") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/tenants/settings") .header("content-type", "application/json") .header("authorization", "Bearer API2_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ \"flags\": { \"use_scope_descriptions_for_consent\": true } }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "flags": { "use_scope_descriptions_for_consent": true } }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -116,8 +127,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer API2_ACCESS_TOKEN", @@ -143,8 +156,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/tenants/settings", @@ -154,7 +169,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{ \"flags\": { \"use_scope_descriptions_for_consent\": true } }", + CURLOPT_POSTFIELDS => "{ "flags": { "use_scope_descriptions_for_consent": true } }", CURLOPT_HTTPHEADER => [ "authorization: Bearer API2_ACCESS_TOKEN", "cache-control: no-cache", @@ -171,12 +186,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"flags\": { \"use_scope_descriptions_for_consent\": true } }" +payload = "{ "flags": { "use_scope_descriptions_for_consent": true } }" headers = { 'content-type': "application/json", @@ -189,8 +206,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/tenants/settings", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -204,11 +223,13 @@ request = Net::HTTP::Patch.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer API2_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ \"flags\": { \"use_scope_descriptions_for_consent\": true } }" +request.body = "{ "flags": { "use_scope_descriptions_for_consent": true } }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -236,20 +257,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ## 拒否された許可に対処する diff --git a/main/docs/ja-jp/get-started/applications/confidential-and-public-applications/view-application-ownership.mdx b/main/docs/ja-jp/get-started/applications/confidential-and-public-applications/view-application-ownership.mdx index c4572d4ec..5767be489 100644 --- a/main/docs/ja-jp/get-started/applications/confidential-and-public-applications/view-application-ownership.mdx +++ b/main/docs/ja-jp/get-started/applications/confidential-and-public-applications/view-application-ownership.mdx @@ -10,19 +10,26 @@ permalink: "view-application-ownership" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Auth0のManagement APIを使って、アプリケーションがAuth0にファーストパーティーアプリケーションとして登録されているのか、サードパーティーアプリケーションとして登録されているのかを確認することができます。 [クライアント取得エンドポイント](/docs/ja-jp/api/management/v2#!/Clients/get_clients_by_id)に`GET`呼び出しを行います。必ず、`{yourClientId}`と`{yourMgmtApiAccessToken}`のプレースホルダーの値を、それぞれご自身のクライアントIDとManagement APIのアクセストークンに置き換えてください。 -export const codeExample1 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/clients/%7ByourClientId%7D?fields=is_first_party&include_fields=true' \ - --header 'authorization: Bearer {yourMgmtApiAccessToken}'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/clients/%7ByourClientId%7D?fields=is_first_party&include_fields=true"); + --header 'authorization: Bearer {yourMgmtApiAccessToken}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/clients/%7ByourClientId%7D?fields=is_first_party&include_fields=true"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer {yourMgmtApiAccessToken}"); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -46,11 +53,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/clients/%7ByourClientId%7D?fields=is_first_party&include_fields=true") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/clients/%7ByourClientId%7D?fields=is_first_party&include_fields=true") .header("authorization", "Bearer {yourMgmtApiAccessToken}") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -63,8 +74,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer {yourMgmtApiAccessToken}" }; @@ -84,8 +97,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/clients/%7ByourClientId%7D?fields=is_first_party&include_fields=true", @@ -109,8 +124,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -121,8 +138,10 @@ conn.request("GET", "/{yourDomain}/api/v2/clients/%7ByourClientId%7D?fields=is_f res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -136,8 +155,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer {yourMgmtApiAccessToken}' response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer {yourMgmtApiAccessToken}"] @@ -157,20 +178,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
    diff --git a/main/docs/ja-jp/get-started/applications/dynamic-client-registration.mdx b/main/docs/ja-jp/get-started/applications/dynamic-client-registration.mdx index 2ccdee298..3ded43ccf 100644 --- a/main/docs/ja-jp/get-started/applications/dynamic-client-registration.mdx +++ b/main/docs/ja-jp/get-started/applications/dynamic-client-registration.mdx @@ -10,6 +10,7 @@ permalink: "dynamic-client-registration" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; テナントに対して、サードパーティーのアプリケーションを動的に登録することができます。この機能は、[OpenID Connect Dynamic Client Registrationの仕様](https://openid.net/specs/openid-connect-registration-1_0.html)に基づいています。 @@ -27,20 +28,26 @@ Auth0は **オープンな動的登録** をサポートしています。つま または、Management API [`/Tenant/patch_settings`](/docs/ja-jp/api/management/v2#!/Tenants/patch_settings)エンドポイントを使用してこのフラグを更新することができます。 -export const codeExample1 = `curl --request PATCH \ + +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/tenants/settings' \ --header 'authorization: Bearer API2_ACCESS_TOKEN' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{ "flags": { "enable_dynamic_client_registration": true } }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/tenants/settings"); + --data '{ "flags": { "enable_dynamic_client_registration": true } }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/tenants/settings"); var request = new RestRequest(Method.PATCH); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer API2_ACCESS_TOKEN"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{ \"flags\": { \"enable_dynamic_client_registration\": true } }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "flags": { "enable_dynamic_client_registration": true } }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -53,7 +60,7 @@ func main() { url := "https://{yourDomain}/api/v2/tenants/settings" - payload := strings.NewReader("{ \"flags\": { \"enable_dynamic_client_registration\": true } }") + payload := strings.NewReader("{ "flags": { "enable_dynamic_client_registration": true } }") req, _ := http.NewRequest("PATCH", url, payload) @@ -69,14 +76,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/tenants/settings") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/tenants/settings") .header("content-type", "application/json") .header("authorization", "Bearer API2_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ \"flags\": { \"enable_dynamic_client_registration\": true } }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "flags": { "enable_dynamic_client_registration": true } }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -93,8 +104,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer API2_ACCESS_TOKEN", @@ -120,8 +133,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/tenants/settings", @@ -131,7 +146,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{ \"flags\": { \"enable_dynamic_client_registration\": true } }", + CURLOPT_POSTFIELDS => "{ "flags": { "enable_dynamic_client_registration": true } }", CURLOPT_HTTPHEADER => [ "authorization: Bearer API2_ACCESS_TOKEN", "cache-control: no-cache", @@ -148,12 +163,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"flags\": { \"enable_dynamic_client_registration\": true } }" +payload = "{ "flags": { "enable_dynamic_client_registration": true } }" headers = { 'content-type': "application/json", @@ -166,8 +183,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/tenants/settings", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -181,11 +200,13 @@ request = Net::HTTP::Patch.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer API2_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ \"flags\": { \"enable_dynamic_client_registration\": true } }" +request.body = "{ "flags": { "enable_dynamic_client_registration": true } }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -213,20 +234,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + `update:tenant_settings`スコープを含む有効なトークンで、`API2_ACCESS_TOKEN`を更新する必要があります。詳細については、「[Management APIのアクセストークン](/docs/ja-jp/secure/tokens/access-tokens/management-api-access-tokens)」をお読みください。 @@ -240,16 +250,22 @@ Auth0でアプリケーションを動的に登録するには、HTTP `POST`メ 「`My Dynamic application`」という名前で、コールバックURLが`https://application.example.com/callback`と`https://application.example.com/callback2`に指定されているアプリケーションを作成するには、以下のスニペットを使用します。 -export const codeExample11 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oidc/register' \ --header 'content-type: application/json' \ - --data '{"client_name":"My Dynamic Application","redirect_uris": ["https://application.example.com/callback", "https://application.example.com/callback2"]}'`; -export const codeExample12 = `var client = new RestClient("https://{yourDomain}/oidc/register"); + --data '{"client_name":"My Dynamic Application","redirect_uris": ["https://application.example.com/callback", "https://application.example.com/callback2"]}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oidc/register"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\"client_name\":\"My Dynamic Application\",\"redirect_uris\": [\"https://application.example.com/callback\", \"https://application.example.com/callback2\"]}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample13 = `package main +request.AddParameter("application/json", "{"client_name":"My Dynamic Application","redirect_uris": ["https://application.example.com/callback", "https://application.example.com/callback2"]}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -262,7 +278,7 @@ func main() { url := "https://{yourDomain}/oidc/register" - payload := strings.NewReader("{\"client_name\":\"My Dynamic Application\",\"redirect_uris\": [\"https://application.example.com/callback\", \"https://application.example.com/callback2\"]}") + payload := strings.NewReader("{"client_name":"My Dynamic Application","redirect_uris": ["https://application.example.com/callback", "https://application.example.com/callback2"]}") req, _ := http.NewRequest("POST", url, payload) @@ -276,12 +292,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample14 = `HttpResponse response = Unirest.post("https://{yourDomain}/oidc/register") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oidc/register") .header("content-type", "application/json") - .body("{\"client_name\":\"My Dynamic Application\",\"redirect_uris\": [\"https://application.example.com/callback\", \"https://application.example.com/callback2\"]}") - .asString();`; -export const codeExample15 = `var axios = require("axios").default; + .body("{"client_name":"My Dynamic Application","redirect_uris": ["https://application.example.com/callback", "https://application.example.com/callback2"]}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -300,8 +320,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample16 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json" }; NSDictionary *parameters = @{ @"client_name": @"My Dynamic Application", @@ -326,8 +348,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oidc/register", CURLOPT_RETURNTRANSFER => true, @@ -336,7 +360,7 @@ CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", -CURLOPT_POSTFIELDS => "{\"client_name\":\"My Dynamic Application\",\"redirect_uris\": [\"https://application.example.com/callback\", \"https://application.example.com/callback2\"]}", +CURLOPT_POSTFIELDS => "{"client_name":"My Dynamic Application","redirect_uris": ["https://application.example.com/callback", "https://application.example.com/callback2"]}", CURLOPT_HTTPHEADER => [ "content-type: application/json" ], @@ -348,16 +372,20 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"client_name\":\"My Dynamic Application\",\"redirect_uris\": [\"https://application.example.com/callback\", \"https://application.example.com/callback2\"]}" +payload = "{"client_name":"My Dynamic Application","redirect_uris": ["https://application.example.com/callback", "https://application.example.com/callback2"]}" headers = { 'content-type': "application/json" } conn.request("POST", "/{yourDomain}/oidc/register", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' url = URI("https://{yourDomain}/oidc/register") @@ -366,10 +394,12 @@ http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["content-type"] = 'application/json' -request.body = "{\"client_name\":\"My Dynamic Application\",\"redirect_uris\": [\"https://application.example.com/callback\", \"https://application.example.com/callback2\"]}" +request.body = "{"client_name":"My Dynamic Application","redirect_uris": ["https://application.example.com/callback", "https://application.example.com/callback2"]}" response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/json"] let parameters = [ "client_name": "My Dynamic Application", @@ -391,20 +421,9 @@ let httpResponse = response as? HTTPURLResponse print(httpResponse) } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ここでは、 diff --git a/main/docs/ja-jp/get-started/applications/remove-applications.mdx b/main/docs/ja-jp/get-started/applications/remove-applications.mdx index a1bb1d692..308757dc0 100644 --- a/main/docs/ja-jp/get-started/applications/remove-applications.mdx +++ b/main/docs/ja-jp/get-started/applications/remove-applications.mdx @@ -10,6 +10,7 @@ permalink: "remove-applications" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; アプリケーションは、Auth0 Dashboardまたは管理APIを使って削除できます。この操作は、一度確定すると元に戻せません。 @@ -25,14 +26,20 @@ import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; [`/Clients/delete_clients_by_id`](/docs/ja-jp/api/management/v2#!/Clients/delete_clients_by_id)エンドポイントに`DELETE`呼び出しを行います。必ず、`YOUR_CLIENT_ID`と`MGMT_API_ACCESS_TOKEN`のプレースホルダーの値を、それぞれご自身のクライアントIDとManagement APIのアクセストークンに置き換えてください。 -export const codeExample1 = `curl --request DELETE \ + +```bash cURL +curl --request DELETE \ --url 'https://{yourDomain}/api/v2/clients/%7ByourClientId%7D' \ - --header 'authorization: Bearer {yourMgmtApiToken}'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/clients/%7ByourClientId%7D"); + --header 'authorization: Bearer {yourMgmtApiToken}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/clients/%7ByourClientId%7D"); var request = new RestRequest(Method.DELETE); request.AddHeader("authorization", "Bearer {yourMgmtApiToken}"); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -56,11 +63,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.delete("https://{yourDomain}/api/v2/clients/%7ByourClientId%7D") +} +``` +```java Java +HttpResponse response = Unirest.delete("https://{yourDomain}/api/v2/clients/%7ByourClientId%7D") .header("authorization", "Bearer {yourMgmtApiToken}") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'DELETE', @@ -72,8 +83,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer {yourMgmtApiToken}" }; @@ -93,8 +106,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/clients/%7ByourClientId%7D", @@ -118,8 +133,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -130,8 +147,10 @@ conn.request("DELETE", "/{yourDomain}/api/v2/clients/%7ByourClientId%7D", header res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -145,8 +164,10 @@ request = Net::HTTP::Delete.new(url) request["authorization"] = 'Bearer {yourMgmtApiToken}' response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer {yourMgmtApiToken}"] @@ -166,20 +187,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
    diff --git a/main/docs/ja-jp/get-started/applications/rotate-client-secret.mdx b/main/docs/ja-jp/get-started/applications/rotate-client-secret.mdx index 0a8ade970..a48c968fa 100644 --- a/main/docs/ja-jp/get-started/applications/rotate-client-secret.mdx +++ b/main/docs/ja-jp/get-started/applications/rotate-client-secret.mdx @@ -10,6 +10,7 @@ permalink: "rotate-client-secret" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; アプリケーションのクライアントシークレットは、Auth0 DashboardまたはManagement APIを使って変更できます。クライアントシークレットをローテーションするときは、新しい値で認可されたアプリケーションを更新する必要があります。 @@ -45,16 +46,22 @@ import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; 1. Management API[クライアントシークレットのローテーション](https://auth0.com/docs/api/management/v2#!/Clients/post_rotate_secret)エンドポイントを呼び出します。`YOUR_CLIENT_ID`と`MGMT_API_ACCESS_TOKEN`のプレースホルダーの値を、それぞれクライアントIDとManagement APIのアクセストークンに置き換えてください。 -export const codeExample1 = ` curl --request POST \ + +```bash cURL + curl --request POST \ --url 'https://{yourDomain}/api/v2/clients/%7ByourClientId%7D/rotate-secret' \ --header 'authorization: Bearer {yourMgmtApiAccessToken}' -`; -export const codeExample2 = ` var client = new RestClient("https://{yourDomain}/api/v2/clients/%7ByourClientId%7D/rotate-secret"); + +``` +```csharp C# + var client = new RestClient("https://{yourDomain}/api/v2/clients/%7ByourClientId%7D/rotate-secret"); var request = new RestRequest(Method.POST); request.AddHeader("authorization", "Bearer {yourMgmtApiAccessToken}"); IRestResponse response = client.Execute(request); -`; -export const codeExample3 = ` package main + +``` +```go Go + package main import ( "fmt" @@ -79,12 +86,16 @@ func main() { fmt.Println(string(body)) } -`; -export const codeExample4 = ` HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/clients/%7ByourClientId%7D/rotate-secret") + +``` +```java Java + HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/clients/%7ByourClientId%7D/rotate-secret") .header("authorization", "Bearer {yourMgmtApiAccessToken}") .asString(); -`; -export const codeExample5 = ` var axios = require("axios").default; + +``` +```javascript Node.JS + var axios = require("axios").default; var options = { method: 'POST', @@ -97,8 +108,10 @@ console.log(response.data); }).catch(function (error) { console.error(error); }); -`; -export const codeExample6 = ` #import + +``` +```obj-c Obj-C + #import NSDictionary *headers = @{ @"authorization": @"Bearer {yourMgmtApiAccessToken}" }; @@ -119,8 +132,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request } }]; [dataTask resume]; -`; -export const codeExample7 = ` $curl = curl_init(); + +``` +```php PHP + $curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/clients/%7ByourClientId%7D/rotate-secret", @@ -145,8 +160,10 @@ echo "cURL Error #:" . $err; } else { echo $response; } -`; -export const codeExample8 = ` import http.client + +``` +```python Python + import http.client conn = http.client.HTTPSConnection("") @@ -159,8 +176,10 @@ res = conn.getresponse() data = res.read() print(data.decode("utf-8")) -`; -export const codeExample9 = ` require 'uri' + +``` +```ruby Ruby + require 'uri' require 'net/http' require 'openssl' url = URI("https://{yourDomain}/api/v2/clients/%7ByourClientId%7D/rotate-secret") @@ -171,8 +190,10 @@ request = Net::HTTP::Post.new(url) request["authorization"] = 'Bearer {yourMgmtApiAccessToken}' response = http.request(request) puts response.read_body -`; -export const codeExample10 = ` import Foundation + +``` +```swift Swift + import Foundation let headers = ["authorization": "Bearer {yourMgmtApiAccessToken}"] @@ -193,20 +214,9 @@ if (error != nil) { }) dataTask.resume() -`; - - - - - - - - - - - - - + +``` +
    diff --git a/main/docs/ja-jp/get-started/applications/update-grant-types.mdx b/main/docs/ja-jp/get-started/applications/update-grant-types.mdx index 5e3ab3392..831f10f4c 100644 --- a/main/docs/ja-jp/get-started/applications/update-grant-types.mdx +++ b/main/docs/ja-jp/get-started/applications/update-grant-types.mdx @@ -10,6 +10,7 @@ permalink: "update-grant-types" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; アプリケーションの付与タイプは、Auth0 Dashboardまたは管理APIを使って変更できます。 @@ -28,20 +29,26 @@ import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; [`/Clients/patch_clients_by_id`](/docs/ja-jp/api/management/v2#!/Clients/patch_clients_by_id)エンドポイントに`PATCH`呼び出しを行います。必ず、`{yourClientId}`、`{yourManagementApiAccessToken}`、および`{grantType}`のプレースホルダーの値をそれぞれ、ご自身のクライアントID、管理APIのアクセストークン、希望する付与タイプに置き換えてください。 -export const codeExample1 = `curl --request PATCH \ + +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/clients/%7ByourClientId%7D' \ --header 'authorization: Bearer {yourMgmtApiAccessToken}' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{ "grant_types": "{grantTypes}" }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/clients/%7ByourClientId%7D"); + --data '{ "grant_types": "{grantTypes}" }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/clients/%7ByourClientId%7D"); var request = new RestRequest(Method.PATCH); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer {yourMgmtApiAccessToken}"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{ \"grant_types\": \"{grantTypes}\" }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "grant_types": "{grantTypes}" }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -54,7 +61,7 @@ func main() { url := "https://{yourDomain}/api/v2/clients/%7ByourClientId%7D" - payload := strings.NewReader("{ \"grant_types\": \"{grantTypes}\" }") + payload := strings.NewReader("{ "grant_types": "{grantTypes}" }") req, _ := http.NewRequest("PATCH", url, payload) @@ -70,14 +77,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/clients/%7ByourClientId%7D") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/clients/%7ByourClientId%7D") .header("content-type", "application/json") .header("authorization", "Bearer {yourMgmtApiAccessToken}") .header("cache-control", "no-cache") - .body("{ \"grant_types\": \"{grantTypes}\" }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "grant_types": "{grantTypes}" }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -94,8 +105,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer {yourMgmtApiAccessToken}", @@ -121,8 +134,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/clients/%7ByourClientId%7D", @@ -132,7 +147,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{ \"grant_types\": \"{grantTypes}\" }", + CURLOPT_POSTFIELDS => "{ "grant_types": "{grantTypes}" }", CURLOPT_HTTPHEADER => [ "authorization: Bearer {yourMgmtApiAccessToken}", "cache-control: no-cache", @@ -149,12 +164,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"grant_types\": \"{grantTypes}\" }" +payload = "{ "grant_types": "{grantTypes}" }" headers = { 'content-type': "application/json", @@ -167,8 +184,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/clients/%7ByourClientId%7D", payload res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -182,11 +201,13 @@ request = Net::HTTP::Patch.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer {yourMgmtApiAccessToken}' request["cache-control"] = 'no-cache' -request.body = "{ \"grant_types\": \"{grantTypes}\" }" +request.body = "{ "grant_types": "{grantTypes}" }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -214,20 +235,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
    diff --git a/main/docs/ja-jp/get-started/architecture-scenarios/mobile-api/part-3.mdx b/main/docs/ja-jp/get-started/architecture-scenarios/mobile-api/part-3.mdx index c3278e324..c4adf3198 100644 --- a/main/docs/ja-jp/get-started/architecture-scenarios/mobile-api/part-3.mdx +++ b/main/docs/ja-jp/get-started/architecture-scenarios/mobile-api/part-3.mdx @@ -10,6 +10,7 @@ permalink: "part-3" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; このセクションでは、当社シナリオでAPIを実装する方法を説明します。 @@ -153,20 +154,26 @@ Location: https://{yourDomain}/callback?code=AUTHORIZATION_CODE`; 次に、応答の`認可コード`をAPIを呼び出すのに使用するアクセストークンと交換します。以下のデータを含めて、[トークン URL](/docs/ja-jp/api/authentication#authorization-code-pkce-)への`POST`要求を実行します。 -export const codeExample3 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=authorization_code \ --data 'client_id={yourClientId}' \ --data code_verified=YOUR_GENERATED_CODE_VERIFIER \ --data code=YOUR_AUTHORIZATION_CODE \ - --data 'redirect_uri=https://{https://yourApp/callback}'`; -export const codeExample4 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data 'redirect_uri=https://{https://yourApp/callback}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=authorization_code&client_id={yourClientId}&code_verified=YOUR_GENERATED_CODE_VERIFIER&code=YOUR_AUTHORIZATION_CODE&redirect_uri=https%3A%2F%2F{https://yourApp/callback}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample5 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -193,12 +200,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample6 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=authorization_code&client_id={yourClientId}&code_verified=YOUR_GENERATED_CODE_VERIFIER&code=YOUR_AUTHORIZATION_CODE&redirect_uri=https%3A%2F%2F{https://yourApp/callback}") - .asString();`; -export const codeExample7 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -217,8 +228,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample8 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -245,8 +258,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample9 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -271,8 +286,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample10 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -285,8 +302,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample11 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -301,8 +320,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=authorization_code&client_id={yourClientId}&code_verified=YOUR_GENERATED_CODE_VERIFIER&code=YOUR_AUTHORIZATION_CODE&redirect_uri=https%3A%2F%2F{https://yourApp/callback}" response = http.request(request) -puts response.read_body`; -export const codeExample12 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -329,20 +350,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
    @@ -443,14 +453,20 @@ APIから安全なリソースにアクセスするには、認証されたユ 要求には以下を含める必要があります。 -export const codeExample13 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ - --header 'content-type: application/x-www-form-urlencoded'`; -export const codeExample14 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --header 'content-type: application/x-www-form-urlencoded' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); -IRestResponse response = client.Execute(request);`; -export const codeExample15 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -474,11 +490,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample16 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") - .asString();`; -export const codeExample17 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -490,8 +510,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample18 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -514,8 +536,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample19 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -539,8 +563,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample20 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -551,8 +577,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", headers=headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample21 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -566,8 +594,10 @@ request = Net::HTTP::Post.new(url) request["content-type"] = 'application/x-www-form-urlencoded' response = http.request(request) -puts response.read_body`; -export const codeExample22 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -590,20 +620,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
    diff --git a/main/docs/ja-jp/get-started/authentication-and-authorization-flow/authorization-code-flow-with-pkce/add-login-using-the-authorization-code-flow-with-pkce.mdx b/main/docs/ja-jp/get-started/authentication-and-authorization-flow/authorization-code-flow-with-pkce/add-login-using-the-authorization-code-flow-with-pkce.mdx index 21e8a5f49..2583db65e 100644 --- a/main/docs/ja-jp/get-started/authentication-and-authorization-flow/authorization-code-flow-with-pkce/add-login-using-the-authorization-code-flow-with-pkce.mdx +++ b/main/docs/ja-jp/get-started/authentication-and-authorization-flow/authorization-code-flow-with-pkce/add-login-using-the-authorization-code-flow-with-pkce.mdx @@ -10,6 +10,7 @@ permalink: "add-login-using-the-authorization-code-flow-with-pkce" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; ネイティブやモバイル、シングルページのアプリケーションにログインを追加するのに、PKCEを使った認可コードフローを活用することができます。フローの仕組みやメリットについては、「[Proof Key for Code Exchange(PKCE)を使った認可コードフロー](/docs/ja-jp/get-started/authentication-and-authorization-flow/authorization-code-flow-with-pkce)」をお読みください。ネイティブやモバイル、シングルページのアプリケーションからAPIを呼び出す方法については、「[PKCEを使った認可コードフローで独自のAPIを呼び出す](/docs/ja-jp/get-started/authentication-and-authorization-flow/authorization-code-flow-with-pkce/call-your-api-using-the-authorization-code-flow-with-pkce)」をお読みください。 @@ -272,20 +273,26 @@ Location: {yourCallbackUrl}?code={authorizationCode}&state=xyzABC123 ### トークンURLへのPOSTの例 -export const codeExample3 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=authorization_code \ --data 'client_id={yourClientId}' \ --data 'code_verifier={yourGeneratedCodeVerifier}' \ --data 'code={yourAuthorizationCode}' \ - --data 'redirect_uri={https://yourApp/callback}'`; -export const codeExample4 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data 'redirect_uri={https://yourApp/callback}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=authorization_code&client_id={yourClientId}&code_verifier=%7ByourGeneratedCodeVerifier%7D&code=%7ByourAuthorizationCode%7D&redirect_uri={https://yourApp/callback}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample5 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -312,12 +319,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample6 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=authorization_code&client_id={yourClientId}&code_verifier=%7ByourGeneratedCodeVerifier%7D&code=%7ByourAuthorizationCode%7D&redirect_uri={https://yourApp/callback}") - .asString();`; -export const codeExample7 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -336,8 +347,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample8 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -364,8 +377,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample9 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -390,8 +405,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample10 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -404,8 +421,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample11 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -420,8 +439,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=authorization_code&client_id={yourClientId}&code_verifier=%7ByourGeneratedCodeVerifier%7D&code=%7ByourAuthorizationCode%7D&redirect_uri={https://yourApp/callback}" response = http.request(request) -puts response.read_body`; -export const codeExample12 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -448,20 +469,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ### パラメーター diff --git a/main/docs/ja-jp/get-started/authentication-and-authorization-flow/authorization-code-flow-with-pkce/call-your-api-using-the-authorization-code-flow-with-pkce.mdx b/main/docs/ja-jp/get-started/authentication-and-authorization-flow/authorization-code-flow-with-pkce/call-your-api-using-the-authorization-code-flow-with-pkce.mdx index e04faaed7..d2eee4e92 100644 --- a/main/docs/ja-jp/get-started/authentication-and-authorization-flow/authorization-code-flow-with-pkce/call-your-api-using-the-authorization-code-flow-with-pkce.mdx +++ b/main/docs/ja-jp/get-started/authentication-and-authorization-flow/authorization-code-flow-with-pkce/call-your-api-using-the-authorization-code-flow-with-pkce.mdx @@ -10,6 +10,7 @@ permalink: "call-your-api-using-the-authorization-code-flow-with-pkce" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; @@ -295,20 +296,26 @@ Location: {yourCallbackUrl}?code={authorizationCode}&state=xyzABC123 #### トークンURLへのPOSTの例 -export const codeExample3 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=authorization_code \ --data 'client_id={yourClientId}' \ --data 'code_verifier={yourGeneratedCodeVerifier}' \ --data 'code={yourAuthorizationCode}' \ - --data 'redirect_uri={https://yourApp/callback}'`; -export const codeExample4 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data 'redirect_uri={https://yourApp/callback}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=authorization_code&client_id={yourClientId}&code_verifier=%7ByourGeneratedCodeVerifier%7D&code=%7ByourAuthorizationCode%7D&redirect_uri={https://yourApp/callback}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample5 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -335,12 +342,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample6 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=authorization_code&client_id={yourClientId}&code_verifier=%7ByourGeneratedCodeVerifier%7D&code=%7ByourAuthorizationCode%7D&redirect_uri={https://yourApp/callback}") - .asString();`; -export const codeExample7 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -359,8 +370,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample8 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -387,8 +400,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample9 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -413,8 +428,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample10 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -427,8 +444,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample11 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -443,8 +462,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=authorization_code&client_id={yourClientId}&code_verifier=%7ByourGeneratedCodeVerifier%7D&code=%7ByourAuthorizationCode%7D&redirect_uri={https://yourApp/callback}" response = http.request(request) -puts response.read_body`; -export const codeExample12 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -471,20 +492,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ##### パラメーター @@ -554,7 +564,7 @@ dataTask.resume()`; ネイティブ/モバイルアプリケーションからAPIを呼び出すには、アプリケーションは、取得したアクセストークンをBearerトークンとしてHTTP要求の認証ヘッダーで渡さなければなりません。 - + ```bash cURL lines curl --request GET \ --url https://myapi.com/api \ @@ -734,7 +744,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + ### リフレッシュトークン @@ -749,18 +759,24 @@ dataTask.resume() #### トークンURLへのPOSTの例 -export const codeExample13 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=refresh_token \ --data 'client_id={yourClientId}' \ - --data 'refresh_token={yourRefreshToken}'`; -export const codeExample14 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data 'refresh_token={yourRefreshToken}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=refresh_token&client_id={yourClientId}&refresh_token=%7ByourRefreshToken%7D", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample15 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -787,12 +803,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample16 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=refresh_token&client_id={yourClientId}&refresh_token=%7ByourRefreshToken%7D") - .asString();`; -export const codeExample17 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -809,8 +829,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample18 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -835,8 +857,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample19 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -861,8 +885,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample20 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -875,8 +901,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample21 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -891,8 +919,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=refresh_token&client_id={yourClientId}&refresh_token=%7ByourRefreshToken%7D" response = http.request(request) -puts response.read_body`; -export const codeExample22 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -917,20 +947,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ##### パラメーター diff --git a/main/docs/ja-jp/get-started/authentication-and-authorization-flow/authorization-code-flow/add-login-auth-code-flow.mdx b/main/docs/ja-jp/get-started/authentication-and-authorization-flow/authorization-code-flow/add-login-auth-code-flow.mdx index 094dfe09a..4b61b1ed4 100644 --- a/main/docs/ja-jp/get-started/authentication-and-authorization-flow/authorization-code-flow/add-login-auth-code-flow.mdx +++ b/main/docs/ja-jp/get-started/authentication-and-authorization-flow/authorization-code-flow/add-login-auth-code-flow.mdx @@ -10,6 +10,7 @@ permalink: "add-login-auth-code-flow" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; 認可コードフローを使用すると、ログインを通常のWebアプリケーションに追加することができます。フローの仕組みと使用すべき理由については、[認可コードフロー](/docs/ja-jp/get-started/authentication-and-authorization-flow/authorization-code-flow)をお読みください。通常のWebアプリからAPIを呼び出すには、[認可コードフローを使用してAPIを呼び出す](/docs/ja-jp/get-started/authentication-and-authorization-flow/authorization-code-flow/call-your-api-using-the-authorization-code-flow)をお読みください。 @@ -127,20 +128,26 @@ Location: {https://yourApp/callback}?code={authorizationCode}&state=xyzABC123 ### トークンURLへのPOSTの例 -export const codeExample3 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=authorization_code \ --data 'client_id={yourClientId}' \ --data 'client_secret={yourClientSecret}' \ --data 'code=yourAuthorizationCode}' \ - --data 'redirect_uri={https://yourApp/callback}'`; -export const codeExample4 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data 'redirect_uri={https://yourApp/callback}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=authorization_code&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&code=yourAuthorizationCode%7D&redirect_uri={https://yourApp/callback}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample5 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -167,12 +174,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample6 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=authorization_code&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&code=yourAuthorizationCode%7D&redirect_uri={https://yourApp/callback}") - .asString();`; -export const codeExample7 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -191,8 +202,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample8 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -219,8 +232,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample9 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -245,8 +260,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample10 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -259,8 +276,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample11 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -275,8 +294,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=authorization_code&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&code=yourAuthorizationCode%7D&redirect_uri={https://yourApp/callback}" response = http.request(request) -puts response.read_body`; -export const codeExample12 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -303,20 +324,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ### パラメーター diff --git a/main/docs/ja-jp/get-started/authentication-and-authorization-flow/authorization-code-flow/call-your-api-using-the-authorization-code-flow.mdx b/main/docs/ja-jp/get-started/authentication-and-authorization-flow/authorization-code-flow/call-your-api-using-the-authorization-code-flow.mdx index 8a678e7cc..c3427fd01 100644 --- a/main/docs/ja-jp/get-started/authentication-and-authorization-flow/authorization-code-flow/call-your-api-using-the-authorization-code-flow.mdx +++ b/main/docs/ja-jp/get-started/authentication-and-authorization-flow/authorization-code-flow/call-your-api-using-the-authorization-code-flow.mdx @@ -10,6 +10,7 @@ permalink: "call-your-api-using-the-authorization-code-flow" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; @@ -113,20 +114,26 @@ Location: {https://yourApp/callback}?code={authorizationCode}&state=xyzABC123 #### トークンURLへのPOSTの例 -export const codeExample3 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=authorization_code \ --data 'client_id={yourClientId}' \ --data 'client_secret={yourClientSecret}' \ --data 'code=yourAuthorizationCode}' \ - --data 'redirect_uri={https://yourApp/callback}'`; -export const codeExample4 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data 'redirect_uri={https://yourApp/callback}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=authorization_code&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&code=yourAuthorizationCode%7D&redirect_uri={https://yourApp/callback}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample5 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -153,12 +160,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample6 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=authorization_code&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&code=yourAuthorizationCode%7D&redirect_uri={https://yourApp/callback}") - .asString();`; -export const codeExample7 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -177,8 +188,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample8 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -205,8 +218,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample9 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -231,16 +246,20 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample10 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") payload = "grant_type=authorization_code&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&code=yourAuthorizationCode%7D&redirect_uri={https://yourApp/callback}" headers = { 'content-type': "application/x-www-form-urlencoded" } conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample11 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -255,8 +274,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=authorization_code&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&code=yourAuthorizationCode%7D&redirect_uri={https://yourApp/callback}" response = http.request(request) -puts response.read_body`; -export const codeExample12 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -283,20 +304,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ##### パラメーター @@ -367,7 +377,7 @@ dataTask.resume()`; 通常のWebアプリケーションからAPIを呼び出すには、アプリケーションは、取得したアクセストークンをベアラートークンとしてHTTP要求の認可ヘッダーで渡さなければなりません。 - + ```bash cURL lines curl --request GET \ --url https://myapi.com/api \ @@ -546,7 +556,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + @@ -563,18 +573,24 @@ dataTask.resume() ##### トークンURLへのPOSTの例 -export const codeExample13 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=refresh_token \ --data 'client_id={yourClientId}' \ - --data 'refresh_token={yourRefreshToken}'`; -export const codeExample14 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data 'refresh_token={yourRefreshToken}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=refresh_token&client_id={yourClientId}&refresh_token=%7ByourRefreshToken%7D", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample15 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -601,12 +617,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample16 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=refresh_token&client_id={yourClientId}&refresh_token=%7ByourRefreshToken%7D") - .asString();`; -export const codeExample17 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -623,8 +643,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample18 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -649,8 +671,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample19 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -675,16 +699,20 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample20 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") payload = "grant_type=refresh_token&client_id={yourClientId}&refresh_token=%7ByourRefreshToken%7D" headers = { 'content-type': "application/x-www-form-urlencoded" } conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample21 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' url = URI("https://{yourDomain}/oauth/token") @@ -695,8 +723,10 @@ request = Net::HTTP::Post.new(url) request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=refresh_token&client_id={yourClientId}&refresh_token=%7ByourRefreshToken%7D" response = http.request(request) -puts response.read_body`; -export const codeExample22 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -721,20 +751,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ###### パラメーター diff --git a/main/docs/ja-jp/get-started/authentication-and-authorization-flow/client-credentials-flow/call-your-api-using-the-client-credentials-flow.mdx b/main/docs/ja-jp/get-started/authentication-and-authorization-flow/client-credentials-flow/call-your-api-using-the-client-credentials-flow.mdx index a7b05fdc9..8ceaaa592 100644 --- a/main/docs/ja-jp/get-started/authentication-and-authorization-flow/client-credentials-flow/call-your-api-using-the-client-credentials-flow.mdx +++ b/main/docs/ja-jp/get-started/authentication-and-authorization-flow/client-credentials-flow/call-your-api-using-the-client-credentials-flow.mdx @@ -10,6 +10,7 @@ permalink: "call-your-api-using-the-client-credentials-flow" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; @@ -47,19 +48,25 @@ APIにアクセスするには、そのAPIのアクセストークンを取得 #### トークンURLに対するPOSTの例 -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=client_credentials \ --data client_id=YOUR_CLIENT_ID \ --data client_secret=YOUR_CLIENT_SECRET \ - --data audience=YOUR_API_IDENTIFIER`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data audience=YOUR_API_IDENTIFIER +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&audience=YOUR_API_IDENTIFIER", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -86,12 +93,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&audience=YOUR_API_IDENTIFIER") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -109,8 +120,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -137,8 +150,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request } }]; [dataTask resume]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -163,8 +178,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -177,8 +194,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -193,8 +212,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&audience=YOUR_API_IDENTIFIER" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -220,20 +241,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ##### パラメーター @@ -289,7 +299,7 @@ dataTask.resume()`; M2MアプリケーションからAPIを呼び出すには、アプリケーションは、取得したアクセストークンをベアラートークンとしてHTTP要求の認可ヘッダーで渡さなければなりません。 - + ```bash cURL lines curl --request GET \ --url https://myapi.com/api \ @@ -469,7 +479,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + ### サンプルユースケース diff --git a/main/docs/ja-jp/get-started/authentication-and-authorization-flow/client-credentials-flow/customize-tokens-using-hooks-with-client-credentials-flow.mdx b/main/docs/ja-jp/get-started/authentication-and-authorization-flow/client-credentials-flow/customize-tokens-using-hooks-with-client-credentials-flow.mdx index d0ca58798..99fa5aec5 100644 --- a/main/docs/ja-jp/get-started/authentication-and-authorization-flow/client-credentials-flow/customize-tokens-using-hooks-with-client-credentials-flow.mdx +++ b/main/docs/ja-jp/get-started/authentication-and-authorization-flow/client-credentials-flow/customize-tokens-using-hooks-with-client-credentials-flow.mdx @@ -10,6 +10,7 @@ permalink: "customize-tokens-using-hooks-with-client-credentials-flow" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; @@ -94,19 +95,25 @@ Auth0は、プロファイル情報を[OpenID Connect(OIDC)仕様](https://o トークンを取得するには、`POST`呼び出しを[クライアントの資格情報フローエンドポイント](/docs/api/authentication#client-credentials-flow)に対して行います。CLIENT_ID、CLIENT_SECRET、API_IDENTIFIERの各プレースホルダーの値をアプリケーションのクライアントID、アプリケーションのクライアントシークレット、APIの識別子にそれぞれ、必ず置き換えてください。クライアントIDとクライアントシークレットは[アプリケーション](https://manage.auth0.com/#/applications)設定、API識別子は[API](https://manage.auth0.com/#/apis)設定でそれぞれ確認できます。 -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=client_credentials \ --data 'client_id={yourClientId}' \ --data client_secret=YOUR_CLIENT_SECRET \ ---data audience=YOUR_API_IDENTIFIER`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/oauth/token"); +--data audience=YOUR_API_IDENTIFIER +``` lines +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=client_credentials&client_id={yourClientId}&client_secret=YOUR_CLIENT_SECRET&audience=YOUR_API_IDENTIFIER", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" "strings" @@ -123,12 +130,16 @@ defer res.Body.Close() body, _ := ioutil.ReadAll(res.Body) fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` lines +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=client_credentials&client_id={yourClientId}&client_secret=YOUR_CLIENT_SECRET&audience=YOUR_API_IDENTIFIER") -.asString();`; -export const codeExample5 = `var axios = require("axios").default; +.asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', url: 'https://{yourDomain}/oauth/token', @@ -144,8 +155,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` lines +```obj-c Obj-C +#import NSDictionary \*headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; NSMutableData \*postData = [[NSMutableData alloc] initWithData:[@"grant_type=client_credentials" dataUsingEncoding:NSUTF8StringEncoding]]; [postData appendData:[@"&client_id={yourClientId}" dataUsingEncoding:NSUTF8StringEncoding]]; @@ -167,8 +180,10 @@ NSHTTPURLResponse \*httpResponse = (NSHTTPURLResponse \*) response; NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", CURLOPT_RETURNTRANSFER => true, @@ -189,16 +204,20 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` lines +```python Python +import http.client conn = http.client.HTTPSConnection("") payload = "grant_type=client_credentials&client_id={yourClientId}&client_secret=YOUR_CLIENT_SECRET&audience=YOUR_API_IDENTIFIER" headers = { 'content-type': "application/x-www-form-urlencoded" } conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' url = URI("https://{yourDomain}/oauth/token") @@ -209,8 +228,10 @@ request = Net::HTTP::Post.new(url) request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=client_credentials&client_id={yourClientId}&client_secret=YOUR_CLIENT_SECRET&audience=YOUR_API_IDENTIFIER" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` lines +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] let postData = NSMutableData(data: "grant_type=client_credentials".data(using: String.Encoding.utf8)!) postData.append("&client_id={yourClientId}".data(using: String.Encoding.utf8)!) @@ -231,20 +252,9 @@ let httpResponse = response as? HTTPURLResponse print(httpResponse) } }) -dataTask.resume()`; - - - lines - - lines - - lines - - lines - - lines - - +dataTask.resume() +``` + 正常な応答に含まれるもの: diff --git a/main/docs/ja-jp/get-started/authentication-and-authorization-flow/device-authorization-flow/call-your-api-using-the-device-authorization-flow.mdx b/main/docs/ja-jp/get-started/authentication-and-authorization-flow/device-authorization-flow/call-your-api-using-the-device-authorization-flow.mdx index 8c99b9ef9..9bc0e5a62 100644 --- a/main/docs/ja-jp/get-started/authentication-and-authorization-flow/device-authorization-flow/call-your-api-using-the-device-authorization-flow.mdx +++ b/main/docs/ja-jp/get-started/authentication-and-authorization-flow/device-authorization-flow/call-your-api-using-the-device-authorization-flow.mdx @@ -10,6 +10,7 @@ permalink: "call-your-api-using-the-device-authorization-flow" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; @@ -61,18 +62,24 @@ Auth0を使用すると、以下を使ってアプリでデバイス認可フロ #### デバイスコードに対するPOSTの例URL -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/device/code' \ --header 'content-type: application/x-www-form-urlencoded' \ --data 'client_id={yourClientId}' \ --data 'scope={scope}' \ - --data 'audience={audience}'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/oauth/device/code"); + --data 'audience={audience}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/device/code"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "client_id={yourClientId}&scope=%7Bscope%7D&audience=%7Baudience%7D", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -99,12 +106,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/device/code") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/device/code") .header("content-type", "application/x-www-form-urlencoded") .body("client_id={yourClientId}&scope=%7Bscope%7D&audience=%7Baudience%7D") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -117,8 +128,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -143,8 +156,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/device/code", @@ -169,8 +184,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -183,8 +200,10 @@ conn.request("POST", "/{yourDomain}/oauth/device/code", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -199,8 +218,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "client_id={yourClientId}&scope=%7Bscope%7D&audience=%7Baudience%7D" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -225,20 +246,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ##### デバイスコードのパラメーター @@ -340,18 +350,24 @@ CLIをビルドする際は、この手順をスキップし、`verification_uri #### トークンURLに対するトークンPOST要求の例 -export const codeExample11 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=urn:ietf:params:oauth:grant-type:device_code \ --data 'device_code={yourDeviceCode}' \ - --data 'client_id={yourClientId}'`; -export const codeExample12 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data 'client_id={yourClientId}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Adevice_code&device_code=%7ByourDeviceCode%7D&client_id={yourClientId}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample13 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -378,12 +394,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample14 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Adevice_code&device_code=%7ByourDeviceCode%7D&client_id={yourClientId}") - .asString();`; -export const codeExample15 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -400,8 +420,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample16 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -426,8 +448,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -452,8 +476,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -466,8 +492,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -482,8 +510,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Adevice_code&device_code=%7ByourDeviceCode%7D&client_id={yourClientId}" response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -508,20 +538,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ##### トークン要求のパラメーター @@ -674,7 +693,7 @@ IDトークンにはデコードして抽出するべきユーザー情報が含 APIを呼び出すには、アプリケーションは、取得したアクセストークンをベアラートークンとしてHTTP要求の認証ヘッダーで渡さなければなりません。 - + ```bash cURL lines curl --request GET \ --url https://myapi.com/api \ @@ -854,7 +873,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + ### リフレッシュトークン @@ -869,19 +888,25 @@ dataTask.resume() #### トークンURLに対するリフレッシュトークンのPOST要求の例 -export const codeExample21 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=refresh_token \ --data 'client_id={yourClientId}' \ --data 'client_secret={yourClientSecret}' \ - --data 'refresh_token={yourRefreshToken}'`; -export const codeExample22 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data 'refresh_token={yourRefreshToken}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=refresh_token&client_id={yourClientId}&client_secret={yourClientSecret}&refresh_token=%7ByourRefreshToken%7D", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample23 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -908,12 +933,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample24 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=refresh_token&client_id={yourClientId}&client_secret={yourClientSecret}&refresh_token=%7ByourRefreshToken%7D") - .asString();`; -export const codeExample25 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -931,8 +960,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample26 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -958,8 +989,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample27 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -984,8 +1017,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample28 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -998,8 +1033,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample29 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -1014,8 +1051,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=refresh_token&client_id={yourClientId}&client_secret={yourClientSecret}&refresh_token=%7ByourRefreshToken%7D" response = http.request(request) -puts response.read_body`; -export const codeExample30 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -1041,20 +1080,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ##### リフレッシュトークン要求パラメーター diff --git a/main/docs/ja-jp/get-started/authentication-and-authorization-flow/hybrid-flow/call-api-hybrid-flow.mdx b/main/docs/ja-jp/get-started/authentication-and-authorization-flow/hybrid-flow/call-api-hybrid-flow.mdx index a6914a379..cd60d796a 100644 --- a/main/docs/ja-jp/get-started/authentication-and-authorization-flow/hybrid-flow/call-api-hybrid-flow.mdx +++ b/main/docs/ja-jp/get-started/authentication-and-authorization-flow/hybrid-flow/call-api-hybrid-flow.mdx @@ -10,6 +10,7 @@ permalink: "call-api-hybrid-flow" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; @@ -216,20 +217,26 @@ IDトークンをデコードして解析すると、`c_hash`という追加の #### トークンURLへのPOSTの例 -export const codeExample3 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=authorization_code \ --data 'client_id={yourClientId}' \ --data 'client_secret={yourClientSecret}' \ --data 'code=yourAuthorizationCode}' \ - --data 'redirect_uri={https://yourApp/callback}'`; -export const codeExample4 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data 'redirect_uri={https://yourApp/callback}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=authorization_code&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&code=yourAuthorizationCode%7D&redirect_uri={https://yourApp/callback}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample5 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -256,12 +263,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample6 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=authorization_code&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&code=yourAuthorizationCode%7D&redirect_uri={https://yourApp/callback}") - .asString();`; -export const codeExample7 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -280,8 +291,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample8 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -308,8 +321,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample9 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -334,8 +349,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample10 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -348,8 +365,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample11 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -364,8 +383,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=authorization_code&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&code=yourAuthorizationCode%7D&redirect_uri={https://yourApp/callback}" response = http.request(request) -puts response.read_body`; -export const codeExample12 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -392,20 +413,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ##### パラメーター @@ -474,7 +484,7 @@ dataTask.resume()`; 通常のWebアプリケーション(または同様のケースで、アプリケーションの資格情報を安全に保存できる場合)からAPIを呼び出すには、アプリケーションは、取得したアクセストークンをベアラートークンとしてHTTP要求の認可ヘッダーで渡さなければなりません。 - + ```bash cURL lines curl --request GET \ --url https://myapi.com/api \ @@ -654,7 +664,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + ### リフレッシュトークン @@ -669,18 +679,24 @@ dataTask.resume() #### トークンURLへのPOSTの例 -export const codeExample13 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=refresh_token \ --data 'client_id={yourClientId}' \ - --data 'refresh_token={yourRefreshToken}'`; -export const codeExample14 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data 'refresh_token={yourRefreshToken}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=refresh_token&client_id={yourClientId}&refresh_token=%7ByourRefreshToken%7D", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample15 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -707,12 +723,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample16 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=refresh_token&client_id={yourClientId}&refresh_token=%7ByourRefreshToken%7D") - .asString();`; -export const codeExample17 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -729,8 +749,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample18 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -755,8 +777,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample19 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -781,8 +805,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample20 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -795,8 +821,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample21 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -811,8 +839,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=refresh_token&client_id={yourClientId}&refresh_token=%7ByourRefreshToken%7D" response = http.request(request) -puts response.read_body`; -export const codeExample22 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -837,20 +867,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ##### パラメーター diff --git a/main/docs/ja-jp/get-started/authentication-and-authorization-flow/resource-owner-password-flow/call-your-api-using-resource-owner-password-flow.mdx b/main/docs/ja-jp/get-started/authentication-and-authorization-flow/resource-owner-password-flow/call-your-api-using-resource-owner-password-flow.mdx index b00c845ab..8ad343aa2 100644 --- a/main/docs/ja-jp/get-started/authentication-and-authorization-flow/resource-owner-password-flow/call-your-api-using-resource-owner-password-flow.mdx +++ b/main/docs/ja-jp/get-started/authentication-and-authorization-flow/resource-owner-password-flow/call-your-api-using-resource-owner-password-flow.mdx @@ -10,6 +10,7 @@ permalink: "call-your-api-using-resource-owner-password-flow" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; @@ -74,7 +75,9 @@ APIを呼び出すには、まずユーザーの資格情報を取得しなけ #### トークンURLへのPOSTの例 -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=password \ @@ -83,13 +86,17 @@ export const codeExample1 = `curl --request POST \ --data 'audience={yourApiIdentifier}' \ --data scope=read:sample \ --data 'client_id={yourClientId}' \ - --data 'client_secret={yourClientSecret}'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data 'client_secret={yourClientSecret}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=password&username=%7Busername%7D&password=%7Bpassword%7D&audience=%7ByourApiIdentifier%7D&scope=read%3Asample&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -116,12 +123,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=password&username=%7Busername%7D&password=%7Bpassword%7D&audience=%7ByourApiIdentifier%7D&scope=read%3Asample&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -142,8 +153,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -172,8 +185,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -198,8 +213,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -212,8 +229,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -228,8 +247,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=password&username=%7Busername%7D&password=%7Bpassword%7D&audience=%7ByourApiIdentifier%7D&scope=read%3Asample&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -258,20 +279,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ##### パラメーター @@ -363,7 +373,7 @@ dataTask.resume()`; APIを呼び出すには、アプリケーションは、取得したアクセストークンをベアラートークンとしてHTTP要求の認証ヘッダーで渡さなければなりません。 - + ```bash cURL lines curl --request GET \ --url https://myapi.com/api \ @@ -543,7 +553,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + ### リフレッシュトークン @@ -558,18 +568,24 @@ dataTask.resume() #### トークンURLへのPOSTの例 -export const codeExample11 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=refresh_token \ --data 'client_id={yourClientId}' \ - --data 'refresh_token={yourRefreshToken}'`; -export const codeExample12 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data 'refresh_token={yourRefreshToken}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=refresh_token&client_id={yourClientId}&refresh_token=%7ByourRefreshToken%7D", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample13 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -596,12 +612,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample14 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=refresh_token&client_id={yourClientId}&refresh_token=%7ByourRefreshToken%7D") - .asString();`; -export const codeExample15 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -618,8 +638,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample16 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -644,8 +666,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -670,8 +694,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -684,8 +710,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -700,8 +728,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=refresh_token&client_id={yourClientId}&refresh_token=%7ByourRefreshToken%7D" response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -726,20 +756,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ##### パラメーター diff --git a/main/docs/ja-jp/get-started/onboarding/self-service-m2m.mdx b/main/docs/ja-jp/get-started/onboarding/self-service-m2m.mdx index aa5146481..3dcaedc6f 100644 --- a/main/docs/ja-jp/get-started/onboarding/self-service-m2m.mdx +++ b/main/docs/ja-jp/get-started/onboarding/self-service-m2m.mdx @@ -10,6 +10,7 @@ permalink: "self-service-m2m" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; ビジネスケースがAPIやバックエンドサーバーなどの非インタラクティブなオーディエンスにサービスを提供する場合は、マシンツーマシン(M2M)構成でオンボードします。 @@ -235,19 +236,25 @@ Auth0は、資格情報としてクライアントIDとクライアントシー `/oauth/token`エンドポイントへの要求は、次のサンプルのようになります。 -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=client_credentials \ --data client_id=YOUR_CLIENT_ID \ --data client_secret=YOUR_CLIENT_SECRET \ - --data audience=YOUR_API_IDENTIFIER`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data audience=YOUR_API_IDENTIFIER +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&audience=YOUR_API_IDENTIFIER", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -274,12 +281,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&audience=YOUR_API_IDENTIFIER") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -297,8 +308,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -324,8 +337,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -350,8 +365,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -364,8 +381,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -380,8 +399,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&audience=YOUR_API_IDENTIFIER" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -407,20 +428,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + 応答は、次のサンプルのようになります。 diff --git a/main/docs/ja-jp/get-started/tenant-settings/signing-keys/revoke-signing-keys.mdx b/main/docs/ja-jp/get-started/tenant-settings/signing-keys/revoke-signing-keys.mdx index c8eaef459..64047ca9d 100644 --- a/main/docs/ja-jp/get-started/tenant-settings/signing-keys/revoke-signing-keys.mdx +++ b/main/docs/ja-jp/get-started/tenant-settings/signing-keys/revoke-signing-keys.mdx @@ -10,6 +10,7 @@ permalink: "revoke-signing-keys" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Auth0 DashboardManagement APIを使って、テナントのアプリケーションの署名鍵を取り消すことができます。署名鍵は、アプリケーションやAPIに送信されたIDトークン、アクセストークン、SAMLアサーション、およびWS-Fedアサーションを署名するのに使用されます。詳細については、「[署名鍵](/docs/ja-jp/get-started/tenant-settings/signing-keys)」をお読みください。 @@ -49,16 +50,22 @@ import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; 1. 署名鍵のリストを取得するには、[全アプリケーション署名鍵の取得](/docs/ja-jp/api/management/v2#!/Keys/get_signing_keys)エンドポイントに`GET`呼び出しを行います。 2. [鍵のIDでアプリケーションの署名鍵取り消し](/docs/ja-jp/api/management/v2#!/Keys/put_signing_keys)エンドポイントに`PUT`呼び出しを行います。`{yourKeyId}`と`{yourMgmtApiAccessToken}`のプレースホルダーの値を、それぞれ署名鍵IDとManagement APIのアクセストークンに置き換えてください。 -export const codeExample1 = ` curl --request PUT \ + +```bash cURL + curl --request PUT \ --url 'https://{yourDomain}/api/v2/keys/signing/%7ByourKeyId%7D/revoke' \ --header 'authorization: Bearer {yourMgmtApiAccessToken}' -`; -export const codeExample2 = ` var client = new RestClient("https://{yourDomain}/api/v2/keys/signing/%7ByourKeyId%7D/revoke"); + +``` +```csharp C# + var client = new RestClient("https://{yourDomain}/api/v2/keys/signing/%7ByourKeyId%7D/revoke"); var request = new RestRequest(Method.PUT); request.AddHeader("authorization", "Bearer {yourMgmtApiAccessToken}"); IRestResponse response = client.Execute(request); -`; -export const codeExample3 = ` package main + +``` +```go Go + package main import ( "fmt" @@ -83,12 +90,16 @@ func main() { fmt.Println(string(body)) } -`; -export const codeExample4 = ` HttpResponse response = Unirest.put("https://{yourDomain}/api/v2/keys/signing/%7ByourKeyId%7D/revoke") + +``` +```java Java + HttpResponse response = Unirest.put("https://{yourDomain}/api/v2/keys/signing/%7ByourKeyId%7D/revoke") .header("authorization", "Bearer {yourMgmtApiAccessToken}") .asString(); -`; -export const codeExample5 = ` var axios = require("axios").default; + +``` +```javascript Node.JS + var axios = require("axios").default; var options = { method: 'PUT', @@ -101,8 +112,10 @@ console.log(response.data); }).catch(function (error) { console.error(error); }); -`; -export const codeExample6 = ` #import + +``` +```obj-c Obj-C + #import NSDictionary *headers = @{ @"authorization": @"Bearer {yourMgmtApiAccessToken}" }; @@ -123,8 +136,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request } }]; [dataTask resume]; -`; -export const codeExample7 = ` $curl = curl_init(); + +``` +```php PHP + $curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/keys/signing/%7ByourKeyId%7D/revoke", @@ -149,8 +164,10 @@ echo "cURL Error #:" . $err; } else { echo $response; } -`; -export const codeExample8 = ` import http.client + +``` +```python Python + import http.client conn = http.client.HTTPSConnection("") @@ -162,8 +179,10 @@ res = conn.getresponse() data = res.read() print(data.decode("utf-8")) -`; -export const codeExample9 = ` require 'uri' + +``` +```ruby Ruby + require 'uri' require 'net/http' require 'openssl' @@ -178,8 +197,10 @@ request["authorization"] = 'Bearer {yourMgmtApiAccessToken}' response = http.request(request) puts response.read_body -`; -export const codeExample10 = ` import Foundation + +``` +```swift Swift + import Foundation let headers = ["authorization": "Bearer {yourMgmtApiAccessToken}"] @@ -200,20 +221,9 @@ if (error != nil) { }) dataTask.resume() -`; - - - - - - - - - - - - - + +``` +
    diff --git a/main/docs/ja-jp/get-started/tenant-settings/signing-keys/rotate-signing-keys.mdx b/main/docs/ja-jp/get-started/tenant-settings/signing-keys/rotate-signing-keys.mdx index 7a08a3553..43e38599a 100644 --- a/main/docs/ja-jp/get-started/tenant-settings/signing-keys/rotate-signing-keys.mdx +++ b/main/docs/ja-jp/get-started/tenant-settings/signing-keys/rotate-signing-keys.mdx @@ -10,6 +10,7 @@ permalink: "rotate-signing-keys" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; 署名鍵を定期的に手動でローテーションして、アプリケーションやAPIがトークンの検証に使用するJSON Web Key(JWK)を変更することができます。アプリケーションまたはAPIがこのキー変更を許可**せず** 、トークンの検証に期限の切れた署名鍵を使おうとした場合は、認証要求が失敗します。 @@ -45,16 +46,22 @@ Auth0は一度に1つの署名鍵しか署名しませんが、テナントの +```bash cURL + curl --request POST \ --url 'https://{yourDomain}/api/v2/keys/signing/rotate' \ --header 'authorization: Bearer {yourMgmtApiAccessToken}' -`; -export const codeExample2 = ` var client = new RestClient("https://{yourDomain}/api/v2/keys/signing/rotate"); + +``` +```csharp C# + var client = new RestClient("https://{yourDomain}/api/v2/keys/signing/rotate"); var request = new RestRequest(Method.POST); request.AddHeader("authorization", "Bearer {yourMgmtApiAccessToken}"); IRestResponse response = client.Execute(request); -`; -export const codeExample3 = ` package main + +``` +```go Go + package main import ( "fmt" @@ -79,12 +86,16 @@ func main() { fmt.Println(string(body)) } -`; -export const codeExample4 = ` HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/keys/signing/rotate") + +``` +```java Java + HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/keys/signing/rotate") .header("authorization", "Bearer {yourMgmtApiAccessToken}") .asString(); -`; -export const codeExample5 = ` var axios = require("axios").default; + +``` +```javascript Node.JS + var axios = require("axios").default; var options = { method: 'POST', @@ -97,8 +108,10 @@ console.log(response.data); }).catch(function (error) { console.error(error); }); -`; -export const codeExample6 = ` #import + +``` +```obj-c Obj-C + #import NSDictionary *headers = @{ @"authorization": @"Bearer {yourMgmtApiAccessToken}" }; @@ -119,8 +132,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request } }]; [dataTask resume]; -`; -export const codeExample7 = ` $curl = curl_init(); + +``` +```php PHP + $curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/keys/signing/rotate", @@ -145,8 +160,10 @@ echo "cURL Error #:" . $err; } else { echo $response; } -`; -export const codeExample8 = ` import http.client + +``` +```python Python + import http.client conn = http.client.HTTPSConnection("") @@ -158,8 +175,10 @@ res = conn.getresponse() data = res.read() print(data.decode("utf-8")) -`; -export const codeExample9 = ` require 'uri' + +``` +```ruby Ruby + require 'uri' require 'net/http' require 'openssl' @@ -174,8 +193,10 @@ request["authorization"] = 'Bearer {yourMgmtApiAccessToken}' response = http.request(request) puts response.read_body -`; -export const codeExample10 = ` import Foundation + +``` +```swift Swift + import Foundation let headers = ["authorization": "Bearer {yourMgmtApiAccessToken}"] @@ -196,20 +217,9 @@ if (error != nil) { }) dataTask.resume() -`; - - - - - - - - - - - - - + +``` +
    diff --git a/main/docs/ja-jp/get-started/tenant-settings/signing-keys/view-signing-certificates.mdx b/main/docs/ja-jp/get-started/tenant-settings/signing-keys/view-signing-certificates.mdx index 55734e593..59438b5e7 100644 --- a/main/docs/ja-jp/get-started/tenant-settings/signing-keys/view-signing-certificates.mdx +++ b/main/docs/ja-jp/get-started/tenant-settings/signing-keys/view-signing-certificates.mdx @@ -10,6 +10,7 @@ permalink: "view-signing-certificates" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Auth0 DashboardManagement APIを使用すると、テナントのアプリケーションのクライアントシークレットと署名鍵を確認することができます。アプリケーションの署名鍵は、アプリケーションに送信されたIDトークン、アクセストークン、SAMLアサーション、およびWS-Fedアサーションを署名するのに使用されます。これらの鍵は、IDプロバイダー(IdP)に対するSAML要求の署名やIdPからの応答の暗号化など、接続とのやり取りを署名する鍵とは異なります。IdP接続のSAMLアサーションはデフォルトで署名されます(これは、推奨されている動作です)。詳しくは、「[SAML IDプロバイダーの構成設定](/docs/ja-jp/authenticate/protocols/saml/saml-identity-provider-configuration-settings)」をお読みください。 @@ -51,14 +52,20 @@ import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; `GET`呼び出しを[`/keys/signing`](https://auth0.com/docs/api/management/v2/keys/get-signing-keys)エンドポイントに対して行います。`{yourMgmtApiAccessToken}`プレースホルダーの値をManageme​nt APIのアクセストークンで置き換えてください。 -export const codeExample1 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/keys/signing' \ - --header 'authorization: Bearer {yourMgmtApiAccessToken}'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/keys/signing"); + --header 'authorization: Bearer {yourMgmtApiAccessToken}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/keys/signing"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer {yourMgmtApiAccessToken}"); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -82,11 +89,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/keys/signing") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/keys/signing") .header("authorization", "Bearer {yourMgmtApiAccessToken}") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -98,8 +109,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer {yourMgmtApiAccessToken}" }; @@ -119,8 +132,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/keys/signing", @@ -144,8 +159,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -156,8 +173,10 @@ conn.request("GET", "/{yourDomain}/api/v2/keys/signing", headers=headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -171,8 +190,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer {yourMgmtApiAccessToken}' response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer {yourMgmtApiAccessToken}"] @@ -192,20 +213,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
    @@ -225,14 +235,20 @@ dataTask.resume()`; `GET`呼び出しを[`/keys/signing`](https://auth0.com/docs/api/management/v2/keys/get-signing-key)エンドポイントに対して行います。`{yourKeyId}`と`{yourMgmtApiAccessToken}`のプレースホルダーの値を、それぞれ署名鍵IDとManagement APIのアクセストークンに置き換えてください。 -export const codeExample11 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/keys/signing/%7ByourKeyId%7D' \ - --header 'authorization: Bearer {yourMgmtApiAccessToken}'`; -export const codeExample12 = `var client = new RestClient("https://{yourDomain}/api/v2/keys/signing/%7ByourKeyId%7D"); + --header 'authorization: Bearer {yourMgmtApiAccessToken}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/keys/signing/%7ByourKeyId%7D"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer {yourMgmtApiAccessToken}"); -IRestResponse response = client.Execute(request);`; -export const codeExample13 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -256,11 +272,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample14 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/keys/signing/%7ByourKeyId%7D") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/keys/signing/%7ByourKeyId%7D") .header("authorization", "Bearer {yourMgmtApiAccessToken}") - .asString();`; -export const codeExample15 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -272,8 +292,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample16 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer {yourMgmtApiAccessToken}" }; @@ -293,8 +315,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/keys/signing/%7ByourKeyId%7D", @@ -318,8 +342,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -330,8 +356,10 @@ conn.request("GET", "/{yourDomain}/api/v2/keys/signing/%7ByourKeyId%7D", headers res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -345,8 +373,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer {yourMgmtApiAccessToken}' response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer {yourMgmtApiAccessToken}"] @@ -366,20 +396,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
    diff --git a/main/docs/ja-jp/libraries/lock/lock-api-reference.mdx b/main/docs/ja-jp/libraries/lock/lock-api-reference.mdx index 010f58e9b..6f62428cd 100644 --- a/main/docs/ja-jp/libraries/lock/lock-api-reference.mdx +++ b/main/docs/ja-jp/libraries/lock/lock-api-reference.mdx @@ -27,9 +27,9 @@ Lockには、多くのメソッド、機能、構成可能なオプションが アプリケーションの`clientID`と[Auth0](https://manage.auth0.com/#/)管理ダッシュボードのアカウントの`ドメイン`を使用して構成された`Auth0Lock`の新しいインスタンスを初期化します。3番目のオプションのパラメーターは、アプリケーションのニーズに合わせてLockを構成するために使用される`オプション`オブジェクトです。この情報は、[アプリケーションの設定](https://manage.auth0.com/#/applications)で確認できます。 -* **clientId {String}** :必須パラメーター。Auth0のアプリケーションのclientId。 +* **clientId `{String}`** :必須パラメーター。Auth0のアプリケーションのclientId。 * **ドメイン{String}** :必須パラメーター。Auth0ドメイン。通常は、your-account.auth0.comです。 -* **オプション {Object}** :オプションのパラメーター。ロックの外観と動作を構成できます。詳細については、[構成オプションのページ](/docs/ja-jp/libraries/lock/lock-configuration)を参照してください。 +* **オプション `{Object}`** :オプションのパラメーター。ロックの外観と動作を構成できます。詳細については、[構成オプションのページ](/docs/ja-jp/libraries/lock/lock-configuration)を参照してください。 export const codeExample1 = `var Auth = (function() { @@ -127,8 +127,8 @@ lock.show({ このオブジェクトは、`show`メソッドのオプションとしてのみ使用でき、Lockをインスタンス化するときに通常の`オプション`オブジェクトでは使用できません。`flashMessage`オブジェクトは、Lockが表示されたときにエラーまたは成功のフラッシュメッセージを表示します。次のパラメーターがあります。 -* **タイプ** {String}:メッセージタイプ。`エラー`または`成功`のいずれかである必要があります。 -* **テキスト** {String}:表示するテキスト。 +* **タイプ** `{String}`:メッセージタイプ。`エラー`または`成功`のいずれかである必要があります。 +* **テキスト** `{String}`:表示するテキスト。 ```javascript lines lock.show({ @@ -239,7 +239,7 @@ export const codeExample2 = `var Auth = (function() { このメソッドは、[auth.autoParseHash](/docs/ja-jp/libraries/lock/lock-configuration)オプションを`false`に設定した場合にのみ使用できます。認証フローを完了するには、`resumeAuth`を呼び出す必要があります。このメソッドは、`#`を使用してurl (`useHash`を使用したangular2、または`hashHistory`を使用したreact-router)を処理するクライアント側ルーターを使用している場合に便利です。 -* **hash** {String}:リダイレクトから受信したハッシュフラグメント。 +* **hash** `{String}`:リダイレクトから受信したハッシュフラグメント。 * **コールバック** {Function}:解析が完了した後に呼び出されます。最初の引数としてエラー(存在する場合)があり、2番目の引数として認証結果があります。使用できるハッシュがない場合は、両方の引数が`null`になります。 ```javascript lines @@ -256,7 +256,7 @@ lock.resumeAuth(hash, function(error, authResult) { `checkSession`メソッドを使用すると、ドメインのAuth0に対して既に認証済みのユーザーのAuth0から新しいトークンを取得できます。次のパラメーターがあります。 -* **オプション** {Object}:オプション。通常は`/authorize`に送信される有効なOAuth2パラメーターを受け入れます。省略した場合は、Auth0の初期化時に指定されたパラメーターが使用されます。 +* **オプション** `{Object}`:オプション。通常は`/authorize`に送信される有効なOAuth2パラメーターを受け入れます。省略した場合は、Auth0の初期化時に指定されたパラメーターが使用されます。 * **コールバック** {Function}:トークンの更新結果で呼び出されます。最初の引数としてエラー(存在する場合)があり、2番目の引数として認証結果があります。 ```javascript lines @@ -269,7 +269,7 @@ lock.checkSession({}, function(err, authResult) { ユーザーをログアウトします。 -* **オプション** {Object}:これはオプションであり、auth0.js logout()と同じルールに従います。 +* **オプション** `{Object}`:これはオプションであり、auth0.js logout()と同じルールに従います。 ```javascript lines lock.logout({ diff --git a/main/docs/ja-jp/libraries/lock/lock-configuration.mdx b/main/docs/ja-jp/libraries/lock/lock-configuration.mdx index c81cd25a3..ee41cb418 100644 --- a/main/docs/ja-jp/libraries/lock/lock-configuration.mdx +++ b/main/docs/ja-jp/libraries/lock/lock-configuration.mdx @@ -411,12 +411,12 @@ Lockを閉じられるかどうかを決定します。`container`オプショ ![Lock Option: Container](/docs/images/ja-jp/cdy7uua7fh8z/5L4S47Yfset2DR9pjcqVrX/1c4d1928cf75acf40129ffd01394bf33/lock-container.png) -### flashMessage {Object} +### flashMessage `{Object}` Lockが表示されているときに、`error`または`success`のフラッシュメッセージを表示します。このオブジェクトは次のプロパティを含みます: -* type {String}:メッセージタイプ。サポートされているタイプは`error`、`info`、`success`です。 -* text {String}:表示するテキスト。 +* type `{String}`:メッセージタイプ。サポートされているタイプは`error`、`info`、`success`です。 +* text `{String}`:表示するテキスト。 ```javascript lines var options = { @@ -478,7 +478,7 @@ var options = { * [パスワードレス認証](/docs/ja-jp/connections/passwordless)を使用して確立されたセッションで、[ホストされたログインページ](/docs/ja-jp/authenticate/login/auth0-universal-login)でLockを使用した * `responseType: code`の[埋め込み型ログインシナリオ](/docs/ja-jp/authenticate/login/universal-vs-embedded-login)でLockを使用した(通常のWebアプリで使用される[認証コードフロー](/docs/ja-jp/get-started/authentication-and-authorization-flow/authorization-code-flow)を示します) -### scrollGlobalMessagesIntoView {Boolean} +### scrollGlobalMessagesIntoView `{Boolean}` `globalMessage`をユーザーのビューポートにスクロールインさせるかどうかを決定します。デフォルトは`true`です。 @@ -510,10 +510,10 @@ var options = { カスタムOAuth2接続を使用してLockのボタンをカスタマイズできます。カスタマイズを希望するカスタムの接続ボタンはそれぞれ、独自のパラメーターセットと一緒に名前で表記する必要があります。カスタマイズ可能なパラメーターは以下です。 -* **displayName** {String}:ボタンタイトルを作成する際に、接続名の代わりに表示する名前、たとえばログインのための「`LOGIN WITH MYCONNECTION`」など。 -* **primaryColor** {String}:ボタンの背景色。デフォルトは、`#eb5424`です。 -* **foregroundColor** {String}:ボタンの文字の色。デフォルトは、`#FFFFFF`です。 -* **icon** {String}:この接続のためのアイコンのURL。例:`http://site.com/logo.png`。 +* **displayName** `{String}`:ボタンタイトルを作成する際に、接続名の代わりに表示する名前、たとえばログインのための「`LOGIN WITH MYCONNECTION`」など。 +* **primaryColor** `{String}`:ボタンの背景色。デフォルトは、`#eb5424`です。 +* **foregroundColor** `{String}`:ボタンの文字の色。デフォルトは、`#FFFFFF`です。 +* **icon** `{String}`:この接続のためのアイコンのURL。例:`http://site.com/logo.png`。 ```javascript lines var options = { @@ -534,7 +534,7 @@ var options = { }; ``` -### labeledSubmitButton {Boolean} +### labeledSubmitButton `{Boolean}` このオプションは、送信ボタンにラベルを付けるかどうかを示し、デフォルトでは`true`です。`false`に設定すると、代わりにアイコンが表示されます。 @@ -550,7 +550,7 @@ var options = { ラベルがデフォルトのtrueに設定されている場合、ラベルのテキストは、[languageDictionary](#languagedictionary-object-)オプションでカスタマイズできます。 -### logo {String} +### logo `{String}` `logo`の値は、画像のURLであり、Lockのヘッダーに配置され、Auth0のロゴのデフォルトになります。ユーザーエクスペリエンスを向上させるために推奨される最大高さは`58px`です。 @@ -674,7 +674,7 @@ var options = { }; ``` -### redirectUrl {String} +### redirectUrl `{String}` URL Auth0が認証後にリダイレクトされます。デフォルトは空の文字列「」(リダイレクトURLなし)です。 @@ -688,7 +688,7 @@ var options = { `redirectUrl`が指定されている場合(空の値以外が設定されている場合)の`responseType`オプションは、手動で設定されていない場合はデフォルトで`code`になります。 -### responseMode {String} +### responseMode `{String}` コードまたはトークンを、クエリ部やフラグメント部分に含めるのではなく、HTTP POST要求で`redirectUrl`に送信する場合は、`"form_post"`に設定する必要があります。 @@ -906,7 +906,7 @@ var options = { `defaultDatabaseConnection:'test-database'` -### initialScreen {String} +### initialScreen `{String}` ウィジェットを開いたときに表示される画面の名前です。有効な値は`login`、`signUp`、`forgotPassword`です。このオプションが指定されていない場合、ウィジェットのデフォルト画面は、リストに用意されている最初の画面になります。 @@ -918,7 +918,7 @@ var options = { `loginAfterSignUp: false` -### forgotPasswordLink {String} +### forgotPasswordLink `{String}` ユーザーがパスワードをリセットできるページのURLを設定します。空でない文字列に設定すると、ログイン画面で「パスワードを覚えていない場合」のリンクをクリックしたユーザーは、指定したURLにリダイレクトされます。 @@ -950,7 +950,7 @@ var options = { }; ``` -### signUpLink {String} +### signUpLink `{String}` サインアップボタンをクリックした際に要求されるURLを設定します。空でない文字列に設定すると、このオプションは`allowSignUp`を強制的に`true`にします。 diff --git a/main/docs/ja-jp/libraries/lock/lock-ui-customization.mdx b/main/docs/ja-jp/libraries/lock/lock-ui-customization.mdx index 595c7b096..d0b26795c 100644 --- a/main/docs/ja-jp/libraries/lock/lock-ui-customization.mdx +++ b/main/docs/ja-jp/libraries/lock/lock-ui-customization.mdx @@ -21,7 +21,7 @@ Lockをインスタンス化するときに、`options`パラメーターを介 `theme`プロパティの下の名前空間で、現在利用できるテーマオプションがいくつかあります。 -#### logo {String} +#### logo `{String}` ![Lock UI customization - Logo](/docs/images/ja-jp/cdy7uua7fh8z/FdOAKKy71rTbFjIlZEL8D/2eef96008095d85388daaa461707901d/lock-theme-logo.png) @@ -35,7 +35,7 @@ var options = { }; ``` -#### primaryColor {String} +#### primaryColor `{String}` ![Lock UI customization - primary color](/docs/images/ja-jp/cdy7uua7fh8z/1qQjeTmXJyIziv400VPaOn/48dd3cb8a72a6e88b2634b4b8a8bed63/lock-theme-primarycolor.png) @@ -50,14 +50,14 @@ var options = { }; ``` -#### authButtons {Object} +#### authButtons `{Object}` Lockのボタンをカスタマイズできます。カスタマイズを希望するカスタムの接続ボタンはそれぞれ、独自のパラメーターセットと一緒に名前で表記する必要があります。カスタマイズ可能なパラメーターは以下です。 -* **displayName** {String}:ボタンタイトルを作成する際に、接続名の代わりに表示する名前、たとえばログインのための「`LOGIN WITH MYCONNECTION`」など。 -* **primaryColor** {String}:ボタンの背景色。デフォルトは、`#eb5424`です。 -* **foregroundColor** {String}:ボタンの文字の色。デフォルトは、`#FFFFFF`です。 -* **icon** {String}:この接続のためのアイコンのURL。例:`http://site.com/logo.png`。 +* **displayName** `{String}`:ボタンタイトルを作成する際に、接続名の代わりに表示する名前、たとえばログインのための「`LOGIN WITH MYCONNECTION`」など。 +* **primaryColor** `{String}`:ボタンの背景色。デフォルトは、`#eb5424`です。 +* **foregroundColor** `{String}`:ボタンの文字の色。デフォルトは、`#FFFFFF`です。 +* **icon** `{String}`:この接続のためのアイコンのURL。例:`http://site.com/logo.png`。 ```javascript lines var options = { diff --git a/main/docs/ja-jp/manage-users/access-control/configure-core-rbac/enable-role-based-access-control-for-apis.mdx b/main/docs/ja-jp/manage-users/access-control/configure-core-rbac/enable-role-based-access-control-for-apis.mdx index 9671bc044..898019092 100644 --- a/main/docs/ja-jp/manage-users/access-control/configure-core-rbac/enable-role-based-access-control-for-apis.mdx +++ b/main/docs/ja-jp/manage-users/access-control/configure-core-rbac/enable-role-based-access-control-for-apis.mdx @@ -10,6 +10,7 @@ permalink: "enable-role-based-access-control-for-apis" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Auth0 DashboardまたはManagement使用して、APIに[ロールベースのアクセス制御(RBAC)](/docs/ja-jp/manage-users/access-control/rbac)を有効化することができます。これにより、APIの認可コア機能セットが有効になります。 @@ -42,20 +43,26 @@ RBACを有効にすると、アクセストークンに権限が含まれてい Management APIを使用してRBACを有効にするには、[リソースサーバー更新エンドポイント](https://auth0.com/docs/api/management/v2/resource-servers/patch-resource-servers-by-id)にPATCH要求を行います。PATCH要求で、`enforce_policies`を`true`に設定します。 -export const codeExample1 = `curl --request PATCH \ + +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/resource-servers/API_ID' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{ "enforce_policies": "true", "token_dialect": "TOKEN_DIALECT" }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/resource-servers/API_ID"); + --data '{ "enforce_policies": "true", "token_dialect": "TOKEN_DIALECT" }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/resource-servers/API_ID"); var request = new RestRequest(Method.PATCH); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{ \"enforce_policies\": \"true\", \"token_dialect\": \"TOKEN_DIALECT\" }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "enforce_policies": "true", "token_dialect": "TOKEN_DIALECT" }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -68,7 +75,7 @@ func main() { url := "https://{yourDomain}/api/v2/resource-servers/API_ID" - payload := strings.NewReader("{ \"enforce_policies\": \"true\", \"token_dialect\": \"TOKEN_DIALECT\" }") + payload := strings.NewReader("{ "enforce_policies": "true", "token_dialect": "TOKEN_DIALECT" }") req, _ := http.NewRequest("PATCH", url, payload) @@ -84,14 +91,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/resource-servers/API_ID") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/resource-servers/API_ID") .header("content-type", "application/json") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ \"enforce_policies\": \"true\", \"token_dialect\": \"TOKEN_DIALECT\" }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "enforce_policies": "true", "token_dialect": "TOKEN_DIALECT" }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -108,8 +119,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @@ -136,8 +149,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/resource-servers/API_ID", @@ -147,7 +162,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{ \"enforce_policies\": \"true\", \"token_dialect\": \"TOKEN_DIALECT\" }", + CURLOPT_POSTFIELDS => "{ "enforce_policies": "true", "token_dialect": "TOKEN_DIALECT" }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "cache-control: no-cache", @@ -164,12 +179,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"enforce_policies\": \"true\", \"token_dialect\": \"TOKEN_DIALECT\" }" +payload = "{ "enforce_policies": "true", "token_dialect": "TOKEN_DIALECT" }" headers = { 'content-type': "application/json", @@ -182,8 +199,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/resource-servers/API_ID", payload, h res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -197,11 +216,13 @@ request = Net::HTTP::Patch.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ \"enforce_policies\": \"true\", \"token_dialect\": \"TOKEN_DIALECT\" }" +request.body = "{ "enforce_policies": "true", "token_dialect": "TOKEN_DIALECT" }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -232,20 +253,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + 以下の表が示すように、`API_ID`、`MGMT_API_ACCESS_TOKEN`、`TOKEN_DIALECT`をそれぞれの値に置き換えます。 diff --git a/main/docs/ja-jp/manage-users/access-control/configure-core-rbac/rbac-users/assign-permissions-to-users.mdx b/main/docs/ja-jp/manage-users/access-control/configure-core-rbac/rbac-users/assign-permissions-to-users.mdx index add6b72ba..797200847 100644 --- a/main/docs/ja-jp/manage-users/access-control/configure-core-rbac/rbac-users/assign-permissions-to-users.mdx +++ b/main/docs/ja-jp/manage-users/access-control/configure-core-rbac/rbac-users/assign-permissions-to-users.mdx @@ -10,6 +10,7 @@ permalink: "assign-permissions-to-users" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Auth0 DashboardまたはManagement APIを使用して、ユーザーに[権限](/docs/ja-jp/manage-users/access-control/rbac)を割り当てることができます。割り当てられた権限は、API Authorization Core機能セットで使用できます。 @@ -47,20 +48,26 @@ import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; `POST`呼び出しを[ユーザー権限割り当てエンドポイント](https://auth0.com/docs/api/management/v2#!/Users/post_permissions)に対して行います。`USER_ID`、`MGMT_API_ACCESS_TOKEN`、`API_IDENTIFIER`、`PERMISSION_NAME`のプレースホルダーをそれぞれユーザーID、Management APIのアクセストークン、API識別子、権限名に置き換えます。 -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/api/v2/users/USER_ID/permissions' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{ "permissions": [ { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" } ] }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/users/USER_ID/permissions"); + --data '{ "permissions": [ { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" } ] }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users/USER_ID/permissions"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{ \"permissions\": [ { \"resource_server_identifier\": \"API_IDENTIFIER\", \"permission_name\": \"PERMISSION_NAME\" }, { \"resource_server_identifier\": \"API_IDENTIFIER\", \"permission_name\": \"PERMISSION_NAME\" } ] }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "permissions": [ { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" } ] }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -73,7 +80,7 @@ func main() { url := "https://{yourDomain}/api/v2/users/USER_ID/permissions" - payload := strings.NewReader("{ \"permissions\": [ { \"resource_server_identifier\": \"API_IDENTIFIER\", \"permission_name\": \"PERMISSION_NAME\" }, { \"resource_server_identifier\": \"API_IDENTIFIER\", \"permission_name\": \"PERMISSION_NAME\" } ] }") + payload := strings.NewReader("{ "permissions": [ { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" } ] }") req, _ := http.NewRequest("POST", url, payload) @@ -89,14 +96,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/users/USER_ID/permissions") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/users/USER_ID/permissions") .header("content-type", "application/json") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ \"permissions\": [ { \"resource_server_identifier\": \"API_IDENTIFIER\", \"permission_name\": \"PERMISSION_NAME\" }, { \"resource_server_identifier\": \"API_IDENTIFIER\", \"permission_name\": \"PERMISSION_NAME\" } ] }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "permissions": [ { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" } ] }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -124,8 +135,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @@ -151,8 +164,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users/USER_ID/permissions", @@ -162,7 +177,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{ \"permissions\": [ { \"resource_server_identifier\": \"API_IDENTIFIER\", \"permission_name\": \"PERMISSION_NAME\" }, { \"resource_server_identifier\": \"API_IDENTIFIER\", \"permission_name\": \"PERMISSION_NAME\" } ] }", + CURLOPT_POSTFIELDS => "{ "permissions": [ { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" } ] }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "cache-control: no-cache", @@ -179,12 +194,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"permissions\": [ { \"resource_server_identifier\": \"API_IDENTIFIER\", \"permission_name\": \"PERMISSION_NAME\" }, { \"resource_server_identifier\": \"API_IDENTIFIER\", \"permission_name\": \"PERMISSION_NAME\" } ] }" +payload = "{ "permissions": [ { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" } ] }" headers = { 'content-type': "application/json", @@ -197,8 +214,10 @@ conn.request("POST", "/{yourDomain}/api/v2/users/USER_ID/permissions", payload, res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -212,11 +231,13 @@ request = Net::HTTP::Post.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ \"permissions\": [ { \"resource_server_identifier\": \"API_IDENTIFIER\", \"permission_name\": \"PERMISSION_NAME\" }, { \"resource_server_identifier\": \"API_IDENTIFIER\", \"permission_name\": \"PERMISSION_NAME\" } ] }" +request.body = "{ "permissions": [ { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" } ] }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -253,20 +274,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
    diff --git a/main/docs/ja-jp/manage-users/access-control/configure-core-rbac/rbac-users/assign-roles-to-users.mdx b/main/docs/ja-jp/manage-users/access-control/configure-core-rbac/rbac-users/assign-roles-to-users.mdx index cc1e1058e..397f4123c 100644 --- a/main/docs/ja-jp/manage-users/access-control/configure-core-rbac/rbac-users/assign-roles-to-users.mdx +++ b/main/docs/ja-jp/manage-users/access-control/configure-core-rbac/rbac-users/assign-roles-to-users.mdx @@ -10,6 +10,7 @@ permalink: "assign-roles-to-users" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Auth0 DashboardまたはManagement APIを使用して、ユーザーに[ロール](/docs/ja-jp/authorization/concepts/rbac)を割り当てることができます。割り当てられたロールは、API Authorization Core機能セットで使用できます。 @@ -42,20 +43,26 @@ import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; [ユーザーロールの割り当てエンドポイント](https://auth0.com/docs/api/management/v2#!/Users/post_user_roles)に`POST`呼び出しを行います。`USER_ID`、`MGMT_API_ACCESS_TOKEN`、`ROLE_ID`のプレースホルダー値をそれぞれユーザーID、Management APIのアクセストークン、ロールIDに置き換えます。 -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/api/v2/users/USER_ID/roles' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{ "roles": [ "ROLE_ID", "ROLE_ID" ] }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/users/USER_ID/roles"); + --data '{ "roles": [ "ROLE_ID", "ROLE_ID" ] }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users/USER_ID/roles"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{ \"roles\": [ \"ROLE_ID\", \"ROLE_ID\" ] }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "roles": [ "ROLE_ID", "ROLE_ID" ] }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -68,7 +75,7 @@ func main() { url := "https://{yourDomain}/api/v2/users/USER_ID/roles" - payload := strings.NewReader("{ \"roles\": [ \"ROLE_ID\", \"ROLE_ID\" ] }") + payload := strings.NewReader("{ "roles": [ "ROLE_ID", "ROLE_ID" ] }") req, _ := http.NewRequest("POST", url, payload) @@ -84,14 +91,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/users/USER_ID/roles") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/users/USER_ID/roles") .header("content-type", "application/json") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ \"roles\": [ \"ROLE_ID\", \"ROLE_ID\" ] }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "roles": [ "ROLE_ID", "ROLE_ID" ] }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -108,8 +119,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @@ -135,8 +148,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users/USER_ID/roles", @@ -146,7 +161,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{ \"roles\": [ \"ROLE_ID\", \"ROLE_ID\" ] }", + CURLOPT_POSTFIELDS => "{ "roles": [ "ROLE_ID", "ROLE_ID" ] }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "cache-control: no-cache", @@ -163,12 +178,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"roles\": [ \"ROLE_ID\", \"ROLE_ID\" ] }" +payload = "{ "roles": [ "ROLE_ID", "ROLE_ID" ] }" headers = { 'content-type': "application/json", @@ -181,8 +198,10 @@ conn.request("POST", "/{yourDomain}/api/v2/users/USER_ID/roles", payload, header res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -196,11 +215,13 @@ request = Net::HTTP::Post.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ \"roles\": [ \"ROLE_ID\", \"ROLE_ID\" ] }" +request.body = "{ "roles": [ "ROLE_ID", "ROLE_ID" ] }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -228,20 +249,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
    diff --git a/main/docs/ja-jp/manage-users/access-control/configure-core-rbac/rbac-users/remove-permissions-from-users.mdx b/main/docs/ja-jp/manage-users/access-control/configure-core-rbac/rbac-users/remove-permissions-from-users.mdx index b5cac17af..5f7f044f9 100644 --- a/main/docs/ja-jp/manage-users/access-control/configure-core-rbac/rbac-users/remove-permissions-from-users.mdx +++ b/main/docs/ja-jp/manage-users/access-control/configure-core-rbac/rbac-users/remove-permissions-from-users.mdx @@ -10,6 +10,7 @@ permalink: "remove-permissions-from-users" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Auth0 DashboardまたはManagement APIを使用して、ユーザーに直接割り当てられた権限を削除することができます。割り当てられた権限は、API Authorization Core機能セットで使用できます。詳細については、「[ロールベースのアクセス制御(RBAC)](/docs/ja-jp/manage-users/access-control/rbac)」をお読みください。 @@ -28,20 +29,26 @@ Role-based Access Control(RBAC)を正しく動作させるには、Dashboard `DELETE`呼び出しを[ユーザー権限削除エンドポイント](https://auth0.com/docs/api/management/v2#!/Users/delete_permissions)に対して行います。`USER_ID`、`MGMT_API_ACCESS_TOKEN`、`API_ID`、`PERMISSION_NAME`のプレースホルダーをそれぞれユーザーID、Management APIのアクセストークン、API ID、権限名に置き換えます。 -export const codeExample1 = `curl --request DELETE \ + +```bash cURL +curl --request DELETE \ --url 'https://{yourDomain}/api/v2/users/USER_ID/permissions' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{ "permissions": [ { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" } ] }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/users/USER_ID/permissions"); + --data '{ "permissions": [ { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" } ] }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users/USER_ID/permissions"); var request = new RestRequest(Method.DELETE); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{ \"permissions\": [ { \"resource_server_identifier\": \"API_ID\", \"permission_name\": \"PERMISSION_NAME\" }, { \"resource_server_identifier\": \"API_ID\", \"permission_name\": \"PERMISSION_NAME\" } ] }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "permissions": [ { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" } ] }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -54,7 +61,7 @@ func main() { url := "https://{yourDomain}/api/v2/users/USER_ID/permissions" - payload := strings.NewReader("{ \"permissions\": [ { \"resource_server_identifier\": \"API_ID\", \"permission_name\": \"PERMISSION_NAME\" }, { \"resource_server_identifier\": \"API_ID\", \"permission_name\": \"PERMISSION_NAME\" } ] }") + payload := strings.NewReader("{ "permissions": [ { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" } ] }") req, _ := http.NewRequest("DELETE", url, payload) @@ -70,14 +77,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.delete("https://{yourDomain}/api/v2/users/USER_ID/permissions") +} +``` +```java Java +HttpResponse response = Unirest.delete("https://{yourDomain}/api/v2/users/USER_ID/permissions") .header("content-type", "application/json") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ \"permissions\": [ { \"resource_server_identifier\": \"API_ID\", \"permission_name\": \"PERMISSION_NAME\" }, { \"resource_server_identifier\": \"API_ID\", \"permission_name\": \"PERMISSION_NAME\" } ] }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "permissions": [ { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" } ] }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'DELETE', @@ -99,8 +110,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @@ -126,8 +139,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users/USER_ID/permissions", @@ -137,7 +152,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "DELETE", - CURLOPT_POSTFIELDS => "{ \"permissions\": [ { \"resource_server_identifier\": \"API_ID\", \"permission_name\": \"PERMISSION_NAME\" }, { \"resource_server_identifier\": \"API_ID\", \"permission_name\": \"PERMISSION_NAME\" } ] }", + CURLOPT_POSTFIELDS => "{ "permissions": [ { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" } ] }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "cache-control: no-cache", @@ -154,12 +169,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"permissions\": [ { \"resource_server_identifier\": \"API_ID\", \"permission_name\": \"PERMISSION_NAME\" }, { \"resource_server_identifier\": \"API_ID\", \"permission_name\": \"PERMISSION_NAME\" } ] }" +payload = "{ "permissions": [ { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" } ] }" headers = { 'content-type': "application/json", @@ -172,8 +189,10 @@ conn.request("DELETE", "/{yourDomain}/api/v2/users/USER_ID/permissions", payload res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -187,11 +206,13 @@ request = Net::HTTP::Delete.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ \"permissions\": [ { \"resource_server_identifier\": \"API_ID\", \"permission_name\": \"PERMISSION_NAME\" }, { \"resource_server_identifier\": \"API_ID\", \"permission_name\": \"PERMISSION_NAME\" } ] }" +request.body = "{ "permissions": [ { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" } ] }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -228,20 +249,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
    diff --git a/main/docs/ja-jp/manage-users/access-control/configure-core-rbac/rbac-users/remove-roles-from-users.mdx b/main/docs/ja-jp/manage-users/access-control/configure-core-rbac/rbac-users/remove-roles-from-users.mdx index 869afa302..9c6059a1f 100644 --- a/main/docs/ja-jp/manage-users/access-control/configure-core-rbac/rbac-users/remove-roles-from-users.mdx +++ b/main/docs/ja-jp/manage-users/access-control/configure-core-rbac/rbac-users/remove-roles-from-users.mdx @@ -10,6 +10,7 @@ permalink: "remove-roles-from-users" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Auth0 DashboardまたはManagement APIを使用して、ユーザーに割り当てられた[ロール](/docs/ja-jp/manage-users/access-control/rbac)を削除できます。割り当てられたロールは、API Authorization Core機能セットで使用されます。 @@ -26,20 +27,26 @@ Role-based Access Control(RBAC)を正しく動作させるには、Dashboard [ユーザーロール削除エンドポイント](https://auth0.com/docs/api/management/v2#!/Users/delete_user_roles)に対して`DELETE`呼び出しを実行します。`USER_ID`、`MGMT_API_ACCESS_TOKEN`、`ROLE_ID`のプレースホルダー値をそれぞれユーザーID、Management APIのアクセストークン、ロールIDに置き換えます。 -export const codeExample1 = `curl --request DELETE \ + +```bash cURL +curl --request DELETE \ --url 'https://{yourDomain}/api/v2/users/USER_ID/roles' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{ "roles": [ "ROLE_ID", "ROLE_ID" ] }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/users/USER_ID/roles"); + --data '{ "roles": [ "ROLE_ID", "ROLE_ID" ] }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users/USER_ID/roles"); var request = new RestRequest(Method.DELETE); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{ \"roles\": [ \"ROLE_ID\", \"ROLE_ID\" ] }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "roles": [ "ROLE_ID", "ROLE_ID" ] }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -52,7 +59,7 @@ func main() { url := "https://{yourDomain}/api/v2/users/USER_ID/roles" - payload := strings.NewReader("{ \"roles\": [ \"ROLE_ID\", \"ROLE_ID\" ] }") + payload := strings.NewReader("{ "roles": [ "ROLE_ID", "ROLE_ID" ] }") req, _ := http.NewRequest("DELETE", url, payload) @@ -68,14 +75,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.delete("https://{yourDomain}/api/v2/users/USER_ID/roles") +} +``` +```java Java +HttpResponse response = Unirest.delete("https://{yourDomain}/api/v2/users/USER_ID/roles") .header("content-type", "application/json") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ \"roles\": [ \"ROLE_ID\", \"ROLE_ID\" ] }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "roles": [ "ROLE_ID", "ROLE_ID" ] }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'DELETE', @@ -92,8 +103,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @@ -119,8 +132,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users/USER_ID/roles", @@ -130,7 +145,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "DELETE", - CURLOPT_POSTFIELDS => "{ \"roles\": [ \"ROLE_ID\", \"ROLE_ID\" ] }", + CURLOPT_POSTFIELDS => "{ "roles": [ "ROLE_ID", "ROLE_ID" ] }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "cache-control: no-cache", @@ -147,12 +162,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"roles\": [ \"ROLE_ID\", \"ROLE_ID\" ] }" +payload = "{ "roles": [ "ROLE_ID", "ROLE_ID" ] }" headers = { 'content-type': "application/json", @@ -165,8 +182,10 @@ conn.request("DELETE", "/{yourDomain}/api/v2/users/USER_ID/roles", payload, head res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -180,11 +199,13 @@ request = Net::HTTP::Delete.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ \"roles\": [ \"ROLE_ID\", \"ROLE_ID\" ] }" +request.body = "{ "roles": [ "ROLE_ID", "ROLE_ID" ] }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -212,20 +233,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
    diff --git a/main/docs/ja-jp/manage-users/access-control/configure-core-rbac/rbac-users/view-user-permissions.mdx b/main/docs/ja-jp/manage-users/access-control/configure-core-rbac/rbac-users/view-user-permissions.mdx index 74f0c3601..b0314faf1 100644 --- a/main/docs/ja-jp/manage-users/access-control/configure-core-rbac/rbac-users/view-user-permissions.mdx +++ b/main/docs/ja-jp/manage-users/access-control/configure-core-rbac/rbac-users/view-user-permissions.mdx @@ -10,6 +10,7 @@ permalink: "view-user-permissions" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; ユーザーに割り当てられた[権限](/docs/ja-jp/manage-users/access-control/rbac)は、Auth0 Dashboardを使用して表示できます。このタスクは、Management APIを使用することでも実行できます。割り当てられた権限は、API Authorization Core機能セットで使用できます。 @@ -56,14 +57,20 @@ Role-based Access Control(RBAC)を正しく動作させるには、Dashboard `GET`呼び出しを[ユーザー権限取得エンドポイント](https://auth0.com/docs/api/management/v2#!/Users/get_permissions)に対して行います。`USER_ID`と`MGMT_API_ACCESS_TOKEN`のプレースホルダーをそれぞれユーザーIDとManagement APIのアクセストークンに置き換えます。 -export const codeExample1 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/users/USER_ID/permissions' \ - --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/users/USER_ID/permissions"); + --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users/USER_ID/permissions"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -87,11 +94,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/users/USER_ID/permissions") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/users/USER_ID/permissions") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -103,8 +114,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN" }; @@ -124,8 +137,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users/USER_ID/permissions", @@ -149,8 +164,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -161,8 +178,10 @@ conn.request("GET", "/{yourDomain}/api/v2/users/USER_ID/permissions", headers=he res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -176,8 +195,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer MGMT_API_ACCESS_TOKEN"] @@ -197,20 +218,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
    diff --git a/main/docs/ja-jp/manage-users/access-control/configure-core-rbac/rbac-users/view-user-roles.mdx b/main/docs/ja-jp/manage-users/access-control/configure-core-rbac/rbac-users/view-user-roles.mdx index 52b39b090..5c6776b7a 100644 --- a/main/docs/ja-jp/manage-users/access-control/configure-core-rbac/rbac-users/view-user-roles.mdx +++ b/main/docs/ja-jp/manage-users/access-control/configure-core-rbac/rbac-users/view-user-roles.mdx @@ -10,6 +10,7 @@ permalink: "view-user-roles" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; ユーザーに割り当てられた[ロール](/docs/ja-jp/manage-users/access-control/rbac)は、Auth0 Dashboardを使用して表示することができます。このタスクは、Management APIを使用することでも実行できます。割り当てられたロールは、API Authorization Core機能セットで使用されます。 @@ -46,14 +47,20 @@ Role-based Access Control(RBAC)を正しく動作させるには、Dashboard `GET`呼び出しを[ユーザーロールの割り当てエンドポイント](https://auth0.com/docs/api/management/v2#!/Users/get_user_roles)に対して行います。`USER_ID`と`MGMT_API_ACCESS_TOKEN`のプレースホルダーをそれぞれユーザーIDとManagement APIのアクセストークンに置き換えます。 -export const codeExample1 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/users/USER_ID/roles' \ - --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/users/USER_ID/roles"); + --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users/USER_ID/roles"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -77,11 +84,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/users/USER_ID/roles") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/users/USER_ID/roles") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -93,8 +104,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN" }; @@ -114,8 +127,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users/USER_ID/roles", @@ -139,8 +154,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -151,8 +168,10 @@ conn.request("GET", "/{yourDomain}/api/v2/users/USER_ID/roles", headers=headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -166,8 +185,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer MGMT_API_ACCESS_TOKEN"] @@ -187,20 +208,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
    diff --git a/main/docs/ja-jp/manage-users/access-control/configure-core-rbac/roles/add-permissions-to-roles.mdx b/main/docs/ja-jp/manage-users/access-control/configure-core-rbac/roles/add-permissions-to-roles.mdx index 48f39f098..30615d31e 100644 --- a/main/docs/ja-jp/manage-users/access-control/configure-core-rbac/roles/add-permissions-to-roles.mdx +++ b/main/docs/ja-jp/manage-users/access-control/configure-core-rbac/roles/add-permissions-to-roles.mdx @@ -10,6 +10,7 @@ permalink: "add-permissions-to-roles" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Auth0 DashboardまたはManagement APIを使用して、[roles](/docs/ja-jp/manage-users/access-control/rbac)に権限を割り当てることができます。ロールとその権限は、API Authorization Core機能セットで使用できます。 @@ -30,20 +31,26 @@ import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; `[POST]`呼び出しを[[Add Role Permissions endpoint(ロール権限追加)]エンドポイント](https://auth0.com/docs/api/management/v2#!/Roles/post_role_permission_assignment)に対して行います。`ROLE_ID`、`MGMT_API_ACCESS_TOKEN`、`API_IDENTIFIER`、`PERMISSION_NAME`のプレースホルダーをそれぞれロールID、Management APIのアクセストークン、API識別子(オーディエンス)、権限名に置き換えます。 -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/api/v2/roles/ROLE_ID/permissions' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{ "permissions": [ { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" } ] }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/roles/ROLE_ID/permissions"); + --data '{ "permissions": [ { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" } ] }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/roles/ROLE_ID/permissions"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{ \"permissions\": [ { \"resource_server_identifier\": \"API_IDENTIFIER\", \"permission_name\": \"PERMISSION_NAME\" }, { \"resource_server_identifier\": \"API_IDENTIFIER\", \"permission_name\": \"PERMISSION_NAME\" } ] }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "permissions": [ { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" } ] }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -56,7 +63,7 @@ func main() { url := "https://{yourDomain}/api/v2/roles/ROLE_ID/permissions" - payload := strings.NewReader("{ \"permissions\": [ { \"resource_server_identifier\": \"API_IDENTIFIER\", \"permission_name\": \"PERMISSION_NAME\" }, { \"resource_server_identifier\": \"API_IDENTIFIER\", \"permission_name\": \"PERMISSION_NAME\" } ] }") + payload := strings.NewReader("{ "permissions": [ { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" } ] }") req, _ := http.NewRequest("POST", url, payload) @@ -72,14 +79,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/roles/ROLE_ID/permissions") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/roles/ROLE_ID/permissions") .header("content-type", "application/json") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ \"permissions\": [ { \"resource_server_identifier\": \"API_IDENTIFIER\", \"permission_name\": \"PERMISSION_NAME\" }, { \"resource_server_identifier\": \"API_IDENTIFIER\", \"permission_name\": \"PERMISSION_NAME\" } ] }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "permissions": [ { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" } ] }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -107,8 +118,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @@ -134,8 +147,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/roles/ROLE_ID/permissions", @@ -145,7 +160,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{ \"permissions\": [ { \"resource_server_identifier\": \"API_IDENTIFIER\", \"permission_name\": \"PERMISSION_NAME\" }, { \"resource_server_identifier\": \"API_IDENTIFIER\", \"permission_name\": \"PERMISSION_NAME\" } ] }", + CURLOPT_POSTFIELDS => "{ "permissions": [ { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" } ] }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "cache-control: no-cache", @@ -162,12 +177,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"permissions\": [ { \"resource_server_identifier\": \"API_IDENTIFIER\", \"permission_name\": \"PERMISSION_NAME\" }, { \"resource_server_identifier\": \"API_IDENTIFIER\", \"permission_name\": \"PERMISSION_NAME\" } ] }" +payload = "{ "permissions": [ { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" } ] }" headers = { 'content-type': "application/json", @@ -180,8 +197,10 @@ conn.request("POST", "/{yourDomain}/api/v2/roles/ROLE_ID/permissions", payload, res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -195,11 +214,13 @@ request = Net::HTTP::Post.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ \"permissions\": [ { \"resource_server_identifier\": \"API_IDENTIFIER\", \"permission_name\": \"PERMISSION_NAME\" }, { \"resource_server_identifier\": \"API_IDENTIFIER\", \"permission_name\": \"PERMISSION_NAME\" } ] }" +request.body = "{ "permissions": [ { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" } ] }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -236,20 +257,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
    diff --git a/main/docs/ja-jp/manage-users/access-control/configure-core-rbac/roles/create-roles.mdx b/main/docs/ja-jp/manage-users/access-control/configure-core-rbac/roles/create-roles.mdx index 4602acefa..95f88bf82 100644 --- a/main/docs/ja-jp/manage-users/access-control/configure-core-rbac/roles/create-roles.mdx +++ b/main/docs/ja-jp/manage-users/access-control/configure-core-rbac/roles/create-roles.mdx @@ -10,6 +10,7 @@ permalink: "create-roles" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Auth0のDashboardまたはManagement APIを使用して、[ロール](/docs/ja-jp/manage-users/access-control/rbac)を作成することができます。ロールは、API Authorization Core機能セットで使用できます。 @@ -28,20 +29,26 @@ Auth0のDashboardまたは response = Unirest.post("https://{yourDomain}/api/v2/roles") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/roles") .header("content-type", "application/json") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ \"name\": \"ROLE_NAME\", \"description\": \"ROLE_DESC\" }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "name": "ROLE_NAME", "description": "ROLE_DESC" }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -94,8 +105,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @@ -122,8 +135,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/roles", @@ -133,7 +148,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{ \"name\": \"ROLE_NAME\", \"description\": \"ROLE_DESC\" }", + CURLOPT_POSTFIELDS => "{ "name": "ROLE_NAME", "description": "ROLE_DESC" }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "cache-control: no-cache", @@ -150,12 +165,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"name\": \"ROLE_NAME\", \"description\": \"ROLE_DESC\" }" +payload = "{ "name": "ROLE_NAME", "description": "ROLE_DESC" }" headers = { 'content-type': "application/json", @@ -168,8 +185,10 @@ conn.request("POST", "/{yourDomain}/api/v2/roles", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -183,11 +202,13 @@ request = Net::HTTP::Post.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ \"name\": \"ROLE_NAME\", \"description\": \"ROLE_DESC\" }" +request.body = "{ "name": "ROLE_NAME", "description": "ROLE_DESC" }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -218,20 +239,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
    diff --git a/main/docs/ja-jp/manage-users/access-control/configure-core-rbac/roles/delete-roles.mdx b/main/docs/ja-jp/manage-users/access-control/configure-core-rbac/roles/delete-roles.mdx index 86f1efba8..95525a20e 100644 --- a/main/docs/ja-jp/manage-users/access-control/configure-core-rbac/roles/delete-roles.mdx +++ b/main/docs/ja-jp/manage-users/access-control/configure-core-rbac/roles/delete-roles.mdx @@ -10,6 +10,7 @@ permalink: "delete-roles" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Auth0 DashboardまたはManagement APIを使用して、[ロール](/docs/ja-jp/manage-users/access-control/rbac)を削除できます。ロールはAPIの認可コア機能セットで使用されます。 @@ -24,14 +25,20 @@ Role-based Access Control(RBAC)を正しく動作させるには、Dashboard `DELETE`呼び出しを[ロール削除エンドポイント](https://auth0.com/docs/api/management/v2#!/Roles/delete_roles_by_id)に対して行います。必ず、`ROLE_ID`と`MGMT_API_ACCESS_TOKEN`のプレースホルダーの値を、それぞれご自身のロールIDとManagement APIのアクセストークンに置き換えてください。 -export const codeExample1 = `curl --request DELETE \ + +```bash cURL +curl --request DELETE \ --url 'https://{yourDomain}/api/v2/roles/ROLE_ID' \ - --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/roles/ROLE_ID"); + --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/roles/ROLE_ID"); var request = new RestRequest(Method.DELETE); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -55,11 +62,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.delete("https://{yourDomain}/api/v2/roles/ROLE_ID") +} +``` +```java Java +HttpResponse response = Unirest.delete("https://{yourDomain}/api/v2/roles/ROLE_ID") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'DELETE', @@ -71,8 +82,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN" }; @@ -92,8 +105,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/roles/ROLE_ID", @@ -117,8 +132,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -129,8 +146,10 @@ conn.request("DELETE", "/{yourDomain}/api/v2/roles/ROLE_ID", headers=headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -144,8 +163,10 @@ request = Net::HTTP::Delete.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer MGMT_API_ACCESS_TOKEN"] @@ -165,20 +186,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
    diff --git a/main/docs/ja-jp/manage-users/access-control/configure-core-rbac/roles/edit-role-definitions.mdx b/main/docs/ja-jp/manage-users/access-control/configure-core-rbac/roles/edit-role-definitions.mdx index bbd34bbd7..9f9f3c734 100644 --- a/main/docs/ja-jp/manage-users/access-control/configure-core-rbac/roles/edit-role-definitions.mdx +++ b/main/docs/ja-jp/manage-users/access-control/configure-core-rbac/roles/edit-role-definitions.mdx @@ -10,6 +10,7 @@ permalink: "edit-role-definitions" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Auth0 DashboardまたはManagement APIを使用して、[ロール](/docs/ja-jp/manage-users/access-control/rbac)の定義を編集することができます。ロールはAPIの認可コア機能セットで使用されます。 @@ -26,20 +27,26 @@ Role-based Access Control(RBAC)を正しく動作させるには、Dashboard [ロール更新エンドポイント](/docs/ja-jp/api/management/v2#!/Roles/patch_roles_by_id)に`PATCH`呼び出しを行います。`ROLE_ID`、`MGMT_API_ACCESS_TOKEN`、`ROLE_NAME`、`ROLE_DESC`のプレースホルダーの値をそれぞれロールID、Management APIのアクセストークン、ロール名、ロールの説明に置き換えます。 -export const codeExample1 = `curl --request PATCH \ + +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/roles/ROLE_ID' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{ "name": "ROLE_NAME", "description": "ROLE_DESC" }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/roles/ROLE_ID"); + --data '{ "name": "ROLE_NAME", "description": "ROLE_DESC" }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/roles/ROLE_ID"); var request = new RestRequest(Method.PATCH); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{ \"name\": \"ROLE_NAME\", \"description\": \"ROLE_DESC\" }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "name": "ROLE_NAME", "description": "ROLE_DESC" }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -52,7 +59,7 @@ func main() { url := "https://{yourDomain}/api/v2/roles/ROLE_ID" - payload := strings.NewReader("{ \"name\": \"ROLE_NAME\", \"description\": \"ROLE_DESC\" }") + payload := strings.NewReader("{ "name": "ROLE_NAME", "description": "ROLE_DESC" }") req, _ := http.NewRequest("PATCH", url, payload) @@ -68,14 +75,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/roles/ROLE_ID") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/roles/ROLE_ID") .header("content-type", "application/json") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ \"name\": \"ROLE_NAME\", \"description\": \"ROLE_DESC\" }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "name": "ROLE_NAME", "description": "ROLE_DESC" }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -92,8 +103,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @@ -120,8 +133,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/roles/ROLE_ID", @@ -131,7 +146,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{ \"name\": \"ROLE_NAME\", \"description\": \"ROLE_DESC\" }", + CURLOPT_POSTFIELDS => "{ "name": "ROLE_NAME", "description": "ROLE_DESC" }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "cache-control: no-cache", @@ -148,12 +163,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"name\": \"ROLE_NAME\", \"description\": \"ROLE_DESC\" }" +payload = "{ "name": "ROLE_NAME", "description": "ROLE_DESC" }" headers = { 'content-type': "application/json", @@ -166,8 +183,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/roles/ROLE_ID", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -181,11 +200,13 @@ request = Net::HTTP::Patch.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ \"name\": \"ROLE_NAME\", \"description\": \"ROLE_DESC\" }" +request.body = "{ "name": "ROLE_NAME", "description": "ROLE_DESC" }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -216,20 +237,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
    diff --git a/main/docs/ja-jp/manage-users/access-control/configure-core-rbac/roles/remove-permissions-from-roles.mdx b/main/docs/ja-jp/manage-users/access-control/configure-core-rbac/roles/remove-permissions-from-roles.mdx index bd332a4f9..51c8760ff 100644 --- a/main/docs/ja-jp/manage-users/access-control/configure-core-rbac/roles/remove-permissions-from-roles.mdx +++ b/main/docs/ja-jp/manage-users/access-control/configure-core-rbac/roles/remove-permissions-from-roles.mdx @@ -10,6 +10,7 @@ permalink: "remove-permissions-from-roles" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Auth0 DashboardまたはManagement APIを使用して、ロールに割り当てられた[権限](/docs/ja-jp/manage-users/access-control/rbac)を削除することができます。割り当てられた権限とロールは、API Authorization Core機能セットで使用されます。 @@ -26,20 +27,26 @@ Role-based Access Control(RBAC)を正しく動作させるには、Dashboard `DELETE`呼び出しを[ロール権限削除エンドポイント](https://auth0.com/docs/api/management/v2#!/Roles/delete_role_permission_assignment)に対して行います。`ROLE_ID`、`MGMT_API_ACCESS_TOKEN`、`API_ID`、および`PERMISSION_NAME`のプレースホルダーをそれぞれロールID、Management APIのアクセストークン、API ID、権限名に置き換えます。 -export const codeExample1 = `curl --request DELETE \ + +```bash cURL +curl --request DELETE \ --url 'https://{yourDomain}/api/v2/roles/ROLE_ID/permissions' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{ "permissions": [ { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" } ] }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/roles/ROLE_ID/permissions"); + --data '{ "permissions": [ { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" } ] }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/roles/ROLE_ID/permissions"); var request = new RestRequest(Method.DELETE); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{ \"permissions\": [ { \"resource_server_identifier\": \"API_ID\", \"permission_name\": \"PERMISSION_NAME\" }, { \"resource_server_identifier\": \"API_ID\", \"permission_name\": \"PERMISSION_NAME\" } ] }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "permissions": [ { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" } ] }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -52,7 +59,7 @@ func main() { url := "https://{yourDomain}/api/v2/roles/ROLE_ID/permissions" - payload := strings.NewReader("{ \"permissions\": [ { \"resource_server_identifier\": \"API_ID\", \"permission_name\": \"PERMISSION_NAME\" }, { \"resource_server_identifier\": \"API_ID\", \"permission_name\": \"PERMISSION_NAME\" } ] }") + payload := strings.NewReader("{ "permissions": [ { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" } ] }") req, _ := http.NewRequest("DELETE", url, payload) @@ -68,14 +75,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.delete("https://{yourDomain}/api/v2/roles/ROLE_ID/permissions") +} +``` +```java Java +HttpResponse response = Unirest.delete("https://{yourDomain}/api/v2/roles/ROLE_ID/permissions") .header("content-type", "application/json") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ \"permissions\": [ { \"resource_server_identifier\": \"API_ID\", \"permission_name\": \"PERMISSION_NAME\" }, { \"resource_server_identifier\": \"API_ID\", \"permission_name\": \"PERMISSION_NAME\" } ] }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "permissions": [ { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" } ] }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'DELETE', @@ -97,8 +108,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @@ -124,8 +137,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/roles/ROLE_ID/permissions", @@ -135,7 +150,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "DELETE", - CURLOPT_POSTFIELDS => "{ \"permissions\": [ { \"resource_server_identifier\": \"API_ID\", \"permission_name\": \"PERMISSION_NAME\" }, { \"resource_server_identifier\": \"API_ID\", \"permission_name\": \"PERMISSION_NAME\" } ] }", + CURLOPT_POSTFIELDS => "{ "permissions": [ { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" } ] }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "cache-control: no-cache", @@ -152,12 +167,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"permissions\": [ { \"resource_server_identifier\": \"API_ID\", \"permission_name\": \"PERMISSION_NAME\" }, { \"resource_server_identifier\": \"API_ID\", \"permission_name\": \"PERMISSION_NAME\" } ] }" +payload = "{ "permissions": [ { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" } ] }" headers = { 'content-type': "application/json", @@ -170,8 +187,10 @@ conn.request("DELETE", "/{yourDomain}/api/v2/roles/ROLE_ID/permissions", payload res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -185,11 +204,13 @@ request = Net::HTTP::Delete.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ \"permissions\": [ { \"resource_server_identifier\": \"API_ID\", \"permission_name\": \"PERMISSION_NAME\" }, { \"resource_server_identifier\": \"API_ID\", \"permission_name\": \"PERMISSION_NAME\" } ] }" +request.body = "{ "permissions": [ { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" } ] }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -226,20 +247,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
    diff --git a/main/docs/ja-jp/manage-users/access-control/configure-core-rbac/roles/view-role-permissions.mdx b/main/docs/ja-jp/manage-users/access-control/configure-core-rbac/roles/view-role-permissions.mdx index 901130364..1ae622cd7 100644 --- a/main/docs/ja-jp/manage-users/access-control/configure-core-rbac/roles/view-role-permissions.mdx +++ b/main/docs/ja-jp/manage-users/access-control/configure-core-rbac/roles/view-role-permissions.mdx @@ -10,6 +10,7 @@ permalink: "view-role-permissions" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Auth0 DashboardまたはManagement APIを使用して、ロールに追加された[権限](/docs/ja-jp/manage-users/access-control/rbac)を表示できます。割り当てられた権限とロールは、API Authorization Core機能セットで使用されます。 @@ -50,14 +51,20 @@ Role-based Access Control(RBAC)を正しく動作させるには、Dashboard `GET`呼び出しを[ロール権限取得エンドポイント](https://auth0.com/docs/api/management/v2#!/Roles/get_role_permission)に対して行います。必ず、`ROLE_ID`と`MGMT_API_ACCESS_TOKEN`のプレースホルダーの値を、それぞれご自身のロールIDとManagement APIのアクセストークンに置き換えてください。 -export const codeExample1 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/roles/ROLE_ID/permissions' \ - --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/roles/ROLE_ID/permissions"); + --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/roles/ROLE_ID/permissions"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -81,11 +88,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/roles/ROLE_ID/permissions") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/roles/ROLE_ID/permissions") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -97,8 +108,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN" }; @@ -118,8 +131,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/roles/ROLE_ID/permissions", @@ -143,8 +158,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -155,8 +172,10 @@ conn.request("GET", "/{yourDomain}/api/v2/roles/ROLE_ID/permissions", headers=he res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -170,8 +189,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer MGMT_API_ACCESS_TOKEN"] @@ -191,20 +212,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
    diff --git a/main/docs/ja-jp/manage-users/my-account-api.mdx b/main/docs/ja-jp/manage-users/my-account-api.mdx index 022c90d7a..7860368a2 100644 --- a/main/docs/ja-jp/manage-users/my-account-api.mdx +++ b/main/docs/ja-jp/manage-users/my-account-api.mdx @@ -10,6 +10,7 @@ permalink: "my-account-api" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; @@ -130,12 +131,18 @@ The My Account API supports the following scopes: ##### Step 1: Request authorization code -export const codeExample1 = `curl --request GET \ - --url 'https://{yourDomain}/authorize?response_type=code&client_id={yourClientId}&redirect_uri=%7ByourRedirectUri%7D&scope=create%3Ame%3Aauthentication_methods&offline_access=&audience=https%3A%2F%2F{yourDomain}%2Fme%2F'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/authorize?response_type=code&client_id={yourClientId}&redirect_uri=%7ByourRedirectUri%7D&scope=create%3Ame%3Aauthentication_methods&offline_access=&audience=https%3A%2F%2F{yourDomain}%2Fme%2F"); + +```bash cURL +curl --request GET \ + --url 'https://{yourDomain}/authorize?response_type=code&client_id={yourClientId}&redirect_uri=%7ByourRedirectUri%7D&scope=create%3Ame%3Aauthentication_methods&offline_access=&audience=https%3A%2F%2F{yourDomain}%2Fme%2F' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/authorize?response_type=code&client_id={yourClientId}&redirect_uri=%7ByourRedirectUri%7D&scope=create%3Ame%3Aauthentication_methods&offline_access=&audience=https%3A%2F%2F{yourDomain}%2Fme%2F"); var request = new RestRequest(Method.GET); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -157,10 +164,14 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.get("https://{yourDomain}/authorize?response_type=code&client_id={yourClientId}&redirect_uri=%7ByourRedirectUri%7D&scope=create%3Ame%3Aauthentication_methods&offline_access=&audience=https%3A%2F%2F{yourDomain}%2Fme%2F") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/authorize?response_type=code&client_id={yourClientId}&redirect_uri=%7ByourRedirectUri%7D&scope=create%3Ame%3Aauthentication_methods&offline_access=&audience=https%3A%2F%2F{yourDomain}%2Fme%2F") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -179,8 +190,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://{yourDomain}/authorize?response_type=code&client_id={yourClientId}&redirect_uri=%7ByourRedirectUri%7D&scope=create%3Ame%3Aauthentication_methods&offline_access=&audience=https%3A%2F%2F{yourDomain}%2Fme%2F"] cachePolicy:NSURLRequestUseProtocolCachePolicy @@ -197,8 +210,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/authorize?response_type=code&client_id={yourClientId}&redirect_uri=%7ByourRedirectUri%7D&scope=create%3Ame%3Aauthentication_methods&offline_access=&audience=https%3A%2F%2F{yourDomain}%2Fme%2F", @@ -219,8 +234,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -229,8 +246,10 @@ conn.request("GET", "/{yourDomain}/authorize?response_type=code&client_id={yourC res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -243,8 +262,10 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Get.new(url) response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let request = NSMutableURLRequest(url: NSURL(string: "https://{yourDomain}/authorize?response_type=code&client_id={yourClientId}&redirect_uri=%7ByourRedirectUri%7D&scope=create%3Ame%3Aauthentication_methods&offline_access=&audience=https%3A%2F%2F{yourDomain}%2Fme%2F")! as URL, cachePolicy: .useProtocolCachePolicy, @@ -261,33 +282,28 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ##### Step 2: Exchange code for access token -export const codeExample11 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/json' \ - --data '{"grant_type": "authorization_code","client_id": "{yourClientId}","client_secret": "{yourClientId}","code": "{yourAuthorizationCode}","redirect_uri": "{yourRedirectUri}","audience": "{yourAudience}","scope": "create:me:authentication_methods","offline_access": ""}'`; -export const codeExample12 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data '{"grant_type": "authorization_code","client_id": "{yourClientId}","client_secret": "{yourClientId}","code": "{yourAuthorizationCode}","redirect_uri": "{yourRedirectUri}","audience": "{yourAudience}","scope": "create:me:authentication_methods","offline_access": ""}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\"grant_type\": \"authorization_code\",\"client_id\": \"{yourClientId}\",\"client_secret\": \"{yourClientId}\",\"code\": \"{yourAuthorizationCode}\",\"redirect_uri\": \"{yourRedirectUri}\",\"audience\": \"{yourAudience}\",\"scope\": \"create:me:authentication_methods\",\"offline_access\": \"\"}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample13 = `package main +request.AddParameter("application/json", "{"grant_type": "authorization_code","client_id": "{yourClientId}","client_secret": "{yourClientId}","code": "{yourAuthorizationCode}","redirect_uri": "{yourRedirectUri}","audience": "{yourAudience}","scope": "create:me:authentication_methods","offline_access": ""}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -300,7 +316,7 @@ func main() { url := "https://{yourDomain}/oauth/token" - payload := strings.NewReader("{\"grant_type\": \"authorization_code\",\"client_id\": \"{yourClientId}\",\"client_secret\": \"{yourClientId}\",\"code\": \"{yourAuthorizationCode}\",\"redirect_uri\": \"{yourRedirectUri}\",\"audience\": \"{yourAudience}\",\"scope\": \"create:me:authentication_methods\",\"offline_access\": \"\"}") + payload := strings.NewReader("{"grant_type": "authorization_code","client_id": "{yourClientId}","client_secret": "{yourClientId}","code": "{yourAuthorizationCode}","redirect_uri": "{yourRedirectUri}","audience": "{yourAudience}","scope": "create:me:authentication_methods","offline_access": ""}") req, _ := http.NewRequest("POST", url, payload) @@ -314,12 +330,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample14 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/json") - .body("{\"grant_type\": \"authorization_code\",\"client_id\": \"{yourClientId}\",\"client_secret\": \"{yourClientId}\",\"code\": \"{yourAuthorizationCode}\",\"redirect_uri\": \"{yourRedirectUri}\",\"audience\": \"{yourAudience}\",\"scope\": \"create:me:authentication_methods\",\"offline_access\": \"\"}") - .asString();`; -export const codeExample15 = `var axios = require("axios").default; + .body("{"grant_type": "authorization_code","client_id": "{yourClientId}","client_secret": "{yourClientId}","code": "{yourAuthorizationCode}","redirect_uri": "{yourRedirectUri}","audience": "{yourAudience}","scope": "create:me:authentication_methods","offline_access": ""}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -341,8 +361,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample16 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json" }; NSDictionary *parameters = @{ @"grant_type": @"authorization_code", @@ -373,8 +395,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -384,7 +408,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{\"grant_type\": \"authorization_code\",\"client_id\": \"{yourClientId}\",\"client_secret\": \"{yourClientId}\",\"code\": \"{yourAuthorizationCode}\",\"redirect_uri\": \"{yourRedirectUri}\",\"audience\": \"{yourAudience}\",\"scope\": \"create:me:authentication_methods\",\"offline_access\": \"\"}", + CURLOPT_POSTFIELDS => "{"grant_type": "authorization_code","client_id": "{yourClientId}","client_secret": "{yourClientId}","code": "{yourAuthorizationCode}","redirect_uri": "{yourRedirectUri}","audience": "{yourAudience}","scope": "create:me:authentication_methods","offline_access": ""}", CURLOPT_HTTPHEADER => [ "content-type: application/json" ], @@ -399,12 +423,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"grant_type\": \"authorization_code\",\"client_id\": \"{yourClientId}\",\"client_secret\": \"{yourClientId}\",\"code\": \"{yourAuthorizationCode}\",\"redirect_uri\": \"{yourRedirectUri}\",\"audience\": \"{yourAudience}\",\"scope\": \"create:me:authentication_methods\",\"offline_access\": \"\"}" +payload = "{"grant_type": "authorization_code","client_id": "{yourClientId}","client_secret": "{yourClientId}","code": "{yourAuthorizationCode}","redirect_uri": "{yourRedirectUri}","audience": "{yourAudience}","scope": "create:me:authentication_methods","offline_access": ""}" headers = { 'content-type': "application/json" } @@ -413,8 +439,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -426,11 +454,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["content-type"] = 'application/json' -request.body = "{\"grant_type\": \"authorization_code\",\"client_id\": \"{yourClientId}\",\"client_secret\": \"{yourClientId}\",\"code\": \"{yourAuthorizationCode}\",\"redirect_uri\": \"{yourRedirectUri}\",\"audience\": \"{yourAudience}\",\"scope\": \"create:me:authentication_methods\",\"offline_access\": \"\"}" +request.body = "{"grant_type": "authorization_code","client_id": "{yourClientId}","client_secret": "{yourClientId}","code": "{yourAuthorizationCode}","redirect_uri": "{yourRedirectUri}","audience": "{yourAudience}","scope": "create:me:authentication_methods","offline_access": ""}" response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/json"] let parameters = [ @@ -463,35 +493,30 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + #### Embedded login with native passkeys ##### Step 1: Request login challenge -export const codeExample21 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/passkey/challenge' \ --header 'content-type: application/json' \ - --data '{"client_id": "{yourDomain}"}'`; -export const codeExample22 = `var client = new RestClient("https://{yourDomain}/passkey/challenge"); + --data '{"client_id": "{yourDomain}"}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/passkey/challenge"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\"client_id\": \"{yourDomain}\"}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample23 = `package main +request.AddParameter("application/json", "{"client_id": "{yourDomain}"}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -504,7 +529,7 @@ func main() { url := "https://{yourDomain}/passkey/challenge" - payload := strings.NewReader("{\"client_id\": \"{yourDomain}\"}") + payload := strings.NewReader("{"client_id": "{yourDomain}"}") req, _ := http.NewRequest("POST", url, payload) @@ -518,12 +543,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample24 = `HttpResponse response = Unirest.post("https://{yourDomain}/passkey/challenge") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/passkey/challenge") .header("content-type", "application/json") - .body("{\"client_id\": \"{yourDomain}\"}") - .asString();`; -export const codeExample25 = `var axios = require("axios").default; + .body("{"client_id": "{yourDomain}"}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -536,8 +565,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample26 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json" }; NSDictionary *parameters = @{ @"client_id": @"{yourDomain}" }; @@ -561,8 +592,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample27 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/passkey/challenge", @@ -572,7 +605,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{\"client_id\": \"{yourDomain}\"}", + CURLOPT_POSTFIELDS => "{"client_id": "{yourDomain}"}", CURLOPT_HTTPHEADER => [ "content-type: application/json" ], @@ -587,12 +620,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample28 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"client_id\": \"{yourDomain}\"}" +payload = "{"client_id": "{yourDomain}"}" headers = { 'content-type': "application/json" } @@ -601,8 +636,10 @@ conn.request("POST", "/{yourDomain}/passkey/challenge", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample29 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -614,11 +651,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["content-type"] = 'application/json' -request.body = "{\"client_id\": \"{yourDomain}\"}" +request.body = "{"client_id": "{yourDomain}"}" response = http.request(request) -puts response.read_body`; -export const codeExample30 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/json"] let parameters = ["client_id": "{yourDomain}"] as [String : Any] @@ -642,33 +681,28 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ##### Step 2: Authenticate existing user -export const codeExample31 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/json' \ - --data '{ "grant_type": "urn:okta:params:oauth:grant-type:webauthn", "client_id": "{yourClientId}", "scope": "create:me:authentication_methods offline_access", "audience": "https://{yourDomain}/me/" "auth_session": "{sessionIdFromTheFirstRequest}", "authn_response": "{authenticatorResponse}"}'`; -export const codeExample32 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data '{ "grant_type": "urn:okta:params:oauth:grant-type:webauthn", "client_id": "{yourClientId}", "scope": "create:me:authentication_methods offline_access", "audience": "https://{yourDomain}/me/" "auth_session": "{sessionIdFromTheFirstRequest}", "authn_response": "{authenticatorResponse}"}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{ \"grant_type\": \"urn:okta:params:oauth:grant-type:webauthn\", \"client_id\": \"{yourClientId}\", \"scope\": \"create:me:authentication_methods offline_access\", \"audience\": \"https://{yourDomain}/me/\" \"auth_session\": \"{sessionIdFromTheFirstRequest}\", \"authn_response\": \"{authenticatorResponse}\"}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample33 = `package main +request.AddParameter("application/json", "{ "grant_type": "urn:okta:params:oauth:grant-type:webauthn", "client_id": "{yourClientId}", "scope": "create:me:authentication_methods offline_access", "audience": "https://{yourDomain}/me/" "auth_session": "{sessionIdFromTheFirstRequest}", "authn_response": "{authenticatorResponse}"}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -681,7 +715,7 @@ func main() { url := "https://{yourDomain}/oauth/token" - payload := strings.NewReader("{ \"grant_type\": \"urn:okta:params:oauth:grant-type:webauthn\", \"client_id\": \"{yourClientId}\", \"scope\": \"create:me:authentication_methods offline_access\", \"audience\": \"https://{yourDomain}/me/\" \"auth_session\": \"{sessionIdFromTheFirstRequest}\", \"authn_response\": \"{authenticatorResponse}\"}") + payload := strings.NewReader("{ "grant_type": "urn:okta:params:oauth:grant-type:webauthn", "client_id": "{yourClientId}", "scope": "create:me:authentication_methods offline_access", "audience": "https://{yourDomain}/me/" "auth_session": "{sessionIdFromTheFirstRequest}", "authn_response": "{authenticatorResponse}"}") req, _ := http.NewRequest("POST", url, payload) @@ -695,12 +729,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample34 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/json") - .body("{ \"grant_type\": \"urn:okta:params:oauth:grant-type:webauthn\", \"client_id\": \"{yourClientId}\", \"scope\": \"create:me:authentication_methods offline_access\", \"audience\": \"https://{yourDomain}/me/\" \"auth_session\": \"{sessionIdFromTheFirstRequest}\", \"authn_response\": \"{authenticatorResponse}\"}") - .asString();`; -export const codeExample35 = `var axios = require("axios").default; + .body("{ "grant_type": "urn:okta:params:oauth:grant-type:webauthn", "client_id": "{yourClientId}", "scope": "create:me:authentication_methods offline_access", "audience": "https://{yourDomain}/me/" "auth_session": "{sessionIdFromTheFirstRequest}", "authn_response": "{authenticatorResponse}"}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -713,8 +751,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample36 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json" }; @@ -737,8 +777,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample37 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -748,7 +790,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{ \"grant_type\": \"urn:okta:params:oauth:grant-type:webauthn\", \"client_id\": \"{yourClientId}\", \"scope\": \"create:me:authentication_methods offline_access\", \"audience\": \"https://{yourDomain}/me/\" \"auth_session\": \"{sessionIdFromTheFirstRequest}\", \"authn_response\": \"{authenticatorResponse}\"}", + CURLOPT_POSTFIELDS => "{ "grant_type": "urn:okta:params:oauth:grant-type:webauthn", "client_id": "{yourClientId}", "scope": "create:me:authentication_methods offline_access", "audience": "https://{yourDomain}/me/" "auth_session": "{sessionIdFromTheFirstRequest}", "authn_response": "{authenticatorResponse}"}", CURLOPT_HTTPHEADER => [ "content-type: application/json" ], @@ -763,12 +805,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample38 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"grant_type\": \"urn:okta:params:oauth:grant-type:webauthn\", \"client_id\": \"{yourClientId}\", \"scope\": \"create:me:authentication_methods offline_access\", \"audience\": \"https://{yourDomain}/me/\" \"auth_session\": \"{sessionIdFromTheFirstRequest}\", \"authn_response\": \"{authenticatorResponse}\"}" +payload = "{ "grant_type": "urn:okta:params:oauth:grant-type:webauthn", "client_id": "{yourClientId}", "scope": "create:me:authentication_methods offline_access", "audience": "https://{yourDomain}/me/" "auth_session": "{sessionIdFromTheFirstRequest}", "authn_response": "{authenticatorResponse}"}" headers = { 'content-type': "application/json" } @@ -777,8 +821,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample39 = `rrequire 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +rrequire 'uri' require 'net/http' require 'openssl' @@ -790,11 +836,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["content-type"] = 'application/json' -request.body = "{ \"grant_type\": \"urn:okta:params:oauth:grant-type:webauthn\", \"client_id\": \"{yourClientId}\", \"scope\": \"create:me:authentication_methods offline_access\", \"audience\": \"https://{yourDomain}/me/\" \"auth_session\": \"{sessionIdFromTheFirstRequest}\", \"authn_response\": \"{authenticatorResponse}\"}" +request.body = "{ "grant_type": "urn:okta:params:oauth:grant-type:webauthn", "client_id": "{yourClientId}", "scope": "create:me:authentication_methods offline_access", "audience": "https://{yourDomain}/me/" "auth_session": "{sessionIdFromTheFirstRequest}", "authn_response": "{authenticatorResponse}"}" response = http.request(request) -puts response.read_body`; -export const codeExample40 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/json"] @@ -817,20 +865,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ## Rate limits diff --git a/main/docs/ja-jp/manage-users/organizations/configure-organizations/add-member-roles.mdx b/main/docs/ja-jp/manage-users/organizations/configure-organizations/add-member-roles.mdx index 29b9708bd..d27e7bb08 100644 --- a/main/docs/ja-jp/manage-users/organizations/configure-organizations/add-member-roles.mdx +++ b/main/docs/ja-jp/manage-users/organizations/configure-organizations/add-member-roles.mdx @@ -9,6 +9,9 @@ permalink: "add-member-roles" 'twitter:description': "Auth0 DashboardまたはManagement APIを使用して組織メンバーにロールを追加する方法を学びます。" --- + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + それぞれの[組織](/docs/ja-jp/manage-users/organizations/organizations-overview)メンバーには1つ以上のロールを割り当てることができます。ロールはユーザーが組織を通してログインするときに適用されます。ロールとその振る舞いについては、「[ロールベースのアクセス制御](/docs/ja-jp/manage-users/access-control/rbac)」をお読みください。 Auth0 DashboardまたはManagement APIを使用して、組織内のメンバーにロールを追加できます。 @@ -29,7 +32,7 @@ Auth0 Dashboardを介して組織メンバーにロールを追加するには Management APIを使ってロールを組織メンバーに追加するには、次を行います: `POST`呼び出しを`Create Organization Member Roles`(組織メンバーのロール作成)エンドポイントに対して行います。`ORG_ID`、`MGMT_API_ACCESS_TOKEN`、`USER_ID`、`ROLE_ID`のプレースホルダーをそれぞれ組織ID、Management APIのアクセストークン、ユーザーID、ロールIDで置き換えます。 - + ```bash cURL lines curl --request POST \ @@ -248,7 +251,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + {/* **Find Your Auth0 Domain** diff --git a/main/docs/ja-jp/manage-users/organizations/configure-organizations/assign-members.mdx b/main/docs/ja-jp/manage-users/organizations/configure-organizations/assign-members.mdx index 2290caa52..12e5b98e0 100644 --- a/main/docs/ja-jp/manage-users/organizations/configure-organizations/assign-members.mdx +++ b/main/docs/ja-jp/manage-users/organizations/configure-organizations/assign-members.mdx @@ -9,6 +9,9 @@ permalink: "assign-members" 'twitter:description': "Auth0 DashboardまたはManagement APIを使ってメンバーを組織に直接割り当てる方法について説明します。" --- + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + [組織](/docs/ja-jp/manage-users/organizations/organizations-overview)にメンバーを割り当てるには、先にテナント内に[ユーザーを作成](/docs/ja-jp/manage-users/user-accounts/create-users)しておく必要があります。ユーザーが見つからない場合には、代わりに[ユーザーを招待](/docs/ja-jp/manage-users/organizations/configure-organizations/invite-members)することもできます。 メンバーを直接管理するには、Auth0 DashboardまたはManagement APIを使用することができます。 @@ -27,7 +30,7 @@ Management APIでメンバーを割り当てるには、以下を行います。 `Create Organization Members`エンドポイントに`POST`呼び出しを行います。必ず、`ORG_ID`、`MGMT_API_ACCESS_TOKEN`、および`USER_ID`のプレースホルダーの値を、それぞれ組織ID、Management APIのアクセストークン、ユーザーIDに置き換えます。 - + ```bash cURL lines curl --request POST \ @@ -246,7 +249,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + diff --git a/main/docs/ja-jp/manage-users/organizations/configure-organizations/create-organizations.mdx b/main/docs/ja-jp/manage-users/organizations/configure-organizations/create-organizations.mdx index 561f6ef7e..951ecad18 100644 --- a/main/docs/ja-jp/manage-users/organizations/configure-organizations/create-organizations.mdx +++ b/main/docs/ja-jp/manage-users/organizations/configure-organizations/create-organizations.mdx @@ -10,6 +10,7 @@ permalink: "create-organizations" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; [組織](/docs/ja-jp/manage-users/organizations/organizations-overview)はAuth0 DashboardまたはManagement APIを使って作成することができます。 @@ -75,20 +76,26 @@ Management APIを使用して組織を作成するには、以下を行います `組織作成`エンドポイントに`POST`呼び出しを行います。placeholder値は必ずテナントからの適切な値に置き換えてください。詳細については、以下のパラメーターの表を参照してください。 -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/api/v2/organizations' \ --header 'authorization: Bearer {MGMT_API_ACCESS_TOKEN}' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{ "name": "ORG_NAME", "display_name": "ORG_DISPLAY_NAME", "branding": [ { "logo_url": "{orgLogo}", "colors": [ { "primary": "{orgPrimaryColor}", "page_background": "{orgPageBackground}" } ] } ], "metadata": [ { "{key}": "{value}", "{key}": "{value}", "{key}": "{value}" } ] }, "enabled_connections": [ { "connection_id": "{connectionId}", "assign_membership_on_login": "{assignMembershipOption}" }, { "connection_id": "{connectionId}", "assign_membership_on_login": "{assignMembershipOption}" } ] }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/organizations"); + --data '{ "name": "ORG_NAME", "display_name": "ORG_DISPLAY_NAME", "branding": [ { "logo_url": "{orgLogo}", "colors": [ { "primary": "{orgPrimaryColor}", "page_background": "{orgPageBackground}" } ] } ], "metadata": [ { "{key}": "{value}", "{key}": "{value}", "{key}": "{value}" } ] }, "enabled_connections": [ { "connection_id": "{connectionId}", "assign_membership_on_login": "{assignMembershipOption}" }, { "connection_id": "{connectionId}", "assign_membership_on_login": "{assignMembershipOption}" } ] }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/organizations"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer {MGMT_API_ACCESS_TOKEN}"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{ \"name\": \"ORG_NAME\", \"display_name\": \"ORG_DISPLAY_NAME\", \"branding\": [ { \"logo_url\": \"{orgLogo}\", \"colors\": [ { \"primary\": \"{orgPrimaryColor}\", \"page_background\": \"{orgPageBackground}\" } ] } ], \"metadata\": [ { \"{key}\": \"{value}\", \"{key}\": \"{value}\", \"{key}\": \"{value}\" } ] }, \"enabled_connections\": [ { \"connection_id\": \"{connectionId}\", \"assign_membership_on_login\": \"{assignMembershipOption}\" }, { \"connection_id\": \"{connectionId}\", \"assign_membership_on_login\": \"{assignMembershipOption}\" } ] }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "name": "ORG_NAME", "display_name": "ORG_DISPLAY_NAME", "branding": [ { "logo_url": "{orgLogo}", "colors": [ { "primary": "{orgPrimaryColor}", "page_background": "{orgPageBackground}" } ] } ], "metadata": [ { "{key}": "{value}", "{key}": "{value}", "{key}": "{value}" } ] }, "enabled_connections": [ { "connection_id": "{connectionId}", "assign_membership_on_login": "{assignMembershipOption}" }, { "connection_id": "{connectionId}", "assign_membership_on_login": "{assignMembershipOption}" } ] }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -101,7 +108,7 @@ func main() { url := "https://{yourDomain}/api/v2/organizations" - payload := strings.NewReader("{ \"name\": \"ORG_NAME\", \"display_name\": \"ORG_DISPLAY_NAME\", \"branding\": [ { \"logo_url\": \"{orgLogo}\", \"colors\": [ { \"primary\": \"{orgPrimaryColor}\", \"page_background\": \"{orgPageBackground}\" } ] } ], \"metadata\": [ { \"{key}\": \"{value}\", \"{key}\": \"{value}\", \"{key}\": \"{value}\" } ] }, \"enabled_connections\": [ { \"connection_id\": \"{connectionId}\", \"assign_membership_on_login\": \"{assignMembershipOption}\" }, { \"connection_id\": \"{connectionId}\", \"assign_membership_on_login\": \"{assignMembershipOption}\" } ] }") + payload := strings.NewReader("{ "name": "ORG_NAME", "display_name": "ORG_DISPLAY_NAME", "branding": [ { "logo_url": "{orgLogo}", "colors": [ { "primary": "{orgPrimaryColor}", "page_background": "{orgPageBackground}" } ] } ], "metadata": [ { "{key}": "{value}", "{key}": "{value}", "{key}": "{value}" } ] }, "enabled_connections": [ { "connection_id": "{connectionId}", "assign_membership_on_login": "{assignMembershipOption}" }, { "connection_id": "{connectionId}", "assign_membership_on_login": "{assignMembershipOption}" } ] }") req, _ := http.NewRequest("POST", url, payload) @@ -117,14 +124,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/organizations") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/organizations") .header("content-type", "application/json") .header("authorization", "Bearer {MGMT_API_ACCESS_TOKEN}") .header("cache-control", "no-cache") - .body("{ \"name\": \"ORG_NAME\", \"display_name\": \"ORG_DISPLAY_NAME\", \"branding\": [ { \"logo_url\": \"{orgLogo}\", \"colors\": [ { \"primary\": \"{orgPrimaryColor}\", \"page_background\": \"{orgPageBackground}\" } ] } ], \"metadata\": [ { \"{key}\": \"{value}\", \"{key}\": \"{value}\", \"{key}\": \"{value}\" } ] }, \"enabled_connections\": [ { \"connection_id\": \"{connectionId}\", \"assign_membership_on_login\": \"{assignMembershipOption}\" }, { \"connection_id\": \"{connectionId}\", \"assign_membership_on_login\": \"{assignMembershipOption}\" } ] }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "name": "ORG_NAME", "display_name": "ORG_DISPLAY_NAME", "branding": [ { "logo_url": "{orgLogo}", "colors": [ { "primary": "{orgPrimaryColor}", "page_background": "{orgPageBackground}" } ] } ], "metadata": [ { "{key}": "{value}", "{key}": "{value}", "{key}": "{value}" } ] }, "enabled_connections": [ { "connection_id": "{connectionId}", "assign_membership_on_login": "{assignMembershipOption}" }, { "connection_id": "{connectionId}", "assign_membership_on_login": "{assignMembershipOption}" } ] }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -141,8 +152,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer {MGMT_API_ACCESS_TOKEN}", @@ -167,8 +180,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/organizations", @@ -178,7 +193,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{ \"name\": \"ORG_NAME\", \"display_name\": \"ORG_DISPLAY_NAME\", \"branding\": [ { \"logo_url\": \"{orgLogo}\", \"colors\": [ { \"primary\": \"{orgPrimaryColor}\", \"page_background\": \"{orgPageBackground}\" } ] } ], \"metadata\": [ { \"{key}\": \"{value}\", \"{key}\": \"{value}\", \"{key}\": \"{value}\" } ] }, \"enabled_connections\": [ { \"connection_id\": \"{connectionId}\", \"assign_membership_on_login\": \"{assignMembershipOption}\" }, { \"connection_id\": \"{connectionId}\", \"assign_membership_on_login\": \"{assignMembershipOption}\" } ] }", + CURLOPT_POSTFIELDS => "{ "name": "ORG_NAME", "display_name": "ORG_DISPLAY_NAME", "branding": [ { "logo_url": "{orgLogo}", "colors": [ { "primary": "{orgPrimaryColor}", "page_background": "{orgPageBackground}" } ] } ], "metadata": [ { "{key}": "{value}", "{key}": "{value}", "{key}": "{value}" } ] }, "enabled_connections": [ { "connection_id": "{connectionId}", "assign_membership_on_login": "{assignMembershipOption}" }, { "connection_id": "{connectionId}", "assign_membership_on_login": "{assignMembershipOption}" } ] }", CURLOPT_HTTPHEADER => [ "authorization: Bearer {MGMT_API_ACCESS_TOKEN}", "cache-control: no-cache", @@ -195,12 +210,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"name\": \"ORG_NAME\", \"display_name\": \"ORG_DISPLAY_NAME\", \"branding\": [ { \"logo_url\": \"{orgLogo}\", \"colors\": [ { \"primary\": \"{orgPrimaryColor}\", \"page_background\": \"{orgPageBackground}\" } ] } ], \"metadata\": [ { \"{key}\": \"{value}\", \"{key}\": \"{value}\", \"{key}\": \"{value}\" } ] }, \"enabled_connections\": [ { \"connection_id\": \"{connectionId}\", \"assign_membership_on_login\": \"{assignMembershipOption}\" }, { \"connection_id\": \"{connectionId}\", \"assign_membership_on_login\": \"{assignMembershipOption}\" } ] }" +payload = "{ "name": "ORG_NAME", "display_name": "ORG_DISPLAY_NAME", "branding": [ { "logo_url": "{orgLogo}", "colors": [ { "primary": "{orgPrimaryColor}", "page_background": "{orgPageBackground}" } ] } ], "metadata": [ { "{key}": "{value}", "{key}": "{value}", "{key}": "{value}" } ] }, "enabled_connections": [ { "connection_id": "{connectionId}", "assign_membership_on_login": "{assignMembershipOption}" }, { "connection_id": "{connectionId}", "assign_membership_on_login": "{assignMembershipOption}" } ] }" headers = { 'content-type': "application/json", @@ -213,8 +230,10 @@ conn.request("POST", "/{yourDomain}/api/v2/organizations", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -228,11 +247,13 @@ request = Net::HTTP::Post.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer {MGMT_API_ACCESS_TOKEN}' request["cache-control"] = 'no-cache' -request.body = "{ \"name\": \"ORG_NAME\", \"display_name\": \"ORG_DISPLAY_NAME\", \"branding\": [ { \"logo_url\": \"{orgLogo}\", \"colors\": [ { \"primary\": \"{orgPrimaryColor}\", \"page_background\": \"{orgPageBackground}\" } ] } ], \"metadata\": [ { \"{key}\": \"{value}\", \"{key}\": \"{value}\", \"{key}\": \"{value}\" } ] }, \"enabled_connections\": [ { \"connection_id\": \"{connectionId}\", \"assign_membership_on_login\": \"{assignMembershipOption}\" }, { \"connection_id\": \"{connectionId}\", \"assign_membership_on_login\": \"{assignMembershipOption}\" } ] }" +request.body = "{ "name": "ORG_NAME", "display_name": "ORG_DISPLAY_NAME", "branding": [ { "logo_url": "{orgLogo}", "colors": [ { "primary": "{orgPrimaryColor}", "page_background": "{orgPageBackground}" } ] } ], "metadata": [ { "{key}": "{value}", "{key}": "{value}", "{key}": "{value}" } ] }, "enabled_connections": [ { "connection_id": "{connectionId}", "assign_membership_on_login": "{assignMembershipOption}" }, { "connection_id": "{connectionId}", "assign_membership_on_login": "{assignMembershipOption}" } ] }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -259,20 +280,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + diff --git a/main/docs/ja-jp/manage-users/organizations/configure-organizations/define-organization-behavior.mdx b/main/docs/ja-jp/manage-users/organizations/configure-organizations/define-organization-behavior.mdx index 171f7372d..c7e59152c 100644 --- a/main/docs/ja-jp/manage-users/organizations/configure-organizations/define-organization-behavior.mdx +++ b/main/docs/ja-jp/manage-users/organizations/configure-organizations/define-organization-behavior.mdx @@ -10,6 +10,7 @@ permalink: "define-organization-behavior" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Auth0でアプリケーションを表す場合には、アプリケーションが対応するべきユーザーの種類を指定することができます。個人による個人アカウントへのログインに対応するアプリケーションもあれば、[組織](/docs/ja-jp/manage-users/organizations/organizations-overview)のメンバーによる使用が目的のものもあります。それらの両方に対応するものもあります。これは組織の動作と呼ばれ、Auth0に接続するアプリケーションのそれぞれに設定することができます。 @@ -55,20 +56,26 @@ Auth0 Dashboardを使用して組織の動作を定義するには、以下を [クライアント更新エンドポイント](/docs/ja-jp/api/management/v2#!/Clients/patch_clients_by_id)に`PATCH`呼び出しを行います。`client_id`、`mgmt_api_access_token`、`organization_usage`、および`organization_require_behavior`のプレースホルダーをそれぞれクライアントID、Management APIのアクセストークン、組織の使用オプション、組織の動作オプションに置き換えます。 -export const codeExample1 = `curl --request PATCH \ + +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/clients/CLIENT_ID' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{ "organization_usage": "ORG_USAGE", "organization_require_behavior": "ORG_REQUIRE_BEHAVIOR" }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/clients/CLIENT_ID"); + --data '{ "organization_usage": "ORG_USAGE", "organization_require_behavior": "ORG_REQUIRE_BEHAVIOR" }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/clients/CLIENT_ID"); var request = new RestRequest(Method.PATCH); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{ \"organization_usage\": \"ORG_USAGE\", \"organization_require_behavior\": \"ORG_REQUIRE_BEHAVIOR\" }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "organization_usage": "ORG_USAGE", "organization_require_behavior": "ORG_REQUIRE_BEHAVIOR" }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -81,7 +88,7 @@ func main() { url := "https://{yourDomain}/api/v2/clients/CLIENT_ID" - payload := strings.NewReader("{ \"organization_usage\": \"ORG_USAGE\", \"organization_require_behavior\": \"ORG_REQUIRE_BEHAVIOR\" }") + payload := strings.NewReader("{ "organization_usage": "ORG_USAGE", "organization_require_behavior": "ORG_REQUIRE_BEHAVIOR" }") req, _ := http.NewRequest("PATCH", url, payload) @@ -97,14 +104,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/clients/CLIENT_ID") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/clients/CLIENT_ID") .header("content-type", "application/json") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ \"organization_usage\": \"ORG_USAGE\", \"organization_require_behavior\": \"ORG_REQUIRE_BEHAVIOR\" }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "organization_usage": "ORG_USAGE", "organization_require_behavior": "ORG_REQUIRE_BEHAVIOR" }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -124,8 +135,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @@ -152,8 +165,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/clients/CLIENT_ID", @@ -163,7 +178,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{ \"organization_usage\": \"ORG_USAGE\", \"organization_require_behavior\": \"ORG_REQUIRE_BEHAVIOR\" }", + CURLOPT_POSTFIELDS => "{ "organization_usage": "ORG_USAGE", "organization_require_behavior": "ORG_REQUIRE_BEHAVIOR" }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "cache-control: no-cache", @@ -180,12 +195,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"organization_usage\": \"ORG_USAGE\", \"organization_require_behavior\": \"ORG_REQUIRE_BEHAVIOR\" }" +payload = "{ "organization_usage": "ORG_USAGE", "organization_require_behavior": "ORG_REQUIRE_BEHAVIOR" }" headers = { 'content-type': "application/json", @@ -198,8 +215,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/clients/CLIENT_ID", payload, headers res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -213,11 +232,13 @@ request = Net::HTTP::Patch.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ \"organization_usage\": \"ORG_USAGE\", \"organization_require_behavior\": \"ORG_REQUIRE_BEHAVIOR\" }" +request.body = "{ "organization_usage": "ORG_USAGE", "organization_require_behavior": "ORG_REQUIRE_BEHAVIOR" }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -248,20 +269,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
    diff --git a/main/docs/ja-jp/manage-users/organizations/configure-organizations/delete-organizations.mdx b/main/docs/ja-jp/manage-users/organizations/configure-organizations/delete-organizations.mdx index fd347a316..76c2c8956 100644 --- a/main/docs/ja-jp/manage-users/organizations/configure-organizations/delete-organizations.mdx +++ b/main/docs/ja-jp/manage-users/organizations/configure-organizations/delete-organizations.mdx @@ -10,6 +10,7 @@ permalink: "delete-organizations" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; [組織](/docs/ja-jp/manage-users/organizations/organizations-overview)を削除すると、すべてのユーザーのメンバーシップと削除された組織との関連付けが削除されますが、ユーザー自体はテナントから削除されることはありません。 @@ -32,14 +33,20 @@ Auth0 Dashboardを使用して組織を削除するには、以下を行いま `DELETE`呼び出しを`Delete Organization`(組織削除)エンドポイントに対して行います。`ORG_ID`と`MGMT_API_ACCESS_TOKEN`のプレースホルダーの値を、それぞれ組織IDとManagement APIのアクセストークンに置き換えてください。 -export const codeExample1 = `curl --request DELETE \ + +```bash cURL +curl --request DELETE \ --url 'https://{yourDomain}/api/v2/organizations/ORG_ID' \ - --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/organizations/ORG_ID"); + --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/organizations/ORG_ID"); var request = new RestRequest(Method.DELETE); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -63,11 +70,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.delete("https://{yourDomain}/api/v2/organizations/ORG_ID") +} +``` +```java Java +HttpResponse response = Unirest.delete("https://{yourDomain}/api/v2/organizations/ORG_ID") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'DELETE', @@ -79,8 +90,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN" }; @@ -100,8 +113,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/organizations/ORG_ID", @@ -125,8 +140,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -137,8 +154,10 @@ conn.request("DELETE", "/{yourDomain}/api/v2/organizations/ORG_ID", headers=head res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -152,8 +171,10 @@ request = Net::HTTP::Delete.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer MGMT_API_ACCESS_TOKEN"] @@ -173,20 +194,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + diff --git a/main/docs/ja-jp/manage-users/organizations/configure-organizations/disable-connections.mdx b/main/docs/ja-jp/manage-users/organizations/configure-organizations/disable-connections.mdx index cdc790074..b584b9fe2 100644 --- a/main/docs/ja-jp/manage-users/organizations/configure-organizations/disable-connections.mdx +++ b/main/docs/ja-jp/manage-users/organizations/configure-organizations/disable-connections.mdx @@ -10,6 +10,7 @@ permalink: "disable-connections" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; [組織](/docs/ja-jp/manage-users/organizations/organizations-overview)の接続はAuth0 DashboardまたはManagement APIを使って無効にすることができます。 @@ -25,14 +26,20 @@ Auth0 Dashboardを使って接続を無効にするには、以下を行いま `Delete Organization Connections`エンドポイントに`DELETE`呼び出しを行います。必ず、`ORG_ID`、`MGMT_API_ACCESS_TOKEN`、および`CONNECTION_ID`のプレースホルダーの値をそれぞれ組織ID、Management APIのアクセストークン、接続IDに置き換えます。 -export const codeExample1 = `curl --request DELETE \ + +```bash cURL +curl --request DELETE \ --url 'https://{yourDomain}/api/v2/organizations/ORG_ID/enabled_connections/CONNECTION_ID' \ - --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/organizations/ORG_ID/enabled_connections/CONNECTION_ID"); + --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/organizations/ORG_ID/enabled_connections/CONNECTION_ID"); var request = new RestRequest(Method.DELETE); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -56,11 +63,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.delete("https://{yourDomain}/api/v2/organizations/ORG_ID/enabled_connections/CONNECTION_ID") +} +``` +```java Java +HttpResponse response = Unirest.delete("https://{yourDomain}/api/v2/organizations/ORG_ID/enabled_connections/CONNECTION_ID") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'DELETE', @@ -72,8 +83,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN" }; @@ -93,8 +106,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/organizations/ORG_ID/enabled_connections/CONNECTION_ID", @@ -118,8 +133,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -130,8 +147,10 @@ conn.request("DELETE", "/{yourDomain}/api/v2/organizations/ORG_ID/enabled_connec res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -145,8 +164,10 @@ request = Net::HTTP::Delete.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer MGMT_API_ACCESS_TOKEN"] @@ -166,20 +187,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + diff --git a/main/docs/ja-jp/manage-users/organizations/configure-organizations/enable-connections.mdx b/main/docs/ja-jp/manage-users/organizations/configure-organizations/enable-connections.mdx index a3aae0859..91af2fcbf 100644 --- a/main/docs/ja-jp/manage-users/organizations/configure-organizations/enable-connections.mdx +++ b/main/docs/ja-jp/manage-users/organizations/configure-organizations/enable-connections.mdx @@ -9,6 +9,9 @@ permalink: "enable-connections" 'twitter:description': "Auth0 DashboardとManagement APIを使用して組織の接続を有効にする方法を説明します。" --- + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + [組織](/docs/ja-jp/manage-users/organizations/organizations-overview)のそれぞれに特定の接続を有効化すると、ユーザーに異なるログインオプションを提供できるようになります。有効にした接続は組織のログインプロンプトに追加され、ユーザーがその接続を使ってアプリケーションにアクセスできるようになります。 組織に接続を有効にするには、テナントにその接続がなくては**なりません** 。サポートされている接続には[データベース接続](/docs/ja-jp/connections/database)、[ソーシャル接続](/docs/ja-jp/connections/identity-providers-social)や[エンタープライズ接続](/docs/ja-jp/connections/identity-providers-enterprise)が含まれます。 @@ -73,7 +76,7 @@ Management APIを使って接続を有効にするには以下を行います。 * **データベース接続のみ** :サインアップの設定に合わせて、`{isSignupEnabled}`を`true`または`false`に置き換えます。 * **エンタープライズ接続のみ** :接続ボタンの設定に合わせて、`{showAsButtonOption}`を`true`または`false`に置き換えます。 - + ```bash cURL lines curl --request POST \ @@ -290,7 +293,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + diff --git a/main/docs/ja-jp/manage-users/organizations/configure-organizations/remove-member-roles.mdx b/main/docs/ja-jp/manage-users/organizations/configure-organizations/remove-member-roles.mdx index 7552cba30..18718ee86 100644 --- a/main/docs/ja-jp/manage-users/organizations/configure-organizations/remove-member-roles.mdx +++ b/main/docs/ja-jp/manage-users/organizations/configure-organizations/remove-member-roles.mdx @@ -10,6 +10,7 @@ permalink: "remove-member-roles" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Auth0 DashboardまたはManagement APIを使用すると、[組織](/docs/ja-jp/manage-users/organizations/organizations-overview)メンバーからロールを削除することができます。 @@ -26,18 +27,24 @@ Auth0 Dashboardを使って組織メンバーからロールを削除するに Management APIを使って組織メンバーからロールを削除するには、次を行います: `DELETE`呼び出しを`Delete Organization Member Roles`(組織メンバーロール削除)エンドポイントに対して行います。`ORG_ID`、`MGMT_API_ACCESS_TOKEN`、`USER_ID`、`ROLE_ID`のプレースホルダーをそれぞれ組織ID、管理APIアクセストークン、ユーザID、ロールIDで置き換えます。 -export const codeExample1 = `curl --request DELETE \ + +```bash cURL +curl --request DELETE \ --url 'https://{yourDomain}/api/v2/organizations/ORG_ID/members/USER_ID/roles' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'cache-control: no-cache' \ - --data '{ "roles": [ "ROLE_ID", "ROLE_ID", "ROLE_ID" ] }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/organizations/ORG_ID/members/USER_ID/roles"); + --data '{ "roles": [ "ROLE_ID", "ROLE_ID", "ROLE_ID" ] }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/organizations/ORG_ID/members/USER_ID/roles"); var request = new RestRequest(Method.DELETE); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("undefined", "{ \"roles\": [ \"ROLE_ID\", \"ROLE_ID\", \"ROLE_ID\" ] }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("undefined", "{ "roles": [ "ROLE_ID", "ROLE_ID", "ROLE_ID" ] }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -50,7 +57,7 @@ func main() { url := "https://{yourDomain}/api/v2/organizations/ORG_ID/members/USER_ID/roles" - payload := strings.NewReader("{ \"roles\": [ \"ROLE_ID\", \"ROLE_ID\", \"ROLE_ID\" ] }") + payload := strings.NewReader("{ "roles": [ "ROLE_ID", "ROLE_ID", "ROLE_ID" ] }") req, _ := http.NewRequest("DELETE", url, payload) @@ -65,13 +72,17 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.delete("https://{yourDomain}/api/v2/organizations/ORG_ID/members/USER_ID/roles") +} +``` +```java Java +HttpResponse response = Unirest.delete("https://{yourDomain}/api/v2/organizations/ORG_ID/members/USER_ID/roles") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ \"roles\": [ \"ROLE_ID\", \"ROLE_ID\", \"ROLE_ID\" ] }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "roles": [ "ROLE_ID", "ROLE_ID", "ROLE_ID" ] }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'DELETE', @@ -84,8 +95,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @"cache-control": @"no-cache" }; @@ -110,8 +123,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/organizations/ORG_ID/members/USER_ID/roles", @@ -121,7 +136,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "DELETE", - CURLOPT_POSTFIELDS => "{ \"roles\": [ \"ROLE_ID\", \"ROLE_ID\", \"ROLE_ID\" ] }", + CURLOPT_POSTFIELDS => "{ "roles": [ "ROLE_ID", "ROLE_ID", "ROLE_ID" ] }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "cache-control: no-cache" @@ -137,12 +152,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"roles\": [ \"ROLE_ID\", \"ROLE_ID\", \"ROLE_ID\" ] }" +payload = "{ "roles": [ "ROLE_ID", "ROLE_ID", "ROLE_ID" ] }" headers = { 'authorization': "Bearer MGMT_API_ACCESS_TOKEN", @@ -154,8 +171,10 @@ conn.request("DELETE", "/{yourDomain}/api/v2/organizations/ORG_ID/members/USER_I res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -168,11 +187,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Delete.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ \"roles\": [ \"ROLE_ID\", \"ROLE_ID\", \"ROLE_ID\" ] }" +request.body = "{ "roles": [ "ROLE_ID", "ROLE_ID", "ROLE_ID" ] }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "authorization": "Bearer MGMT_API_ACCESS_TOKEN", @@ -199,20 +220,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + diff --git a/main/docs/ja-jp/manage-users/organizations/configure-organizations/remove-members.mdx b/main/docs/ja-jp/manage-users/organizations/configure-organizations/remove-members.mdx index 321d84656..c0b87b227 100644 --- a/main/docs/ja-jp/manage-users/organizations/configure-organizations/remove-members.mdx +++ b/main/docs/ja-jp/manage-users/organizations/configure-organizations/remove-members.mdx @@ -10,6 +10,7 @@ permalink: "remove-members" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Auth0 DashboardまたはManagement APIを使用して、組織からメンバーを削除できます。[組織](/docs/ja-jp/manage-users/organizations/organizations-overview)からユーザーを削除すると、そのユーザーの特定の組織でのメンバーシップのみが削除されます。接続またはAuth0テナントからユーザーが削除されることはありません。削除プロセスには約5~10秒かかります。 @@ -26,18 +27,24 @@ Auth0 Dashboardからメンバーを削除するには以下を行います。 Management API経由でメンバーを削除するには以下を行います。 `Delete Organization Members`エンドポイントに対して`DELETE`呼び出しを実行します。必ず、`ORG_ID`、`MGMT_API_ACCESS_TOKEN`、および`USER_ID`のプレースホルダーの値を、それぞれ組織ID、Management APIのアクセストークン、ユーザーIDに置き換えます。 -export const codeExample1 = `curl --request DELETE \ + +```bash cURL +curl --request DELETE \ --url 'https://{yourDomain}/api/v2/organizations/ORG_ID/members' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'cache-control: no-cache' \ - --data '{ "members": [ "USER_ID", "USER_ID", "USER_ID" ] }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/organizations/ORG_ID/members"); + --data '{ "members": [ "USER_ID", "USER_ID", "USER_ID" ] }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/organizations/ORG_ID/members"); var request = new RestRequest(Method.DELETE); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("undefined", "{ \"members\": [ \"USER_ID\", \"USER_ID\", \"USER_ID\" ] }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("undefined", "{ "members": [ "USER_ID", "USER_ID", "USER_ID" ] }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -50,7 +57,7 @@ func main() { url := "https://{yourDomain}/api/v2/organizations/ORG_ID/members" - payload := strings.NewReader("{ \"members\": [ \"USER_ID\", \"USER_ID\", \"USER_ID\" ] }") + payload := strings.NewReader("{ "members": [ "USER_ID", "USER_ID", "USER_ID" ] }") req, _ := http.NewRequest("DELETE", url, payload) @@ -65,13 +72,17 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.delete("https://{yourDomain}/api/v2/organizations/ORG_ID/members") +} +``` +```java Java +HttpResponse response = Unirest.delete("https://{yourDomain}/api/v2/organizations/ORG_ID/members") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ \"members\": [ \"USER_ID\", \"USER_ID\", \"USER_ID\" ] }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "members": [ "USER_ID", "USER_ID", "USER_ID" ] }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'DELETE', @@ -84,8 +95,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @"cache-control": @"no-cache" }; @@ -110,8 +123,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/organizations/ORG_ID/members", @@ -121,7 +136,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "DELETE", - CURLOPT_POSTFIELDS => "{ \"members\": [ \"USER_ID\", \"USER_ID\", \"USER_ID\" ] }", + CURLOPT_POSTFIELDS => "{ "members": [ "USER_ID", "USER_ID", "USER_ID" ] }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "cache-control: no-cache" @@ -137,12 +152,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"members\": [ \"USER_ID\", \"USER_ID\", \"USER_ID\" ] }" +payload = "{ "members": [ "USER_ID", "USER_ID", "USER_ID" ] }" headers = { 'authorization': "Bearer MGMT_API_ACCESS_TOKEN", @@ -154,8 +171,10 @@ conn.request("DELETE", "/{yourDomain}/api/v2/organizations/ORG_ID/members", payl res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -168,11 +187,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Delete.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ \"members\": [ \"USER_ID\", \"USER_ID\", \"USER_ID\" ] }" +request.body = "{ "members": [ "USER_ID", "USER_ID", "USER_ID" ] }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "authorization": "Bearer MGMT_API_ACCESS_TOKEN", @@ -199,20 +220,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + diff --git a/main/docs/ja-jp/manage-users/organizations/configure-organizations/retrieve-connections.mdx b/main/docs/ja-jp/manage-users/organizations/configure-organizations/retrieve-connections.mdx index c8e08f0a3..f62357bc3 100644 --- a/main/docs/ja-jp/manage-users/organizations/configure-organizations/retrieve-connections.mdx +++ b/main/docs/ja-jp/manage-users/organizations/configure-organizations/retrieve-connections.mdx @@ -10,6 +10,7 @@ permalink: "retrieve-connections" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; プログラムで[組織](/docs/ja-jp/manage-users/organizations/organizations-overview)を操作するには、組織に対して有効になっている接続のリストを取得する必要がある場合があります。 @@ -24,14 +25,20 @@ import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; `Get Organization Connections`エンドポイントに`GET`呼び出しを行います。`ORG_ID`と`MGMT_API_ACCESS_TOKEN`のプレースホルダーの値を、それぞれ組織IDとManagement APIのアクセストークンに置き換えてください。 -export const codeExample1 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/organizations/ORG_ID/enabled_connections' \ - --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/organizations/ORG_ID/enabled_connections"); + --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/organizations/ORG_ID/enabled_connections"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -55,11 +62,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/organizations/ORG_ID/enabled_connections") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/organizations/ORG_ID/enabled_connections") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -71,8 +82,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN" }; @@ -92,8 +105,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/organizations/ORG_ID/enabled_connections", @@ -117,8 +132,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -129,8 +146,10 @@ conn.request("GET", "/{yourDomain}/api/v2/organizations/ORG_ID/enabled_connectio res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -144,8 +163,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer MGMT_API_ACCESS_TOKEN"] @@ -165,20 +186,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + diff --git a/main/docs/ja-jp/manage-users/organizations/configure-organizations/retrieve-member-roles.mdx b/main/docs/ja-jp/manage-users/organizations/configure-organizations/retrieve-member-roles.mdx index 020a244bd..9da6b6632 100644 --- a/main/docs/ja-jp/manage-users/organizations/configure-organizations/retrieve-member-roles.mdx +++ b/main/docs/ja-jp/manage-users/organizations/configure-organizations/retrieve-member-roles.mdx @@ -10,6 +10,7 @@ permalink: "retrieve-member-roles" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; プログラムで[組織](/docs/ja-jp/manage-users/organizations/organizations-overview)を操作するには、組織のメンバーに割り当てられたロールのリストを取得する必要がある場合があります。 @@ -24,14 +25,20 @@ import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; `Get Organization Member Roles`エンドポイントに対して`GET`呼び出しを行います。必ず、`ORG_ID`、`USER_ID`、および`MGMT_API_ACCESS_TOKEN`のプレースホルダーの値を、それぞれご自身の組織ID、メンバーのユーザーID、Management APIのアクセストークンに置き換えてください。 -export const codeExample1 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/organizations/ORG_ID/members/USER_ID/roles' \ - --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/organizations/ORG_ID/members/USER_ID/roles"); + --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/organizations/ORG_ID/members/USER_ID/roles"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -55,11 +62,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/organizations/ORG_ID/members/USER_ID/roles") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/organizations/ORG_ID/members/USER_ID/roles") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -71,8 +82,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN" }; @@ -92,8 +105,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/organizations/ORG_ID/members/USER_ID/roles", @@ -117,8 +132,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -129,8 +146,10 @@ conn.request("GET", "/{yourDomain}/api/v2/organizations/ORG_ID/members/USER_ID/r res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -144,8 +163,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer MGMT_API_ACCESS_TOKEN"] @@ -165,20 +186,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + diff --git a/main/docs/ja-jp/manage-users/organizations/configure-organizations/retrieve-members.mdx b/main/docs/ja-jp/manage-users/organizations/configure-organizations/retrieve-members.mdx index 8c1501036..84671541b 100644 --- a/main/docs/ja-jp/manage-users/organizations/configure-organizations/retrieve-members.mdx +++ b/main/docs/ja-jp/manage-users/organizations/configure-organizations/retrieve-members.mdx @@ -10,6 +10,7 @@ permalink: "retrieve-members" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; プログラムで[組織](/docs/ja-jp/manage-users/organizations/organizations-overview)を操作するには、組織メンバーのリストを取得する必要がある場合があります。 @@ -30,14 +31,20 @@ Auth0 DashboardまたはManagement APIを使用して表示できる組織メン `Get Organization Members`エンドポイントに`GET`呼び出しを行います。`ORG_ID`と`MGMT_API_ACCESS_TOKEN`のプレースホルダーの値を、それぞれ組織IDとManagement APIのアクセストークンに置き換えてください。 -export const codeExample1 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/organizations/ORG_ID/members' \ - --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/organizations/ORG_ID/members"); + --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/organizations/ORG_ID/members"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -61,11 +68,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/organizations/ORG_ID/members") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/organizations/ORG_ID/members") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -77,8 +88,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN" }; @@ -98,8 +111,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/organizations/ORG_ID/members", @@ -123,8 +138,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -135,8 +152,10 @@ conn.request("GET", "/{yourDomain}/api/v2/organizations/ORG_ID/members", headers res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -150,8 +169,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer MGMT_API_ACCESS_TOKEN"] @@ -171,20 +192,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + diff --git a/main/docs/ja-jp/manage-users/organizations/configure-organizations/retrieve-organizations.mdx b/main/docs/ja-jp/manage-users/organizations/configure-organizations/retrieve-organizations.mdx index cf9e77fb2..35db153bc 100644 --- a/main/docs/ja-jp/manage-users/organizations/configure-organizations/retrieve-organizations.mdx +++ b/main/docs/ja-jp/manage-users/organizations/configure-organizations/retrieve-organizations.mdx @@ -10,6 +10,7 @@ permalink: "retrieve-organizations" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; プログラムで[組織](/docs/ja-jp/manage-users/organizations/organizations-overview)を操作する場合は、すべての組織のリストを取得するか、名前またはIDで組織を個別に取得する必要がある場合があります。 @@ -31,14 +32,20 @@ Management APIには、機密のクライアントを使ってアクセスする `Get Organizations`エンドポイントに対して`GET`呼び出しを行います。`MGMT_API_ACCESS_TOKEN`プレースホルダーの値をManagement APIのアクセストークンで置き換えてください。 -export const codeExample1 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/organizations' \ - --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/organizations"); + --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/organizations"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -62,11 +69,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/organizations") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/organizations") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -78,8 +89,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN" }; @@ -99,8 +112,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/organizations", @@ -124,8 +139,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -136,8 +153,10 @@ conn.request("GET", "/{yourDomain}/api/v2/organizations", headers=headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -151,8 +170,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer MGMT_API_ACCESS_TOKEN"] @@ -172,20 +193,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + @@ -281,14 +291,20 @@ Management APIを介してIDで組織を取得できます。 `Get Organization`エンドポイントに対して`GET`呼び出しを行います。`ORG_ID`と`MGMT_API_ACCESS_TOKEN`のプレースホルダーの値を、それぞれ組織IDとManagement APIのアクセストークンに置き換えてください。 -export const codeExample11 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/organizations/ORG_ID' \ - --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN'`; -export const codeExample12 = `var client = new RestClient("https://{yourDomain}/api/v2/organizations/ORG_ID"); + --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/organizations/ORG_ID"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); -IRestResponse response = client.Execute(request);`; -export const codeExample13 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -312,11 +328,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample14 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/organizations/ORG_ID") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/organizations/ORG_ID") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") - .asString();`; -export const codeExample15 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -328,8 +348,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample16 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN" }; @@ -349,8 +371,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/organizations/ORG_ID", @@ -374,8 +398,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -386,8 +412,10 @@ conn.request("GET", "/{yourDomain}/api/v2/organizations/ORG_ID", headers=headers res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -401,8 +429,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer MGMT_API_ACCESS_TOKEN"] @@ -422,20 +452,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + @@ -529,14 +548,20 @@ Management APIを介して組織を名前で取得できます。 `Get Organization by Name`エンドポイントへの`GET`呼び出しを行います。`ORG_NAME`と`MGMT_API_ACCESS_TOKEN`のプレースホルダーの値を、それぞれ組織IDとManagement APIのアクセストークンに置き換えてください。 -export const codeExample21 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/organizations/name/ORG_NAME' \ - --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN'`; -export const codeExample22 = `var client = new RestClient("https://{yourDomain}/api/v2/organizations/name/ORG_NAME"); + --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/organizations/name/ORG_NAME"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); -IRestResponse response = client.Execute(request);`; -export const codeExample23 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -560,11 +585,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample24 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/organizations/name/ORG_NAME") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/organizations/name/ORG_NAME") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") - .asString();`; -export const codeExample25 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -576,8 +605,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample26 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN" }; @@ -597,8 +628,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample27 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/organizations/name/ORG_NAME", @@ -622,8 +655,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample28 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -634,8 +669,10 @@ conn.request("GET", "/{yourDomain}/api/v2/organizations/name/ORG_NAME", headers= res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample29 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -649,8 +686,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' response = http.request(request) -puts response.read_body`; -export const codeExample30 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer MGMT_API_ACCESS_TOKEN"] @@ -670,20 +709,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + diff --git a/main/docs/ja-jp/manage-users/organizations/configure-organizations/retrieve-user-membership.mdx b/main/docs/ja-jp/manage-users/organizations/configure-organizations/retrieve-user-membership.mdx index 3a5d8fbe2..b0f094879 100644 --- a/main/docs/ja-jp/manage-users/organizations/configure-organizations/retrieve-user-membership.mdx +++ b/main/docs/ja-jp/manage-users/organizations/configure-organizations/retrieve-user-membership.mdx @@ -10,6 +10,7 @@ permalink: "retrieve-user-membership" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; [組織](/docs/ja-jp/manage-users/organizations/organizations-overview)をプログラム的に操作する際、ユーザーがメンバーシップを割り当てられている組織のリストを取得する必要があります。 @@ -23,14 +24,20 @@ Auth0 DashboardまたはManagement APIを使用して表示できる組織メン `Get User Organizations`エンドポイントに対して`GET`呼び出しを行います。`USER_ID`と`MGMT_API_ACCESS_TOKEN`のプレースホルダーの値を、それぞれユーザーIDとManagement APIのアクセストークンに置き換えてください。 -export const codeExample1 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/users/USER_ID/organizations' \ - --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/users/USER_ID/organizations"); + --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users/USER_ID/organizations"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -54,11 +61,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/users/USER_ID/organizations") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/users/USER_ID/organizations") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -70,8 +81,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN" }; @@ -91,8 +104,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users/USER_ID/organizations", @@ -116,8 +131,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -128,8 +145,10 @@ conn.request("GET", "/{yourDomain}/api/v2/users/USER_ID/organizations", headers= res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -143,8 +162,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer MGMT_API_ACCESS_TOKEN"] @@ -164,20 +185,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + diff --git a/main/docs/ja-jp/manage-users/sessions/configure-session-lifetime-settings.mdx b/main/docs/ja-jp/manage-users/sessions/configure-session-lifetime-settings.mdx index e14557b02..765b7a514 100644 --- a/main/docs/ja-jp/manage-users/sessions/configure-session-lifetime-settings.mdx +++ b/main/docs/ja-jp/manage-users/sessions/configure-session-lifetime-settings.mdx @@ -10,6 +10,7 @@ permalink: "configure-session-lifetime-settings" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; セッションの**絶対有効期限** は、セッションが作られたときに定義されます。絶対有効期限を変更するには、Auth0 DashboardまたはManagement APIを使ってセッション設定を構成し直します。 @@ -38,26 +39,30 @@ import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; ![Dashboard テナント設定 詳細設定 ログインセッション管理](/docs/images/ja-jp/cdy7uua7fh8z/q2fGPzoUqCcXj7OxcHhjy/ed80efb619cbc1b963dc3dcc1f3365b0/Tenant_Settings_-_Session_Expiration.png) - - ## Management API `PATCH`呼び出しを[テナント設定エンドポイント](https://auth0.com/docs/api/management/v2#!/tenants/patch_settings)に対して行います。`MGMT_API_ACCESS_TOKEN`、`SESSION_LIFETIME`、`IDLE_SESSION_LIFETIME`のプレースホルダーをそれぞれ使用しているManagement APIのアクセストークン、セッションライフタイム値、アイドルセッションライフタイム値で置き換えます。 -export const codeExample1 = `curl --request PATCH \ + +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/tenants/settings' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{ "session_lifetime": SESSION_LIFETIME_VALUE, "idle_session_lifetime": IDLE_SESSION_LIFETIME_VALUE }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/tenants/settings"); + --data '{ "session_lifetime": SESSION_LIFETIME_VALUE, "idle_session_lifetime": IDLE_SESSION_LIFETIME_VALUE }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/tenants/settings"); var request = new RestRequest(Method.PATCH); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{ \"session_lifetime\": SESSION_LIFETIME_VALUE, \"idle_session_lifetime\": IDLE_SESSION_LIFETIME_VALUE }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "session_lifetime": SESSION_LIFETIME_VALUE, "idle_session_lifetime": IDLE_SESSION_LIFETIME_VALUE }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -70,7 +75,7 @@ func main() { url := "https://{yourDomain}/api/v2/tenants/settings" - payload := strings.NewReader("{ \"session_lifetime\": SESSION_LIFETIME_VALUE, \"idle_session_lifetime\": IDLE_SESSION_LIFETIME_VALUE }") + payload := strings.NewReader("{ "session_lifetime": SESSION_LIFETIME_VALUE, "idle_session_lifetime": IDLE_SESSION_LIFETIME_VALUE }") req, _ := http.NewRequest("PATCH", url, payload) @@ -86,14 +91,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/tenants/settings") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/tenants/settings") .header("content-type", "application/json") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ \"session_lifetime\": SESSION_LIFETIME_VALUE, \"idle_session_lifetime\": IDLE_SESSION_LIFETIME_VALUE }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "session_lifetime": SESSION_LIFETIME_VALUE, "idle_session_lifetime": IDLE_SESSION_LIFETIME_VALUE }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -110,8 +119,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @@ -136,8 +147,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/tenants/settings", @@ -147,7 +160,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{ \"session_lifetime\": SESSION_LIFETIME_VALUE, \"idle_session_lifetime\": IDLE_SESSION_LIFETIME_VALUE }", + CURLOPT_POSTFIELDS => "{ "session_lifetime": SESSION_LIFETIME_VALUE, "idle_session_lifetime": IDLE_SESSION_LIFETIME_VALUE }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "cache-control: no-cache", @@ -164,12 +177,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"session_lifetime\": SESSION_LIFETIME_VALUE, \"idle_session_lifetime\": IDLE_SESSION_LIFETIME_VALUE }" +payload = "{ "session_lifetime": SESSION_LIFETIME_VALUE, "idle_session_lifetime": IDLE_SESSION_LIFETIME_VALUE }" headers = { 'content-type': "application/json", @@ -182,8 +197,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/tenants/settings", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -197,11 +214,13 @@ request = Net::HTTP::Patch.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ \"session_lifetime\": SESSION_LIFETIME_VALUE, \"idle_session_lifetime\": IDLE_SESSION_LIFETIME_VALUE }" +request.body = "{ "session_lifetime": SESSION_LIFETIME_VALUE, "idle_session_lifetime": IDLE_SESSION_LIFETIME_VALUE }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -228,20 +247,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
    diff --git a/main/docs/ja-jp/manage-users/user-accounts/change-user-picture.mdx b/main/docs/ja-jp/manage-users/user-accounts/change-user-picture.mdx index 35f014687..419c6c586 100644 --- a/main/docs/ja-jp/manage-users/user-accounts/change-user-picture.mdx +++ b/main/docs/ja-jp/manage-users/user-accounts/change-user-picture.mdx @@ -10,6 +10,7 @@ permalink: "change-user-picture" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Auth0は、ユーザープロファイル内の共通プロファイルプロパティを正規化します。これには、`name`や`picture`フィールドなどが含まれます。画像フィールドには、ソーシャルプロバイダーのプロフィール画像、またはユーザーのメールアドレスに関連付けられたGravatar画像のいずれかが入力されます。 @@ -21,18 +22,24 @@ Auth0は、ユーザープロファイル内の共通プロファイルプロパ または、メタデータを使用してユーザーの画像属性を保管することもできます。たとえば、アプリにプロフィール画像をアップロードする方法がある場合は、画像をアップロードすれば、`user.user_metadata.picture`でURLを画像に設定できます。 -export const codeExample1 = `curl --request PATCH \ + +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/users/USER_ID' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'content-type: application/json' \ - --data '{"user_metadata": {"picture": "https://example.com/some-image.png"}}'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/users/USER_ID"); + --data '{"user_metadata": {"picture": "https://example.com/some-image.png"}}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users/USER_ID"); var request = new RestRequest(Method.PATCH); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\"user_metadata\": {\"picture\": \"https://example.com/some-image.png\"}}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{"user_metadata": {"picture": "https://example.com/some-image.png"}}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -45,7 +52,7 @@ func main() { url := "https://{yourDomain}/api/v2/users/USER_ID" - payload := strings.NewReader("{\"user_metadata\": {\"picture\": \"https://example.com/some-image.png\"}}") + payload := strings.NewReader("{"user_metadata": {"picture": "https://example.com/some-image.png"}}") req, _ := http.NewRequest("PATCH", url, payload) @@ -60,13 +67,17 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/users/USER_ID") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/users/USER_ID") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("content-type", "application/json") - .body("{\"user_metadata\": {\"picture\": \"https://example.com/some-image.png\"}}") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{"user_metadata": {"picture": "https://example.com/some-image.png"}}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -82,8 +93,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @"content-type": @"application/json" }; @@ -108,8 +121,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users/USER_ID", @@ -119,7 +134,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{\"user_metadata\": {\"picture\": \"https://example.com/some-image.png\"}}", + CURLOPT_POSTFIELDS => "{"user_metadata": {"picture": "https://example.com/some-image.png"}}", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "content-type: application/json" @@ -135,12 +150,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"user_metadata\": {\"picture\": \"https://example.com/some-image.png\"}}" +payload = "{"user_metadata": {"picture": "https://example.com/some-image.png"}}" headers = { 'authorization': "Bearer MGMT_API_ACCESS_TOKEN", @@ -152,8 +169,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/users/USER_ID", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -166,11 +185,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Patch.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["content-type"] = 'application/json' -request.body = "{\"user_metadata\": {\"picture\": \"https://example.com/some-image.png\"}}" +request.body = "{"user_metadata": {"picture": "https://example.com/some-image.png"}}" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "authorization": "Bearer MGMT_API_ACCESS_TOKEN", @@ -197,20 +218,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ## アクションを使用する diff --git a/main/docs/ja-jp/manage-users/user-accounts/metadata/manage-metadata-api.mdx b/main/docs/ja-jp/manage-users/user-accounts/metadata/manage-metadata-api.mdx index 1f6633a43..d20973636 100644 --- a/main/docs/ja-jp/manage-users/user-accounts/metadata/manage-metadata-api.mdx +++ b/main/docs/ja-jp/manage-users/user-accounts/metadata/manage-metadata-api.mdx @@ -10,6 +10,7 @@ permalink: "manage-metadata-api" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; ## ユーザーメタデータ @@ -31,18 +32,24 @@ import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; Management API [`/post_users`](/docs/ja-jp/api/management/v2#!/Users/post_users)エンドポイントに対して次の`POST`呼び出しを実行し、ユーザーの作成とプロパティ値の設定を行います。 -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/api/v2/users' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'content-type: application/json' \ - --data '{"email": "jane.doe@example.com", "user_metadata": {"hobby": "surfing"}, "app_metadata": {"plan": "full"}}'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/users"); + --data '{"email": "jane.doe@example.com", "user_metadata": {"hobby": "surfing"}, "app_metadata": {"plan": "full"}}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users"); var request = new RestRequest(Method.POST); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\"email\": \"jane.doe@example.com\", \"user_metadata\": {\"hobby\": \"surfing\"}, \"app_metadata\": {\"plan\": \"full\"}}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{"email": "jane.doe@example.com", "user_metadata": {"hobby": "surfing"}, "app_metadata": {"plan": "full"}}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -55,7 +62,7 @@ func main() { url := "https://{yourDomain}/api/v2/users" - payload := strings.NewReader("{\"email\": \"jane.doe@example.com\", \"user_metadata\": {\"hobby\": \"surfing\"}, \"app_metadata\": {\"plan\": \"full\"}}") + payload := strings.NewReader("{"email": "jane.doe@example.com", "user_metadata": {"hobby": "surfing"}, "app_metadata": {"plan": "full"}}") req, _ := http.NewRequest("POST", url, payload) @@ -70,13 +77,17 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/users") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/users") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("content-type", "application/json") - .body("{\"email\": \"jane.doe@example.com\", \"user_metadata\": {\"hobby\": \"surfing\"}, \"app_metadata\": {\"plan\": \"full\"}}") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{"email": "jane.doe@example.com", "user_metadata": {"hobby": "surfing"}, "app_metadata": {"plan": "full"}}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -96,8 +107,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @"content-type": @"application/json" }; @@ -124,8 +137,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users", @@ -135,7 +150,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{\"email\": \"jane.doe@example.com\", \"user_metadata\": {\"hobby\": \"surfing\"}, \"app_metadata\": {\"plan\": \"full\"}}", + CURLOPT_POSTFIELDS => "{"email": "jane.doe@example.com", "user_metadata": {"hobby": "surfing"}, "app_metadata": {"plan": "full"}}", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "content-type: application/json" @@ -151,12 +166,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"email\": \"jane.doe@example.com\", \"user_metadata\": {\"hobby\": \"surfing\"}, \"app_metadata\": {\"plan\": \"full\"}}" +payload = "{"email": "jane.doe@example.com", "user_metadata": {"hobby": "surfing"}, "app_metadata": {"plan": "full"}}" headers = { 'authorization': "Bearer MGMT_API_ACCESS_TOKEN", @@ -168,8 +185,10 @@ conn.request("POST", "/{yourDomain}/api/v2/users", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -182,11 +201,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["content-type"] = 'application/json' -request.body = "{\"email\": \"jane.doe@example.com\", \"user_metadata\": {\"hobby\": \"surfing\"}, \"app_metadata\": {\"plan\": \"full\"}}" +request.body = "{"email": "jane.doe@example.com", "user_metadata": {"hobby": "surfing"}, "app_metadata": {"plan": "full"}}" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "authorization": "Bearer MGMT_API_ACCESS_TOKEN", @@ -217,20 +238,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ### ユーザーメタデータを更新する @@ -262,18 +272,24 @@ Management API [`/patch_users_by_id`](/docs/ja-jp/api/management/v2#!/Users/patc 次の`PATCH`呼び出しを実行します。 -export const codeExample11 = `curl --request PATCH \ + +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/users/user_id' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'content-type: application/json' \ - --data '{"user_metadata": {"addresses": {"home": "123 Main Street, Anytown, ST 12345"}}}'`; -export const codeExample12 = `var client = new RestClient("https://{yourDomain}/api/v2/users/user_id"); + --data '{"user_metadata": {"addresses": {"home": "123 Main Street, Anytown, ST 12345"}}}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users/user_id"); var request = new RestRequest(Method.PATCH); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\"user_metadata\": {\"addresses\": {\"home\": \"123 Main Street, Anytown, ST 12345\"}}}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample13 = `package main +request.AddParameter("application/json", "{"user_metadata": {"addresses": {"home": "123 Main Street, Anytown, ST 12345"}}}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -286,7 +302,7 @@ func main() { url := "https://{yourDomain}/api/v2/users/user_id" - payload := strings.NewReader("{\"user_metadata\": {\"addresses\": {\"home\": \"123 Main Street, Anytown, ST 12345\"}}}") + payload := strings.NewReader("{"user_metadata": {"addresses": {"home": "123 Main Street, Anytown, ST 12345"}}}") req, _ := http.NewRequest("PATCH", url, payload) @@ -301,13 +317,17 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample14 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/users/user_id") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/users/user_id") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("content-type", "application/json") - .body("{\"user_metadata\": {\"addresses\": {\"home\": \"123 Main Street, Anytown, ST 12345\"}}}") - .asString();`; -export const codeExample15 = `var axios = require("axios").default; + .body("{"user_metadata": {"addresses": {"home": "123 Main Street, Anytown, ST 12345"}}}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -323,8 +343,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample16 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @"content-type": @"application/json" }; @@ -349,8 +371,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users/user_id", @@ -360,7 +384,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{\"user_metadata\": {\"addresses\": {\"home\": \"123 Main Street, Anytown, ST 12345\"}}}", + CURLOPT_POSTFIELDS => "{"user_metadata": {"addresses": {"home": "123 Main Street, Anytown, ST 12345"}}}", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "content-type: application/json" @@ -376,12 +400,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"user_metadata\": {\"addresses\": {\"home\": \"123 Main Street, Anytown, ST 12345\"}}}" +payload = "{"user_metadata": {"addresses": {"home": "123 Main Street, Anytown, ST 12345"}}}" headers = { 'authorization': "Bearer MGMT_API_ACCESS_TOKEN", @@ -393,8 +419,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/users/user_id", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -407,11 +435,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Patch.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["content-type"] = 'application/json' -request.body = "{\"user_metadata\": {\"addresses\": {\"home\": \"123 Main Street, Anytown, ST 12345\"}}}" +request.body = "{"user_metadata": {"addresses": {"home": "123 Main Street, Anytown, ST 12345"}}}" response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "authorization": "Bearer MGMT_API_ACCESS_TOKEN", @@ -438,20 +468,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ユーザーのプロファイルは以下のように表示されるようになります。 @@ -495,18 +514,24 @@ dataTask.resume()`; したがって、APIに対する`PATCH`呼び出しは、次のようになります。 -export const codeExample21 = `curl --request PATCH \ + +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/users/user_id' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'content-type: application/json' \ - --data '{"user_metadata": {"addresses": {"home": "123 Main Street, Anytown, ST 12345", "work": "100 Industrial Way, Anytown, ST 12345"}}}'`; -export const codeExample22 = `var client = new RestClient("https://{yourDomain}/api/v2/users/user_id"); + --data '{"user_metadata": {"addresses": {"home": "123 Main Street, Anytown, ST 12345", "work": "100 Industrial Way, Anytown, ST 12345"}}}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users/user_id"); var request = new RestRequest(Method.PATCH); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\"user_metadata\": {\"addresses\": {\"home\": \"123 Main Street, Anytown, ST 12345\", \"work\": \"100 Industrial Way, Anytown, ST 12345\"}}}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample23 = `package main +request.AddParameter("application/json", "{"user_metadata": {"addresses": {"home": "123 Main Street, Anytown, ST 12345", "work": "100 Industrial Way, Anytown, ST 12345"}}}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -519,7 +544,7 @@ func main() { url := "https://{yourDomain}/api/v2/users/user_id" - payload := strings.NewReader("{\"user_metadata\": {\"addresses\": {\"home\": \"123 Main Street, Anytown, ST 12345\", \"work\": \"100 Industrial Way, Anytown, ST 12345\"}}}") + payload := strings.NewReader("{"user_metadata": {"addresses": {"home": "123 Main Street, Anytown, ST 12345", "work": "100 Industrial Way, Anytown, ST 12345"}}}") req, _ := http.NewRequest("PATCH", url, payload) @@ -534,13 +559,17 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample24 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/users/user_id") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/users/user_id") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("content-type", "application/json") - .body("{\"user_metadata\": {\"addresses\": {\"home\": \"123 Main Street, Anytown, ST 12345\", \"work\": \"100 Industrial Way, Anytown, ST 12345\"}}}") - .asString();`; -export const codeExample25 = `var axios = require("axios").default; + .body("{"user_metadata": {"addresses": {"home": "123 Main Street, Anytown, ST 12345", "work": "100 Industrial Way, Anytown, ST 12345"}}}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -563,8 +592,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample26 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @"content-type": @"application/json" }; @@ -589,8 +620,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample27 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users/user_id", @@ -600,7 +633,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{\"user_metadata\": {\"addresses\": {\"home\": \"123 Main Street, Anytown, ST 12345\", \"work\": \"100 Industrial Way, Anytown, ST 12345\"}}}", + CURLOPT_POSTFIELDS => "{"user_metadata": {"addresses": {"home": "123 Main Street, Anytown, ST 12345", "work": "100 Industrial Way, Anytown, ST 12345"}}}", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "content-type: application/json" @@ -616,12 +649,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample28 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"user_metadata\": {\"addresses\": {\"home\": \"123 Main Street, Anytown, ST 12345\", \"work\": \"100 Industrial Way, Anytown, ST 12345\"}}}" +payload = "{"user_metadata": {"addresses": {"home": "123 Main Street, Anytown, ST 12345", "work": "100 Industrial Way, Anytown, ST 12345"}}}" headers = { 'authorization': "Bearer MGMT_API_ACCESS_TOKEN", @@ -633,8 +668,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/users/user_id", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample29 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -647,11 +684,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Patch.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["content-type"] = 'application/json' -request.body = "{\"user_metadata\": {\"addresses\": {\"home\": \"123 Main Street, Anytown, ST 12345\", \"work\": \"100 Industrial Way, Anytown, ST 12345\"}}}" +request.body = "{"user_metadata": {"addresses": {"home": "123 Main Street, Anytown, ST 12345", "work": "100 Industrial Way, Anytown, ST 12345"}}}" response = http.request(request) -puts response.read_body`; -export const codeExample30 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "authorization": "Bearer MGMT_API_ACCESS_TOKEN", @@ -681,20 +720,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ### ユーザーメタデータを削除する diff --git a/main/docs/ja-jp/manage-users/user-accounts/user-account-linking.mdx b/main/docs/ja-jp/manage-users/user-accounts/user-account-linking.mdx index 2524b247f..eeb45f81e 100644 --- a/main/docs/ja-jp/manage-users/user-accounts/user-account-linking.mdx +++ b/main/docs/ja-jp/manage-users/user-accounts/user-account-linking.mdx @@ -2,6 +2,9 @@ title: ユーザーアカウントのリンク --- + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + Auth0は、様々なIDプロバイダーのユーザーアカウントのリンクをサポートします。これによりユーザーは、どのアカウントから認証してもアプリによって認識され、同じユーザープロファイルに関連付けられます。 + ```json プライマリアカウントのプロファイル lines { "email": "your0@email.com", @@ -133,7 +136,7 @@ Auth0は、デフォルトではすべてのIDを個別のIDとして扱いま ... } ``` - + 以下にご注意ください: diff --git a/main/docs/ja-jp/manage-users/user-accounts/user-profiles/configure-connection-sync-with-auth0.mdx b/main/docs/ja-jp/manage-users/user-accounts/user-profiles/configure-connection-sync-with-auth0.mdx index 7dd60780c..9cb78df92 100644 --- a/main/docs/ja-jp/manage-users/user-accounts/user-profiles/configure-connection-sync-with-auth0.mdx +++ b/main/docs/ja-jp/manage-users/user-accounts/user-profiles/configure-connection-sync-with-auth0.mdx @@ -10,6 +10,7 @@ permalink: "configure-connection-sync-with-auth0" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; アップストリームIDプロバイダーの接続設定を更新して、ユーザープロファイルのルート属性の更新がいつ許可されるかをAuth0 DashboardManagement APIで制御することができます。 @@ -37,20 +38,26 @@ import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; [接続更新エンドポイント](https://auth0.com/docs/api/management/v2#!/Connections/patch_connections_by_id)に`PATCH`呼び出しを行います。必ず、呼び出しに元のoptions値を含めて、現在の値が上書きされないようにしてください。また、`CONNECTION_ID`、`MGMT_API_ACCESS_TOKEN`、`ATTRIBUTE_UPDATE_VALUE`のプレースホルダーの値をそれぞれ接続ID、Management APIのアクセストークン、属性の更新値に置き換えます。 -export const codeExample1 = `curl --request PATCH \ + +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/connections/CONNECTION_ID' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{"options":{"set_user_root_attributes": "ATTRIBUTE_UPDATE_VALUE"}}'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/connections/CONNECTION_ID"); + --data '{"options":{"set_user_root_attributes": "ATTRIBUTE_UPDATE_VALUE"}}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/connections/CONNECTION_ID"); var request = new RestRequest(Method.PATCH); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{\"options\":{\"set_user_root_attributes\": \"ATTRIBUTE_UPDATE_VALUE\"}}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{"options":{"set_user_root_attributes": "ATTRIBUTE_UPDATE_VALUE"}}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -63,7 +70,7 @@ func main() { url := "https://{yourDomain}/api/v2/connections/CONNECTION_ID" - payload := strings.NewReader("{\"options\":{\"set_user_root_attributes\": \"ATTRIBUTE_UPDATE_VALUE\"}}") + payload := strings.NewReader("{"options":{"set_user_root_attributes": "ATTRIBUTE_UPDATE_VALUE"}}") req, _ := http.NewRequest("PATCH", url, payload) @@ -79,14 +86,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/connections/CONNECTION_ID") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/connections/CONNECTION_ID") .header("content-type", "application/json") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{\"options\":{\"set_user_root_attributes\": \"ATTRIBUTE_UPDATE_VALUE\"}}") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{"options":{"set_user_root_attributes": "ATTRIBUTE_UPDATE_VALUE"}}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -103,8 +114,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @@ -130,8 +143,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/connections/CONNECTION_ID", @@ -141,7 +156,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{\"options\":{\"set_user_root_attributes\": \"ATTRIBUTE_UPDATE_VALUE\"}}", + CURLOPT_POSTFIELDS => "{"options":{"set_user_root_attributes": "ATTRIBUTE_UPDATE_VALUE"}}", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "cache-control: no-cache", @@ -158,12 +173,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"options\":{\"set_user_root_attributes\": \"ATTRIBUTE_UPDATE_VALUE\"}}" +payload = "{"options":{"set_user_root_attributes": "ATTRIBUTE_UPDATE_VALUE"}}" headers = { 'content-type': "application/json", @@ -176,8 +193,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/connections/CONNECTION_ID", payload, res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -191,11 +210,13 @@ request = Net::HTTP::Patch.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{\"options\":{\"set_user_root_attributes\": \"ATTRIBUTE_UPDATE_VALUE\"}}" +request.body = "{"options":{"set_user_root_attributes": "ATTRIBUTE_UPDATE_VALUE"}}" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -223,20 +244,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
    diff --git a/main/docs/ja-jp/manage-users/user-accounts/user-profiles/root-attributes/set-root-attributes-during-user-import.mdx b/main/docs/ja-jp/manage-users/user-accounts/user-profiles/root-attributes/set-root-attributes-during-user-import.mdx index 8db53cbf9..6ad251eab 100644 --- a/main/docs/ja-jp/manage-users/user-accounts/user-profiles/root-attributes/set-root-attributes-during-user-import.mdx +++ b/main/docs/ja-jp/manage-users/user-accounts/user-profiles/root-attributes/set-root-attributes-during-user-import.mdx @@ -10,23 +10,30 @@ permalink: "set-root-attributes-during-user-import" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; このガイドでは、Auth0のManagement APIを使用して、インポート中にユーザーのルート属性を設定する方法について説明します。これにより、ユーザーをインポートする際に、ルート属性の設定に必要なAPI呼び出しの数を最小限に抑えることができます。インポート可能な属性については、「[正規化ユーザープロファイルの構造](/docs/ja-jp/manage-users/user-accounts/user-profiles/user-profile-structure)」を参照してください。 `POST`呼び出しを[ユーザーインポートのジョブ作成エンドポイント](/docs/ja-jp/api/management/v2#!/Jobs/post_users_imports)に対して行います。`MGMT_API_ACCESS_TOKEN`、`CONNECTION_ID`、`JSON_USER_FILE_PATH`のプレースホルダーをそれぞれManagement APIのアクセストークン、接続ID、ユーザーファイル名に置き換えます。 -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/api/v2/jobs/usersimports' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'content-type: multipart/form-data ' \ - --data '{ "connection_id": "CONNECTION_ID", "users": "JSON_USER_FILE_PATH" }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/jobs/usersimports"); + --data '{ "connection_id": "CONNECTION_ID", "users": "JSON_USER_FILE_PATH" }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/jobs/usersimports"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "multipart/form-data "); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); -request.AddParameter("multipart/form-data ", "{ \"connection_id\": \"CONNECTION_ID\", \"users\": \"JSON_USER_FILE_PATH\" }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("multipart/form-data ", "{ "connection_id": "CONNECTION_ID", "users": "JSON_USER_FILE_PATH" }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -39,7 +46,7 @@ func main() { url := "https://{yourDomain}/api/v2/jobs/usersimports" - payload := strings.NewReader("{ \"connection_id\": \"CONNECTION_ID\", \"users\": \"JSON_USER_FILE_PATH\" }") + payload := strings.NewReader("{ "connection_id": "CONNECTION_ID", "users": "JSON_USER_FILE_PATH" }") req, _ := http.NewRequest("POST", url, payload) @@ -54,13 +61,17 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/jobs/usersimports") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/jobs/usersimports") .header("content-type", "multipart/form-data ") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") - .body("{ \"connection_id\": \"CONNECTION_ID\", \"users\": \"JSON_USER_FILE_PATH\" }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "connection_id": "CONNECTION_ID", "users": "JSON_USER_FILE_PATH" }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -76,8 +87,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"multipart/form-data ", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN" }; @@ -101,8 +114,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/jobs/usersimports", @@ -112,7 +127,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{ \"connection_id\": \"CONNECTION_ID\", \"users\": \"JSON_USER_FILE_PATH\" }", + CURLOPT_POSTFIELDS => "{ "connection_id": "CONNECTION_ID", "users": "JSON_USER_FILE_PATH" }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "content-type: multipart/form-data " @@ -128,12 +143,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"connection_id\": \"CONNECTION_ID\", \"users\": \"JSON_USER_FILE_PATH\" }" +payload = "{ "connection_id": "CONNECTION_ID", "users": "JSON_USER_FILE_PATH" }" headers = { 'content-type': "multipart/form-data ", @@ -145,8 +162,10 @@ conn.request("POST", "/{yourDomain}/api/v2/jobs/usersimports", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -159,11 +178,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["content-type"] = 'multipart/form-data ' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' -request.body = "{ \"connection_id\": \"CONNECTION_ID\", \"users\": \"JSON_USER_FILE_PATH\" }" +request.body = "{ "connection_id": "CONNECTION_ID", "users": "JSON_USER_FILE_PATH" }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "multipart/form-data ", @@ -189,20 +210,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
    diff --git a/main/docs/ja-jp/manage-users/user-accounts/user-profiles/root-attributes/set-root-attributes-during-user-sign-up.mdx b/main/docs/ja-jp/manage-users/user-accounts/user-profiles/root-attributes/set-root-attributes-during-user-sign-up.mdx index 9473f07ad..f29e17213 100644 --- a/main/docs/ja-jp/manage-users/user-accounts/user-profiles/root-attributes/set-root-attributes-during-user-sign-up.mdx +++ b/main/docs/ja-jp/manage-users/user-accounts/user-profiles/root-attributes/set-root-attributes-during-user-sign-up.mdx @@ -10,25 +10,32 @@ permalink: "set-root-attributes-during-user-sign-up" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Auth0のManagement APIを使用して、サインアップ時にユーザーのルート属性を設定することができます。これにより、ユーザーの作成時にルート属性を設定するために必要なAPI呼び出しの数を最小限に抑えることができます。 [ユーザー作成エンドポイント](/docs/ja-jp/api/management/v2#!/Users/post_users)に`POST`呼び出しを行います。必ず、`MGMT_API_ACCESS_TOKEN`、`CONNECTION_NAME`、`EMAIL_VALUE`、`PASSWORD_VALUE`、`GIVEN_NAME_VALUE`、`FAMILY_NAME_VALUE`、`NAME_VALUE`、`NICKNAME_VALUE`、および`PICTURE`のプレースホルダーの値を、それぞれご自身のManagement APIのアクセストークン、初期接続名、メールアドレス、パスワード、名、姓、名前、ニックネーム、写真のURLに置き換えてください。 -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/api/v2/users' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{ "connection": CONNECTION_NAME, "email": EMAIL_VALUE, "password": PASSWORD_VALUE, "given_name": GIVEN_NAME_VALUE, "family_name": FAMILY_NAME_VALUE,"name": NAME_VALUE, "nickname": NICKNAME_VALUE,"picture": PICTURE_VALUE }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/users"); + --data '{ "connection": CONNECTION_NAME, "email": EMAIL_VALUE, "password": PASSWORD_VALUE, "given_name": GIVEN_NAME_VALUE, "family_name": FAMILY_NAME_VALUE,"name": NAME_VALUE, "nickname": NICKNAME_VALUE,"picture": PICTURE_VALUE }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{ \"connection\": CONNECTION_NAME, \"email\": EMAIL_VALUE, \"password\": PASSWORD_VALUE, \"given_name\": GIVEN_NAME_VALUE, \"family_name\": FAMILY_NAME_VALUE,\"name\": NAME_VALUE, \"nickname\": NICKNAME_VALUE,\"picture\": PICTURE_VALUE }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "connection": CONNECTION_NAME, "email": EMAIL_VALUE, "password": PASSWORD_VALUE, "given_name": GIVEN_NAME_VALUE, "family_name": FAMILY_NAME_VALUE,"name": NAME_VALUE, "nickname": NICKNAME_VALUE,"picture": PICTURE_VALUE }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -41,7 +48,7 @@ func main() { url := "https://{yourDomain}/api/v2/users" - payload := strings.NewReader("{ \"connection\": CONNECTION_NAME, \"email\": EMAIL_VALUE, \"password\": PASSWORD_VALUE, \"given_name\": GIVEN_NAME_VALUE, \"family_name\": FAMILY_NAME_VALUE,\"name\": NAME_VALUE, \"nickname\": NICKNAME_VALUE,\"picture\": PICTURE_VALUE }") + payload := strings.NewReader("{ "connection": CONNECTION_NAME, "email": EMAIL_VALUE, "password": PASSWORD_VALUE, "given_name": GIVEN_NAME_VALUE, "family_name": FAMILY_NAME_VALUE,"name": NAME_VALUE, "nickname": NICKNAME_VALUE,"picture": PICTURE_VALUE }") req, _ := http.NewRequest("POST", url, payload) @@ -57,14 +64,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/users") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/users") .header("content-type", "application/json") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ \"connection\": CONNECTION_NAME, \"email\": EMAIL_VALUE, \"password\": PASSWORD_VALUE, \"given_name\": GIVEN_NAME_VALUE, \"family_name\": FAMILY_NAME_VALUE,\"name\": NAME_VALUE, \"nickname\": NICKNAME_VALUE,\"picture\": PICTURE_VALUE }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "connection": CONNECTION_NAME, "email": EMAIL_VALUE, "password": PASSWORD_VALUE, "given_name": GIVEN_NAME_VALUE, "family_name": FAMILY_NAME_VALUE,"name": NAME_VALUE, "nickname": NICKNAME_VALUE,"picture": PICTURE_VALUE }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -81,8 +92,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @@ -107,8 +120,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users", @@ -118,7 +133,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{ \"connection\": CONNECTION_NAME, \"email\": EMAIL_VALUE, \"password\": PASSWORD_VALUE, \"given_name\": GIVEN_NAME_VALUE, \"family_name\": FAMILY_NAME_VALUE,\"name\": NAME_VALUE, \"nickname\": NICKNAME_VALUE,\"picture\": PICTURE_VALUE }", + CURLOPT_POSTFIELDS => "{ "connection": CONNECTION_NAME, "email": EMAIL_VALUE, "password": PASSWORD_VALUE, "given_name": GIVEN_NAME_VALUE, "family_name": FAMILY_NAME_VALUE,"name": NAME_VALUE, "nickname": NICKNAME_VALUE,"picture": PICTURE_VALUE }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "cache-control: no-cache", @@ -135,12 +150,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"connection\": CONNECTION_NAME, \"email\": EMAIL_VALUE, \"password\": PASSWORD_VALUE, \"given_name\": GIVEN_NAME_VALUE, \"family_name\": FAMILY_NAME_VALUE,\"name\": NAME_VALUE, \"nickname\": NICKNAME_VALUE,\"picture\": PICTURE_VALUE }" +payload = "{ "connection": CONNECTION_NAME, "email": EMAIL_VALUE, "password": PASSWORD_VALUE, "given_name": GIVEN_NAME_VALUE, "family_name": FAMILY_NAME_VALUE,"name": NAME_VALUE, "nickname": NICKNAME_VALUE,"picture": PICTURE_VALUE }" headers = { 'content-type': "application/json", @@ -153,8 +170,10 @@ conn.request("POST", "/{yourDomain}/api/v2/users", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -168,11 +187,13 @@ request = Net::HTTP::Post.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ \"connection\": CONNECTION_NAME, \"email\": EMAIL_VALUE, \"password\": PASSWORD_VALUE, \"given_name\": GIVEN_NAME_VALUE, \"family_name\": FAMILY_NAME_VALUE,\"name\": NAME_VALUE, \"nickname\": NICKNAME_VALUE,\"picture\": PICTURE_VALUE }" +request.body = "{ "connection": CONNECTION_NAME, "email": EMAIL_VALUE, "password": PASSWORD_VALUE, "given_name": GIVEN_NAME_VALUE, "family_name": FAMILY_NAME_VALUE,"name": NAME_VALUE, "nickname": NICKNAME_VALUE,"picture": PICTURE_VALUE }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -199,21 +220,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - - +dataTask.resume() +``` +
    diff --git a/main/docs/ja-jp/manage-users/user-accounts/user-profiles/root-attributes/update-root-attributes-for-users.mdx b/main/docs/ja-jp/manage-users/user-accounts/user-profiles/root-attributes/update-root-attributes-for-users.mdx index 57159ef6b..713034aca 100644 --- a/main/docs/ja-jp/manage-users/user-accounts/user-profiles/root-attributes/update-root-attributes-for-users.mdx +++ b/main/docs/ja-jp/manage-users/user-accounts/user-profiles/root-attributes/update-root-attributes-for-users.mdx @@ -10,6 +10,7 @@ permalink: "update-root-attributes-for-users" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Auth0 Management APIを使用すると、既存ユーザープロファイルのルート属性を更新することができます。 @@ -17,20 +18,26 @@ Auth0の[正規化ユーザープロファイル](/docs/ja-jp/manage-users/user- `PATCH`呼び出しを[ユーザー更新エンドポイント](/docs/ja-jp/api/management/v2#!/Users/patch_users_by_id)に対して行います。`USER_ID`、`MGMT_API_ACCESS_TOKEN`、`GIVEN_NAME_VALUE`、`FAMILY_NAME_VALUE`、`NAME_VALUE`、`NICKNAME_VALUE`、`PICTURE`のプレースホルダーをそれぞれユーザーID、Management APIのアクセストークン、名、氏、名前、ニックネーム、画像URLで置き換えます。 -export const codeExample1 = `curl --request PATCH \ + +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/users/USER_ID' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{ "given_name": GIVEN_NAME_VALUE, "family_name": FAMILY_NAME_VALUE,"name": NAME_VALUE, "nickname": NICKNAME_VALUE,"picture": PICTURE_VALUE }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/users/USER_ID"); + --data '{ "given_name": GIVEN_NAME_VALUE, "family_name": FAMILY_NAME_VALUE,"name": NAME_VALUE, "nickname": NICKNAME_VALUE,"picture": PICTURE_VALUE }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users/USER_ID"); var request = new RestRequest(Method.PATCH); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{ \"given_name\": GIVEN_NAME_VALUE, \"family_name\": FAMILY_NAME_VALUE,\"name\": NAME_VALUE, \"nickname\": NICKNAME_VALUE,\"picture\": PICTURE_VALUE }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "given_name": GIVEN_NAME_VALUE, "family_name": FAMILY_NAME_VALUE,"name": NAME_VALUE, "nickname": NICKNAME_VALUE,"picture": PICTURE_VALUE }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -43,7 +50,7 @@ func main() { url := "https://{yourDomain}/api/v2/users/USER_ID" - payload := strings.NewReader("{ \"given_name\": GIVEN_NAME_VALUE, \"family_name\": FAMILY_NAME_VALUE,\"name\": NAME_VALUE, \"nickname\": NICKNAME_VALUE,\"picture\": PICTURE_VALUE }") + payload := strings.NewReader("{ "given_name": GIVEN_NAME_VALUE, "family_name": FAMILY_NAME_VALUE,"name": NAME_VALUE, "nickname": NICKNAME_VALUE,"picture": PICTURE_VALUE }") req, _ := http.NewRequest("PATCH", url, payload) @@ -59,14 +66,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/users/USER_ID") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/users/USER_ID") .header("content-type", "application/json") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ \"given_name\": GIVEN_NAME_VALUE, \"family_name\": FAMILY_NAME_VALUE,\"name\": NAME_VALUE, \"nickname\": NICKNAME_VALUE,\"picture\": PICTURE_VALUE }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "given_name": GIVEN_NAME_VALUE, "family_name": FAMILY_NAME_VALUE,"name": NAME_VALUE, "nickname": NICKNAME_VALUE,"picture": PICTURE_VALUE }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -83,8 +94,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @@ -109,8 +122,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users/USER_ID", @@ -120,7 +135,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{ \"given_name\": GIVEN_NAME_VALUE, \"family_name\": FAMILY_NAME_VALUE,\"name\": NAME_VALUE, \"nickname\": NICKNAME_VALUE,\"picture\": PICTURE_VALUE }", + CURLOPT_POSTFIELDS => "{ "given_name": GIVEN_NAME_VALUE, "family_name": FAMILY_NAME_VALUE,"name": NAME_VALUE, "nickname": NICKNAME_VALUE,"picture": PICTURE_VALUE }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "cache-control: no-cache", @@ -137,12 +152,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"given_name\": GIVEN_NAME_VALUE, \"family_name\": FAMILY_NAME_VALUE,\"name\": NAME_VALUE, \"nickname\": NICKNAME_VALUE,\"picture\": PICTURE_VALUE }" +payload = "{ "given_name": GIVEN_NAME_VALUE, "family_name": FAMILY_NAME_VALUE,"name": NAME_VALUE, "nickname": NICKNAME_VALUE,"picture": PICTURE_VALUE }" headers = { 'content-type': "application/json", @@ -155,8 +172,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/users/USER_ID", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -170,11 +189,13 @@ request = Net::HTTP::Patch.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ \"given_name\": GIVEN_NAME_VALUE, \"family_name\": FAMILY_NAME_VALUE,\"name\": NAME_VALUE, \"nickname\": NICKNAME_VALUE,\"picture\": PICTURE_VALUE }" +request.body = "{ "given_name": GIVEN_NAME_VALUE, "family_name": FAMILY_NAME_VALUE,"name": NAME_VALUE, "nickname": NICKNAME_VALUE,"picture": PICTURE_VALUE }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -201,20 +222,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
    diff --git a/main/docs/ja-jp/manage-users/user-migration/bulk-user-exports.mdx b/main/docs/ja-jp/manage-users/user-migration/bulk-user-exports.mdx index 539e696e6..ddc39988a 100644 --- a/main/docs/ja-jp/manage-users/user-migration/bulk-user-exports.mdx +++ b/main/docs/ja-jp/manage-users/user-migration/bulk-user-exports.mdx @@ -10,6 +10,7 @@ permalink: "bulk-user-exports" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; `POST /api/v2/jobs/users-exports`エンドポイントを使用して、[接続](/docs/ja-jp/identityproviders)に関連付けられているすべてのユーザー、またはテナント内のすべてのユーザーをエクスポートするジョブを作成できます。 @@ -53,18 +54,24 @@ import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; 必要なスコープ:`read:users` -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/api/v2/jobs/users-exports' \ --header 'authorization: Bearer {yourMgmtAPIAccessToken}' \ --header 'content-type: application/json' \ - --data '{"connection_id": "{yourConnectionId}", "format": "csv", "limit": 5, "fields": [{"name": "email"}, { "name": "identities[0].connection", "export_as": "provider" }]}'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/jobs/users-exports"); + --data '{"connection_id": "{yourConnectionId}", "format": "csv", "limit": 5, "fields": [{"name": "email"}, { "name": "identities[0].connection", "export_as": "provider" }]}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/jobs/users-exports"); var request = new RestRequest(Method.POST); request.AddHeader("authorization", "Bearer {yourMgmtAPIAccessToken}"); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\"connection_id\": \"{yourConnectionId}\", \"format\": \"csv\", \"limit\": 5, \"fields\": [{\"name\": \"email\"}, { \"name\": \"identities[0].connection\", \"export_as\": \"provider\" }]}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{"connection_id": "{yourConnectionId}", "format": "csv", "limit": 5, "fields": [{"name": "email"}, { "name": "identities[0].connection", "export_as": "provider" }]}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -77,7 +84,7 @@ func main() { url := "https://{yourDomain}/api/v2/jobs/users-exports" - payload := strings.NewReader("{\"connection_id\": \"{yourConnectionId}\", \"format\": \"csv\", \"limit\": 5, \"fields\": [{\"name\": \"email\"}, { \"name\": \"identities[0].connection\", \"export_as\": \"provider\" }]}") + payload := strings.NewReader("{"connection_id": "{yourConnectionId}", "format": "csv", "limit": 5, "fields": [{"name": "email"}, { "name": "identities[0].connection", "export_as": "provider" }]}") req, _ := http.NewRequest("POST", url, payload) @@ -92,13 +99,17 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/jobs/users-exports") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/jobs/users-exports") .header("authorization", "Bearer {yourMgmtAPIAccessToken}") .header("content-type", "application/json") - .body("{\"connection_id\": \"{yourConnectionId}\", \"format\": \"csv\", \"limit\": 5, \"fields\": [{\"name\": \"email\"}, { \"name\": \"identities[0].connection\", \"export_as\": \"provider\" }]}") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{"connection_id": "{yourConnectionId}", "format": "csv", "limit": 5, "fields": [{"name": "email"}, { "name": "identities[0].connection", "export_as": "provider" }]}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -119,8 +130,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer {yourMgmtAPIAccessToken}", @"content-type": @"application/json" }; @@ -148,8 +161,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/jobs/users-exports", @@ -159,7 +174,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{\"connection_id\": \"{yourConnectionId}\", \"format\": \"csv\", \"limit\": 5, \"fields\": [{\"name\": \"email\"}, { \"name\": \"identities[0].connection\", \"export_as\": \"provider\" }]}", + CURLOPT_POSTFIELDS => "{"connection_id": "{yourConnectionId}", "format": "csv", "limit": 5, "fields": [{"name": "email"}, { "name": "identities[0].connection", "export_as": "provider" }]}", CURLOPT_HTTPHEADER => [ "authorization: Bearer {yourMgmtAPIAccessToken}", "content-type: application/json" @@ -175,12 +190,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"connection_id\": \"{yourConnectionId}\", \"format\": \"csv\", \"limit\": 5, \"fields\": [{\"name\": \"email\"}, { \"name\": \"identities[0].connection\", \"export_as\": \"provider\" }]}" +payload = "{"connection_id": "{yourConnectionId}", "format": "csv", "limit": 5, "fields": [{"name": "email"}, { "name": "identities[0].connection", "export_as": "provider" }]}" headers = { 'authorization': "Bearer {yourMgmtAPIAccessToken}", @@ -192,8 +209,10 @@ conn.request("POST", "/{yourDomain}/api/v2/jobs/users-exports", payload, headers res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -206,11 +225,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["authorization"] = 'Bearer {yourMgmtAPIAccessToken}' request["content-type"] = 'application/json' -request.body = "{\"connection_id\": \"{yourConnectionId}\", \"format\": \"csv\", \"limit\": 5, \"fields\": [{\"name\": \"email\"}, { \"name\": \"identities[0].connection\", \"export_as\": \"provider\" }]}" +request.body = "{"connection_id": "{yourConnectionId}", "format": "csv", "limit": 5, "fields": [{"name": "email"}, { "name": "identities[0].connection", "export_as": "provider" }]}" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "authorization": "Bearer {yourMgmtAPIAccessToken}", @@ -248,20 +269,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + 応答はこのようになっているはずです。 @@ -323,18 +333,24 @@ dataTask.resume()`; エクスポート要求(3つのフィールドすべて)は次のようになります。 -export const codeExample11 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/api/v2/jobs/users-exports' \ --header 'authorization: Bearer {yourMgmtAPIAccessToken}' \ --header 'content-type: application/json' \ - --data '{"connection_id": "{yourConnectionId}", "format": "csv", "limit": 5, "fields": [{"name": "email"}, {"name": "user_metadata.consent.given"}, {"name": "user_metadata.consent.date"}, {"name": "user_metadata.consent.text_details"}]}'`; -export const codeExample12 = `var client = new RestClient("https://{yourDomain}/api/v2/jobs/users-exports"); + --data '{"connection_id": "{yourConnectionId}", "format": "csv", "limit": 5, "fields": [{"name": "email"}, {"name": "user_metadata.consent.given"}, {"name": "user_metadata.consent.date"}, {"name": "user_metadata.consent.text_details"}]}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/jobs/users-exports"); var request = new RestRequest(Method.POST); request.AddHeader("authorization", "Bearer {yourMgmtAPIAccessToken}"); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\"connection_id\": \"{yourConnectionId}\", \"format\": \"csv\", \"limit\": 5, \"fields\": [{\"name\": \"email\"}, {\"name\": \"user_metadata.consent.given\"}, {\"name\": \"user_metadata.consent.date\"}, {\"name\": \"user_metadata.consent.text_details\"}]}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample13 = `package main +request.AddParameter("application/json", "{"connection_id": "{yourConnectionId}", "format": "csv", "limit": 5, "fields": [{"name": "email"}, {"name": "user_metadata.consent.given"}, {"name": "user_metadata.consent.date"}, {"name": "user_metadata.consent.text_details"}]}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -347,7 +363,7 @@ func main() { url := "https://{yourDomain}/api/v2/jobs/users-exports" - payload := strings.NewReader("{\"connection_id\": \"{yourConnectionId}\", \"format\": \"csv\", \"limit\": 5, \"fields\": [{\"name\": \"email\"}, {\"name\": \"user_metadata.consent.given\"}, {\"name\": \"user_metadata.consent.date\"}, {\"name\": \"user_metadata.consent.text_details\"}]}") + payload := strings.NewReader("{"connection_id": "{yourConnectionId}", "format": "csv", "limit": 5, "fields": [{"name": "email"}, {"name": "user_metadata.consent.given"}, {"name": "user_metadata.consent.date"}, {"name": "user_metadata.consent.text_details"}]}") req, _ := http.NewRequest("POST", url, payload) @@ -362,13 +378,17 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample14 = `HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/jobs/users-exports") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/jobs/users-exports") .header("authorization", "Bearer {yourMgmtAPIAccessToken}") .header("content-type", "application/json") - .body("{\"connection_id\": \"{yourConnectionId}\", \"format\": \"csv\", \"limit\": 5, \"fields\": [{\"name\": \"email\"}, {\"name\": \"user_metadata.consent.given\"}, {\"name\": \"user_metadata.consent.date\"}, {\"name\": \"user_metadata.consent.text_details\"}]}") - .asString();`; -export const codeExample15 = `var axios = require("axios").default; + .body("{"connection_id": "{yourConnectionId}", "format": "csv", "limit": 5, "fields": [{"name": "email"}, {"name": "user_metadata.consent.given"}, {"name": "user_metadata.consent.date"}, {"name": "user_metadata.consent.text_details"}]}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -394,8 +414,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample16 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer {yourMgmtAPIAccessToken}", @"content-type": @"application/json" }; @@ -423,8 +445,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/jobs/users-exports", @@ -434,7 +458,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{\"connection_id\": \"{yourConnectionId}\", \"format\": \"csv\", \"limit\": 5, \"fields\": [{\"name\": \"email\"}, {\"name\": \"user_metadata.consent.given\"}, {\"name\": \"user_metadata.consent.date\"}, {\"name\": \"user_metadata.consent.text_details\"}]}", + CURLOPT_POSTFIELDS => "{"connection_id": "{yourConnectionId}", "format": "csv", "limit": 5, "fields": [{"name": "email"}, {"name": "user_metadata.consent.given"}, {"name": "user_metadata.consent.date"}, {"name": "user_metadata.consent.text_details"}]}", CURLOPT_HTTPHEADER => [ "authorization: Bearer {yourMgmtAPIAccessToken}", "content-type: application/json" @@ -450,12 +474,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"connection_id\": \"{yourConnectionId}\", \"format\": \"csv\", \"limit\": 5, \"fields\": [{\"name\": \"email\"}, {\"name\": \"user_metadata.consent.given\"}, {\"name\": \"user_metadata.consent.date\"}, {\"name\": \"user_metadata.consent.text_details\"}]}" +payload = "{"connection_id": "{yourConnectionId}", "format": "csv", "limit": 5, "fields": [{"name": "email"}, {"name": "user_metadata.consent.given"}, {"name": "user_metadata.consent.date"}, {"name": "user_metadata.consent.text_details"}]}" headers = { 'authorization': "Bearer {yourMgmtAPIAccessToken}", @@ -467,8 +493,10 @@ conn.request("POST", "/{yourDomain}/api/v2/jobs/users-exports", payload, headers res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -481,11 +509,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["authorization"] = 'Bearer {yourMgmtAPIAccessToken}' request["content-type"] = 'application/json' -request.body = "{\"connection_id\": \"{yourConnectionId}\", \"format\": \"csv\", \"limit\": 5, \"fields\": [{\"name\": \"email\"}, {\"name\": \"user_metadata.consent.given\"}, {\"name\": \"user_metadata.consent.date\"}, {\"name\": \"user_metadata.consent.text_details\"}]}" +request.body = "{"connection_id": "{yourConnectionId}", "format": "csv", "limit": 5, "fields": [{"name": "email"}, {"name": "user_metadata.consent.given"}, {"name": "user_metadata.consent.date"}, {"name": "user_metadata.consent.text_details"}]}" response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "authorization": "Bearer {yourMgmtAPIAccessToken}", @@ -517,20 +547,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + @@ -554,18 +573,24 @@ Auth0によって生成されたエクスポートを使用してユーザーを この場合、前に使用したのと同じ例では、要求は次のようになります。 -export const codeExample21 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/api/v2/jobs/users-exports' \ --header 'authorization: Bearer {yourMgmtAPIAccessToken}' \ --header 'content-type: application/json' \ - --data '{"connection_id": "{yourConnectionId}", "format": "json", "limit": 5, "fields": [{"name": "email"}, {"name": "user_metadata.consent"}]}'`; -export const codeExample22 = `var client = new RestClient("https://{yourDomain}/api/v2/jobs/users-exports"); + --data '{"connection_id": "{yourConnectionId}", "format": "json", "limit": 5, "fields": [{"name": "email"}, {"name": "user_metadata.consent"}]}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/jobs/users-exports"); var request = new RestRequest(Method.POST); request.AddHeader("authorization", "Bearer {yourMgmtAPIAccessToken}"); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\"connection_id\": \"{yourConnectionId}\", \"format\": \"json\", \"limit\": 5, \"fields\": [{\"name\": \"email\"}, {\"name\": \"user_metadata.consent\"}]}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample23 = `package main +request.AddParameter("application/json", "{"connection_id": "{yourConnectionId}", "format": "json", "limit": 5, "fields": [{"name": "email"}, {"name": "user_metadata.consent"}]}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -578,7 +603,7 @@ func main() { url := "https://{yourDomain}/api/v2/jobs/users-exports" - payload := strings.NewReader("{\"connection_id\": \"{yourConnectionId}\", \"format\": \"json\", \"limit\": 5, \"fields\": [{\"name\": \"email\"}, {\"name\": \"user_metadata.consent\"}]}") + payload := strings.NewReader("{"connection_id": "{yourConnectionId}", "format": "json", "limit": 5, "fields": [{"name": "email"}, {"name": "user_metadata.consent"}]}") req, _ := http.NewRequest("POST", url, payload) @@ -593,13 +618,17 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample24 = `HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/jobs/users-exports") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/jobs/users-exports") .header("authorization", "Bearer {yourMgmtAPIAccessToken}") .header("content-type", "application/json") - .body("{\"connection_id\": \"{yourConnectionId}\", \"format\": \"json\", \"limit\": 5, \"fields\": [{\"name\": \"email\"}, {\"name\": \"user_metadata.consent\"}]}") - .asString();`; -export const codeExample25 = `var axios = require("axios").default; + .body("{"connection_id": "{yourConnectionId}", "format": "json", "limit": 5, "fields": [{"name": "email"}, {"name": "user_metadata.consent"}]}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -620,8 +649,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample26 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer {yourMgmtAPIAccessToken}", @"content-type": @"application/json" }; @@ -649,8 +680,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample27 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/jobs/users-exports", @@ -660,7 +693,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{\"connection_id\": \"{yourConnectionId}\", \"format\": \"json\", \"limit\": 5, \"fields\": [{\"name\": \"email\"}, {\"name\": \"user_metadata.consent\"}]}", + CURLOPT_POSTFIELDS => "{"connection_id": "{yourConnectionId}", "format": "json", "limit": 5, "fields": [{"name": "email"}, {"name": "user_metadata.consent"}]}", CURLOPT_HTTPHEADER => [ "authorization: Bearer {yourMgmtAPIAccessToken}", "content-type: application/json" @@ -676,12 +709,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample28 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"connection_id\": \"{yourConnectionId}\", \"format\": \"json\", \"limit\": 5, \"fields\": [{\"name\": \"email\"}, {\"name\": \"user_metadata.consent\"}]}" +payload = "{"connection_id": "{yourConnectionId}", "format": "json", "limit": 5, "fields": [{"name": "email"}, {"name": "user_metadata.consent"}]}" headers = { 'authorization': "Bearer {yourMgmtAPIAccessToken}", @@ -693,8 +728,10 @@ conn.request("POST", "/{yourDomain}/api/v2/jobs/users-exports", payload, headers res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample29 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -707,11 +744,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["authorization"] = 'Bearer {yourMgmtAPIAccessToken}' request["content-type"] = 'application/json' -request.body = "{\"connection_id\": \"{yourConnectionId}\", \"format\": \"json\", \"limit\": 5, \"fields\": [{\"name\": \"email\"}, {\"name\": \"user_metadata.consent\"}]}" +request.body = "{"connection_id": "{yourConnectionId}", "format": "json", "limit": 5, "fields": [{"name": "email"}, {"name": "user_metadata.consent"}]}" response = http.request(request) -puts response.read_body`; -export const codeExample30 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "authorization": "Bearer {yourMgmtAPIAccessToken}", @@ -743,20 +782,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ## エクスポートステータスの確認 @@ -766,14 +794,20 @@ dataTask.resume()`; 必要なスコープ: `create:users`, `read:users`, `create:passwords_checking_job` -export const codeExample31 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/jobs/%7ByourJobId%7D' \ - --header 'authorization: Bearer {yourMgmtAPIAccessToken}'`; -export const codeExample32 = `var client = new RestClient("https://{yourDomain}/api/v2/jobs/%7ByourJobId%7D"); + --header 'authorization: Bearer {yourMgmtAPIAccessToken}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/jobs/%7ByourJobId%7D"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer {yourMgmtAPIAccessToken}"); -IRestResponse response = client.Execute(request);`; -export const codeExample33 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -797,11 +831,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample34 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/jobs/%7ByourJobId%7D") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/jobs/%7ByourJobId%7D") .header("authorization", "Bearer {yourMgmtAPIAccessToken}") - .asString();`; -export const codeExample35 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -813,8 +851,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample36 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer {yourMgmtAPIAccessToken}" }; @@ -834,8 +874,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample37 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/jobs/%7ByourJobId%7D", @@ -859,8 +901,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample38 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -871,8 +915,10 @@ conn.request("GET", "/{yourDomain}/api/v2/jobs/%7ByourJobId%7D", headers=headers res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample39 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -886,8 +932,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer {yourMgmtAPIAccessToken}' response = http.request(request) -puts response.read_body`; -export const codeExample40 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer {yourMgmtAPIAccessToken}"] @@ -907,20 +955,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + 次のような応答が返されます。 diff --git a/main/docs/ja-jp/manage-users/user-migration/bulk-user-imports.mdx b/main/docs/ja-jp/manage-users/user-migration/bulk-user-imports.mdx index aa1be11ac..9bc82a969 100644 --- a/main/docs/ja-jp/manage-users/user-migration/bulk-user-imports.mdx +++ b/main/docs/ja-jp/manage-users/user-migration/bulk-user-imports.mdx @@ -10,6 +10,7 @@ permalink: "bulk-user-imports" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; ユーザーデータを一括してAuth0にインポートするには、[ユーザーインポートジョブ作成](/docs/ja-jp/api/management/v2#!/Jobs/post_users_imports)エンドポイントを使用します。一括インポートは、ユーザーを既存のデータベースやサービスからAuth0に移行するのに便利です。 @@ -52,19 +53,39 @@ JSONファイルのスキーマと例については、「[一括インポート 一括ユーザーインポートジョブを始めるには、`POST`要求を[一括ユーザーインポートジョブ作成](https://auth0.com/docs/api/management/v2#!/Jobs/post_users_imports)エンドポイントに対して行います。必ず、`MGMT_API_ACCESS_TOKEN`、`USERS_IMPORT_FILE.json`、`CONNECTION_ID`、および`EXTERNAL_ID`のプレースホルダーの値をそれぞれManagement APIのアクセストークン、ユーザーのJSONファイル、データベース[接続ID](/docs/ja-jp/authenticate/identity-providers/locate-the-connection-id)と外部IDに置き換えます。 -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/api/v2/jobs/users-imports' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --form users=@USERS_IMPORT_FILE.json \ --form connection_id=CONNECTION_ID \ - --form external_id=EXTERNAL_ID`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/jobs/users-imports"); + --form external_id=EXTERNAL_ID +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/jobs/users-imports"); var request = new RestRequest(Method.POST); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("content-type", "multipart/form-data; boundary=---011000010111000001101001"); -request.AddParameter("multipart/form-data; boundary=---011000010111000001101001", "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"users\"; filename=\"USERS_IMPORT_FILE.json\"\r\nContent-Type: text/json\r\n\r\n\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"connection_id\"\r\n\r\nCONNECTION_ID\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"external_id\"\r\n\r\nEXTERNAL_ID\r\n-----011000010111000001101001--\r\n", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("multipart/form-data; boundary=---011000010111000001101001", "-----011000010111000001101001\r +Content-Disposition: form-data; name="users"; filename="USERS_IMPORT_FILE.json"\r +Content-Type: text/json\r +\r +\r +-----011000010111000001101001\r +Content-Disposition: form-data; name="connection_id"\r +\r +CONNECTION_ID\r +-----011000010111000001101001\r +Content-Disposition: form-data; name="external_id"\r +\r +EXTERNAL_ID\r +-----011000010111000001101001--\r +", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -77,7 +98,21 @@ func main() { url := "https://{yourDomain}/api/v2/jobs/users-imports" - payload := strings.NewReader("-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"users\"; filename=\"USERS_IMPORT_FILE.json\"\r\nContent-Type: text/json\r\n\r\n\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"connection_id\"\r\n\r\nCONNECTION_ID\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"external_id\"\r\n\r\nEXTERNAL_ID\r\n-----011000010111000001101001--\r\n") + payload := strings.NewReader("-----011000010111000001101001\r +Content-Disposition: form-data; name="users"; filename="USERS_IMPORT_FILE.json"\r +Content-Type: text/json\r +\r +\r +-----011000010111000001101001\r +Content-Disposition: form-data; name="connection_id"\r +\r +CONNECTION_ID\r +-----011000010111000001101001\r +Content-Disposition: form-data; name="external_id"\r +\r +EXTERNAL_ID\r +-----011000010111000001101001--\r +") req, _ := http.NewRequest("POST", url, payload) @@ -92,13 +127,31 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/jobs/users-imports") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/jobs/users-imports") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("content-type", "multipart/form-data; boundary=---011000010111000001101001") - .body("-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"users\"; filename=\"USERS_IMPORT_FILE.json\"\r\nContent-Type: text/json\r\n\r\n\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"connection_id\"\r\n\r\nCONNECTION_ID\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"external_id\"\r\n\r\nEXTERNAL_ID\r\n-----011000010111000001101001--\r\n") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("-----011000010111000001101001\r +Content-Disposition: form-data; name="users"; filename="USERS_IMPORT_FILE.json"\r +Content-Type: text/json\r +\r +\r +-----011000010111000001101001\r +Content-Disposition: form-data; name="connection_id"\r +\r +CONNECTION_ID\r +-----011000010111000001101001\r +Content-Disposition: form-data; name="external_id"\r +\r +EXTERNAL_ID\r +-----011000010111000001101001--\r +") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -107,15 +160,31 @@ var options = { authorization: 'Bearer MGMT_API_ACCESS_TOKEN', 'content-type': 'multipart/form-data; boundary=---011000010111000001101001' }, - data: '-----011000010111000001101001\r\nContent-Disposition: form-data; name="users"; filename="USERS_IMPORT_FILE.json"\r\nContent-Type: text/json\r\n\r\n\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name="connection_id"\r\n\r\nCONNECTION_ID\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name="external_id"\r\n\r\nEXTERNAL_ID\r\n-----011000010111000001101001--\r\n' + data: '-----011000010111000001101001\r +Content-Disposition: form-data; name="users"; filename="USERS_IMPORT_FILE.json"\r +Content-Type: text/json\r +\r +\r +-----011000010111000001101001\r +Content-Disposition: form-data; name="connection_id"\r +\r +CONNECTION_ID\r +-----011000010111000001101001\r +Content-Disposition: form-data; name="external_id"\r +\r +EXTERNAL_ID\r +-----011000010111000001101001--\r +' }; axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @"content-type": @"multipart/form-data; boundary=---011000010111000001101001" }; @@ -127,20 +196,28 @@ NSString *boundary = @"---011000010111000001101001"; NSError *error; NSMutableString *body = [NSMutableString string]; for (NSDictionary *param in parameters) { - [body appendFormat:@"--%@\r\n", boundary]; + [body appendFormat:@"--%@\r +", boundary]; if (param[@"fileName"]) { - [body appendFormat:@"Content-Disposition:form-data; name=\"%@\"; filename=\"%@\"\r\n", param[@"name"], param[@"fileName"]]; - [body appendFormat:@"Content-Type: %@\r\n\r\n", param[@"contentType"]]; + [body appendFormat:@"Content-Disposition:form-data; name="%@"; filename="%@"\r +", param[@"name"], param[@"fileName"]]; + [body appendFormat:@"Content-Type: %@\r +\r +", param[@"contentType"]]; [body appendFormat:@"%@", [NSString stringWithContentsOfFile:param[@"fileName"] encoding:NSUTF8StringEncoding error:&error]]; if (error) { NSLog(@"%@", error); } } else { - [body appendFormat:@"Content-Disposition:form-data; name=\"%@\"\r\n\r\n", param[@"name"]]; + [body appendFormat:@"Content-Disposition:form-data; name="%@"\r +\r +", param[@"name"]]; [body appendFormat:@"%@", param[@"value"]]; } } -[body appendFormat:@"\r\n--%@--\r\n", boundary]; +[body appendFormat:@"\r +--%@--\r +", boundary]; NSData *postData = [body dataUsingEncoding:NSUTF8StringEncoding]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://{yourDomain}/api/v2/jobs/users-imports"] @@ -160,8 +237,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/jobs/users-imports", @@ -171,7 +250,21 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"users\"; filename=\"USERS_IMPORT_FILE.json\"\r\nContent-Type: text/json\r\n\r\n\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"connection_id\"\r\n\r\nCONNECTION_ID\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"external_id\"\r\n\r\nEXTERNAL_ID\r\n-----011000010111000001101001--\r\n", + CURLOPT_POSTFIELDS => "-----011000010111000001101001\r +Content-Disposition: form-data; name="users"; filename="USERS_IMPORT_FILE.json"\r +Content-Type: text/json\r +\r +\r +-----011000010111000001101001\r +Content-Disposition: form-data; name="connection_id"\r +\r +CONNECTION_ID\r +-----011000010111000001101001\r +Content-Disposition: form-data; name="external_id"\r +\r +EXTERNAL_ID\r +-----011000010111000001101001--\r +", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "content-type: multipart/form-data; boundary=---011000010111000001101001" @@ -187,12 +280,28 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"users\"; filename=\"USERS_IMPORT_FILE.json\"\r\nContent-Type: text/json\r\n\r\n\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"connection_id\"\r\n\r\nCONNECTION_ID\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"external_id\"\r\n\r\nEXTERNAL_ID\r\n-----011000010111000001101001--\r\n" +payload = "-----011000010111000001101001\r +Content-Disposition: form-data; name="users"; filename="USERS_IMPORT_FILE.json"\r +Content-Type: text/json\r +\r +\r +-----011000010111000001101001\r +Content-Disposition: form-data; name="connection_id"\r +\r +CONNECTION_ID\r +-----011000010111000001101001\r +Content-Disposition: form-data; name="external_id"\r +\r +EXTERNAL_ID\r +-----011000010111000001101001--\r +" headers = { 'authorization': "Bearer MGMT_API_ACCESS_TOKEN", @@ -204,8 +313,10 @@ conn.request("POST", "/{yourDomain}/api/v2/jobs/users-imports", payload, headers res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -218,11 +329,27 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["content-type"] = 'multipart/form-data; boundary=---011000010111000001101001' -request.body = "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"users\"; filename=\"USERS_IMPORT_FILE.json\"\r\nContent-Type: text/json\r\n\r\n\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"connection_id\"\r\n\r\nCONNECTION_ID\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"external_id\"\r\n\r\nEXTERNAL_ID\r\n-----011000010111000001101001--\r\n" +request.body = "-----011000010111000001101001\r +Content-Disposition: form-data; name="users"; filename="USERS_IMPORT_FILE.json"\r +Content-Type: text/json\r +\r +\r +-----011000010111000001101001\r +Content-Disposition: form-data; name="connection_id"\r +\r +CONNECTION_ID\r +-----011000010111000001101001\r +Content-Disposition: form-data; name="external_id"\r +\r +EXTERNAL_ID\r +-----011000010111000001101001--\r +" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "authorization": "Bearer MGMT_API_ACCESS_TOKEN", @@ -250,19 +377,25 @@ var body = "" var error: NSError? = nil for param in parameters { let paramName = param["name"]! - body += "--\(boundary)\r\n" - body += "Content-Disposition:form-data; name=\"\(paramName)\"" + body += "--\(boundary)\r +" + body += "Content-Disposition:form-data; name="\(paramName)"" if let filename = param["fileName"] { let contentType = param["content-type"]! let fileContent = String(contentsOfFile: filename, encoding: String.Encoding.utf8) if (error != nil) { print(error) } - body += "; filename=\"\(filename)\"\r\n" - body += "Content-Type: \(contentType)\r\n\r\n" + body += "; filename="\(filename)"\r +" + body += "Content-Type: \(contentType)\r +\r +" body += fileContent } else if let paramValue = param["value"] { - body += "\r\n\r\n\(paramValue)" + body += "\r +\r +\(paramValue)" } } @@ -283,20 +416,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
    @@ -363,16 +485,22 @@ dataTask.resume()`; ジョブのステータスを確認するには、`GET`要求を[ジョブ取得](https://auth0.com/docs/api/management/v2#!/Jobs/get_jobs_by_id)エンドポイントに対して行います。必ず、`MGMT_API_ACCESS_TOKEN`および`JOB_ID`のプレースホルダーの値をそれぞれManagement APIのアクセストークンとユーザーインポートジョブIDに置き換えます。 -export const codeExample11 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/jobs/JOB_ID' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ - --header 'content-type: application/json'`; -export const codeExample12 = `var client = new RestClient("https://{yourDomain}/api/v2/jobs/JOB_ID"); + --header 'content-type: application/json' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/jobs/JOB_ID"); var request = new RestRequest(Method.GET); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); -IRestResponse response = client.Execute(request);`; -export const codeExample13 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -397,12 +525,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample14 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/jobs/JOB_ID") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/jobs/JOB_ID") .header("content-type", "application/json") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") - .asString();`; -export const codeExample15 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -417,8 +549,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample16 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN" }; @@ -439,8 +573,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/jobs/JOB_ID", @@ -465,8 +601,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -480,8 +618,10 @@ conn.request("GET", "/{yourDomain}/api/v2/jobs/JOB_ID", headers=headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -496,8 +636,10 @@ request["content-type"] = 'application/json' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -520,20 +662,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ユーザーインポートジョブのステータスに応じて、以下のような応答の1つを受け取ります。 @@ -604,16 +735,22 @@ dataTask.resume()`; ユーザーインポートジョブにエラーがある場合には、`GET`要求を[ジョブエラー詳細取得](/docs/ja-jp/api/management/v2#!/Jobs/get_errors)エンドポイントに行って、エラー詳細を取得することができます。必ず、`MGMT_API_ACCESS_TOKEN`および`JOB_ID`のプレースホルダーの値をそれぞれManagement APIのアクセストークンとユーザーインポートジョブIDに置き換えます。 -export const codeExample21 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/jobs/JOB_ID/errors' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ - --header 'content-type: application/json'`; -export const codeExample22 = `var client = new RestClient("https://{yourDomain}/api/v2/jobs/JOB_ID/errors"); + --header 'content-type: application/json' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/jobs/JOB_ID/errors"); var request = new RestRequest(Method.GET); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); -IRestResponse response = client.Execute(request);`; -export const codeExample23 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -638,12 +775,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample24 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/jobs/JOB_ID/errors") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/jobs/JOB_ID/errors") .header("content-type", "application/json") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") - .asString();`; -export const codeExample25 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -658,8 +799,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample26 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN" }; @@ -680,8 +823,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample27 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/jobs/JOB_ID/errors", @@ -706,8 +851,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample28 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -721,8 +868,10 @@ conn.request("GET", "/{yourDomain}/api/v2/jobs/JOB_ID/errors", headers=headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample29 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -737,8 +886,10 @@ request["content-type"] = 'application/json' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' response = http.request(request) -puts response.read_body`; -export const codeExample30 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -761,20 +912,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + 要求に成功すると、以下のような応答を受け取ります。`hash.value`などの機密フィールドは応答内でマスクされます。 diff --git a/main/docs/ja-jp/manage-users/user-search/retrieve-users-with-get-users-by-email-endpoint.mdx b/main/docs/ja-jp/manage-users/user-search/retrieve-users-with-get-users-by-email-endpoint.mdx index 6ebcf6884..bf3523db0 100644 --- a/main/docs/ja-jp/manage-users/user-search/retrieve-users-with-get-users-by-email-endpoint.mdx +++ b/main/docs/ja-jp/manage-users/user-search/retrieve-users-with-get-users-by-email-endpoint.mdx @@ -10,6 +10,7 @@ permalink: "retrieve-users-with-get-users-by-email-endpoint" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; [`GET /api/v2/users-by-email`エンドポイント](/docs/ja-jp/api/management/v2#!/Users_By_Email/get_users_by_email)を使うと、メールアドレスを使用してユーザーを検索できます。この検索では指定したメールアドレスとの完全一致を探し、小文字と大文字を区別します。 @@ -24,14 +25,20 @@ import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; 必要なスコープ:`read:users` -export const codeExample1 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/users-by-email?email=%7BuserEmailAddress%7D' \ - --header 'authorization: Bearer {yourMgmtApiAccessToken}'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/users-by-email?email=%7BuserEmailAddress%7D"); + --header 'authorization: Bearer {yourMgmtApiAccessToken}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users-by-email?email=%7BuserEmailAddress%7D"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer {yourMgmtApiAccessToken}"); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -55,11 +62,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/users-by-email?email=%7BuserEmailAddress%7D") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/users-by-email?email=%7BuserEmailAddress%7D") .header("authorization", "Bearer {yourMgmtApiAccessToken}") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -72,8 +83,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer {yourMgmtApiAccessToken}" }; @@ -93,8 +106,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users-by-email?email=%7BuserEmailAddress%7D", @@ -118,8 +133,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -130,8 +147,10 @@ conn.request("GET", "/{yourDomain}/api/v2/users-by-email?email=%7BuserEmailAddre res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -145,8 +164,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer {yourMgmtApiAccessToken}' response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer {yourMgmtApiAccessToken}"] @@ -166,20 +187,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ```json lines [ diff --git a/main/docs/ja-jp/manage-users/user-search/retrieve-users-with-get-users-by-id-endpoint.mdx b/main/docs/ja-jp/manage-users/user-search/retrieve-users-with-get-users-by-id-endpoint.mdx index 296772ed2..5736689d7 100644 --- a/main/docs/ja-jp/manage-users/user-search/retrieve-users-with-get-users-by-id-endpoint.mdx +++ b/main/docs/ja-jp/manage-users/user-search/retrieve-users-with-get-users-by-id-endpoint.mdx @@ -10,6 +10,7 @@ permalink: "retrieve-users-with-get-users-by-id-endpoint" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; [`GET /api/v2/users/{id}`エンドポイント](https://auth0.com/docs/api/management/v2#!/Users/get_users_by_id)を使うと、Auth0ユーザーIDを使用して特定のユーザーを取得できます。 @@ -26,14 +27,20 @@ import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; 必要なスコープ:`read:users` -export const codeExample1 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/users/%7BuserId%7D' \ - --header 'authorization: Bearer {yourMgmtApiAccessToken}'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/users/%7BuserId%7D"); + --header 'authorization: Bearer {yourMgmtApiAccessToken}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users/%7BuserId%7D"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer {yourMgmtApiAccessToken}"); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -57,11 +64,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/users/%7BuserId%7D") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/users/%7BuserId%7D") .header("authorization", "Bearer {yourMgmtApiAccessToken}") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -73,8 +84,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer {yourMgmtApiAccessToken}" }; @@ -94,8 +107,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users/%7BuserId%7D", @@ -119,8 +134,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -131,8 +148,10 @@ conn.request("GET", "/{yourDomain}/api/v2/users/%7BuserId%7D", headers=headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -146,8 +165,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer {yourMgmtApiAccessToken}' response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer {yourMgmtApiAccessToken}"] @@ -167,20 +188,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ```json lines { diff --git a/main/docs/ja-jp/manage-users/user-search/retrieve-users-with-get-users-endpoint.mdx b/main/docs/ja-jp/manage-users/user-search/retrieve-users-with-get-users-endpoint.mdx index 16fc7c0a6..ef8702530 100644 --- a/main/docs/ja-jp/manage-users/user-search/retrieve-users-with-get-users-endpoint.mdx +++ b/main/docs/ja-jp/manage-users/user-search/retrieve-users-with-get-users-endpoint.mdx @@ -10,6 +10,7 @@ permalink: "retrieve-users-with-get-users-endpoint" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; [`GET /api/v2/users`エンドポイント](/docs/ja-jp/api/management/v2#!/Users/get_users)を使うと、ユーザーのリストを取得できます。このエンドポイントを使用すると、次の操作を実行できます。 @@ -25,14 +26,20 @@ import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; たとえば、メールアドレスが`jane@exampleco.com`と完全一致するユーザーを検索するには、`q=email:"jane@exampleco.com"`を使用します。 -export const codeExample1 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/users?q=email%3A%22jane%40exampleco.com%22&search_engine=v3' \ - --header 'authorization: Bearer {yourMgmtApiAccessToken}'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/users?q=email%3A%22jane%40exampleco.com%22&search_engine=v3"); + --header 'authorization: Bearer {yourMgmtApiAccessToken}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users?q=email%3A%22jane%40exampleco.com%22&search_engine=v3"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer {yourMgmtApiAccessToken}"); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -56,11 +63,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/users?q=email%3A%22jane%40exampleco.com%22&search_engine=v3") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/users?q=email%3A%22jane%40exampleco.com%22&search_engine=v3") .header("authorization", "Bearer {yourMgmtApiAccessToken}") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -73,8 +84,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer {yourMgmtApiAccessToken}" }; @@ -94,8 +107,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users?q=email%3A%22jane%40exampleco.com%22&search_engine=v3", @@ -119,8 +134,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -131,8 +148,10 @@ conn.request("GET", "/{yourDomain}/api/v2/users?q=email%3A%22jane%40exampleco.co res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -146,8 +165,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer {yourMgmtApiAccessToken}' response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer {yourMgmtApiAccessToken}"] @@ -167,20 +188,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + 成功すると、次のような応答を受け取ります。 diff --git a/main/docs/ja-jp/manage-users/user-search/sort-search-results.mdx b/main/docs/ja-jp/manage-users/user-search/sort-search-results.mdx index 2b8d90b29..26c4d45ed 100644 --- a/main/docs/ja-jp/manage-users/user-search/sort-search-results.mdx +++ b/main/docs/ja-jp/manage-users/user-search/sort-search-results.mdx @@ -10,6 +10,7 @@ permalink: "sort-search-results" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; ユーザー検索結果を並べ替えるには、要求を行う際に`field:order`値を`sort`パラメーターに渡します。`field`は並べ替えるフィールドの名前で、昇順には`1`、降順には`-1`を設定することができます。 @@ -17,14 +18,20 @@ import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; たとえば、`created_at`フィールドでユーザーを昇順に並べ替えるには、`created_at:1`値を`sort`パラメータに渡します。 -export const codeExample1 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/users?q=logins_count%3A%5B100%20TO%20200%5D&sort=created_at%3A1&search_engine=v3' \ - --header 'authorization: Bearer {yourMgmtApiAccessToken}'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/users?q=logins_count%3A%5B100%20TO%20200%5D&sort=created_at%3A1&search_engine=v3"); + --header 'authorization: Bearer {yourMgmtApiAccessToken}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users?q=logins_count%3A%5B100%20TO%20200%5D&sort=created_at%3A1&search_engine=v3"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer {yourMgmtApiAccessToken}"); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -48,11 +55,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/users?q=logins_count%3A%5B100%20TO%20200%5D&sort=created_at%3A1&search_engine=v3") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/users?q=logins_count%3A%5B100%20TO%20200%5D&sort=created_at%3A1&search_engine=v3") .header("authorization", "Bearer {yourMgmtApiAccessToken}") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -65,8 +76,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer {yourMgmtApiAccessToken}" }; @@ -86,8 +99,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users?q=logins_count%3A%5B100%20TO%20200%5D&sort=created_at%3A1&search_engine=v3", @@ -111,8 +126,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -123,8 +140,10 @@ conn.request("GET", "/{yourDomain}/api/v2/users?q=logins_count%3A%5B100%20TO%202 res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -138,8 +157,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer {yourMgmtApiAccessToken}' response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer {yourMgmtApiAccessToken}"] @@ -159,19 +180,8 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + `sort`や他のパラメーターについては、[Management API Explorer](https://auth0.com/docs/api/management/v2#!/Users/get_users)のドキュメントをお読みください。 \ No newline at end of file diff --git a/main/docs/ja-jp/manage-users/user-search/user-search-query-syntax.mdx b/main/docs/ja-jp/manage-users/user-search/user-search-query-syntax.mdx index 803fe596a..9a7d7db7a 100644 --- a/main/docs/ja-jp/manage-users/user-search/user-search-query-syntax.mdx +++ b/main/docs/ja-jp/manage-users/user-search/user-search-query-syntax.mdx @@ -10,6 +10,7 @@ permalink: "user-search-query-syntax" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; @@ -112,14 +113,20 @@ import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; たとえば、`jane smith`という名前のユーザーを検索するには、`q=name:"jane smith"`を使用します。 -export const codeExample1 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/users?q=name%3A%22jane%20smith%22&search_engine=v3' \ - --header 'authorization: Bearer {yourMgmtApiAccessToken}'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/users?q=name%3A%22jane%20smith%22&search_engine=v3"); + --header 'authorization: Bearer {yourMgmtApiAccessToken}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users?q=name%3A%22jane%20smith%22&search_engine=v3"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer {yourMgmtApiAccessToken}"); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -143,11 +150,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/users?q=name%3A%22jane%20smith%22&search_engine=v3") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/users?q=name%3A%22jane%20smith%22&search_engine=v3") .header("authorization", "Bearer {yourMgmtApiAccessToken}") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -160,8 +171,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer {yourMgmtApiAccessToken}" }; @@ -181,8 +194,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users?q=name%3A%22jane%20smith%22&search_engine=v3", @@ -206,8 +221,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -218,8 +235,10 @@ conn.request("GET", "/{yourDomain}/api/v2/users?q=name%3A%22jane%20smith%22&sear res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -233,8 +252,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer {yourMgmtApiAccessToken}' response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer {yourMgmtApiAccessToken}"] @@ -254,20 +275,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ## ワイルドカード @@ -280,14 +290,20 @@ dataTask.resume()`; * `q=name:john*` は、 `john`で始まる名前のユーザーすべてを返します。 * サフィックスの照合の場合、リテラルは3文字以上である必要があります。たとえば、`name:*usa`は使用できますが、`name:*sa`は使用できません。 -export const codeExample11 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/users?q=name%3Ajohn*&search_engine=v3' \ - --header 'authorization: Bearer {yourMgmtApiAccessToken}'`; -export const codeExample12 = `var client = new RestClient("https://{yourDomain}/api/v2/users?q=name%3Ajohn\*&search_engine=v3"); + --header 'authorization: Bearer {yourMgmtApiAccessToken}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users?q=name%3Ajohn\*&search_engine=v3"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer {yourMgmtApiAccessToken}"); -IRestResponse response = client.Execute(request);`; -export const codeExample13 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -311,11 +327,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample14 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/users?q=name%3Ajohn*&search_engine=v3") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/users?q=name%3Ajohn*&search_engine=v3") .header("authorization", "Bearer {yourMgmtApiAccessToken}") - .asString();`; -export const codeExample15 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -328,8 +348,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample16 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer {yourMgmtApiAccessToken}" }; @@ -349,8 +371,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users?q=name%3Ajohn*&search_engine=v3", @@ -374,8 +398,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -386,8 +412,10 @@ conn.request("GET", "/{yourDomain}/api/v2/users?q=name%3Ajohn*&search_engine=v3" res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -401,8 +429,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer {yourMgmtApiAccessToken}' response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer {yourMgmtApiAccessToken}"] @@ -422,20 +452,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ## 範囲 @@ -446,14 +465,20 @@ dataTask.resume()`; * 中括弧と角括弧は同じ範囲の表現内で組み合わせることができます:`logins_count:[100 TO 200}` * ワイルドカードと組み合わせて範囲を使用します。たとえば、100回以上ログインしているユーザーを見つけるには、 `q=logins_count:{100 TO *]`を使用します。 -export const codeExample21 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/users?q=logins_count%3A%7B100%20TO%20*%5D&search_engine=v3' \ - --header 'authorization: Bearer {yourMgmtApiAccessToken}'`; -export const codeExample22 = `var client = new RestClient("https://{yourDomain}/api/v2/users?q=logins_count%3A%7B100%20TO%20\*%5D&search_engine=v3"); + --header 'authorization: Bearer {yourMgmtApiAccessToken}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users?q=logins_count%3A%7B100%20TO%20\*%5D&search_engine=v3"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer {yourMgmtApiAccessToken}"); -IRestResponse response = client.Execute(request);`; -export const codeExample23 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -477,11 +502,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample24 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/users?q=logins_count%3A%7B100%20TO%20*%5D&search_engine=v3") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/users?q=logins_count%3A%7B100%20TO%20*%5D&search_engine=v3") .header("authorization", "Bearer {yourMgmtApiAccessToken}") - .asString();`; -export const codeExample25 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -494,8 +523,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample26 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer {yourMgmtApiAccessToken}" }; @@ -515,8 +546,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample27 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users?q=logins_count%3A%7B100%20TO%20*%5D&search_engine=v3", @@ -540,8 +573,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample28 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -552,8 +587,10 @@ conn.request("GET", "/{yourDomain}/api/v2/users?q=logins_count%3A%7B100%20TO%20* res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample29 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -567,8 +604,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer {yourMgmtApiAccessToken}' response = http.request(request) -puts response.read_body`; -export const codeExample30 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer {yourMgmtApiAccessToken}"] @@ -588,20 +627,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ## 検索可能なプロファイル属性の例 diff --git a/main/docs/ja-jp/manage-users/user-search/view-search-results-by-page.mdx b/main/docs/ja-jp/manage-users/user-search/view-search-results-by-page.mdx index ca0926294..2afa6b165 100644 --- a/main/docs/ja-jp/manage-users/user-search/view-search-results-by-page.mdx +++ b/main/docs/ja-jp/manage-users/user-search/view-search-results-by-page.mdx @@ -10,6 +10,7 @@ permalink: "view-search-results-by-page" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; ユーザーの検索結果をページで区切るには、要求で`page`、`per_page`、`include_totals`のパラメーターを使用します。 @@ -37,14 +38,20 @@ import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; ## 要求例 -export const codeExample1 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/users?q=logins_count%3A%5B100%20TO%20200%5D&page=2&per_page=10&include_totals=true&search_engine=v3' \ - --header 'authorization: Bearer {yourMgmtApiAccessToken}'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/users?q=logins_count%3A%5B100%20TO%20200%5D&page=2&per_page=10&include_totals=true&search_engine=v3"); + --header 'authorization: Bearer {yourMgmtApiAccessToken}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users?q=logins_count%3A%5B100%20TO%20200%5D&page=2&per_page=10&include_totals=true&search_engine=v3"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer {yourMgmtApiAccessToken}"); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -68,11 +75,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/users?q=logins_count%3A%5B100%20TO%20200%5D&page=2&per_page=10&include_totals=true&search_engine=v3") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/users?q=logins_count%3A%5B100%20TO%20200%5D&page=2&per_page=10&include_totals=true&search_engine=v3") .header("authorization", "Bearer {yourMgmtApiAccessToken}") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -91,8 +102,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer {yourMgmtApiAccessToken}" }; @@ -112,8 +125,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users?q=logins_count%3A%5B100%20TO%20200%5D&page=2&per_page=10&include_totals=true&search_engine=v3", @@ -137,8 +152,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -149,8 +166,10 @@ conn.request("GET", "/{yourDomain}/api/v2/users?q=logins_count%3A%5B100%20TO%202 res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -164,8 +183,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer {yourMgmtApiAccessToken}' response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer {yourMgmtApiAccessToken}"] @@ -185,20 +206,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ## 応答例 diff --git a/main/docs/ja-jp/quickstart/backend/aspnet-core-webapi/interactive.mdx b/main/docs/ja-jp/quickstart/backend/aspnet-core-webapi/interactive.mdx index 458a8f1c5..05c8ec7e0 100644 --- a/main/docs/ja-jp/quickstart/backend/aspnet-core-webapi/interactive.mdx +++ b/main/docs/ja-jp/quickstart/backend/aspnet-core-webapi/interactive.mdx @@ -1,490 +1,492 @@ ---- -title: "ASP.NET Core Web APIアプリケーションに認可を追加する" -permalink: "interactive" -'description': "このチュートリアルは、標準のJWTミドルウェアを使ってASP.NET Core Web APIアプリケーションに認可を追加する方法を説明します。" -'og:title': "ASP.NET Core Web APIアプリケーションに認可を追加する" -'og:description': "このチュートリアルは、標準のJWTミドルウェアを使ってASP.NET Core Web APIアプリケーションに認可を追加する方法を説明します。" -'og:image': "/docs/media/platforms/asp.png" -'twitter:title': "ASP.NET Core Web APIアプリケーションに認可を追加する" -'twitter:description': "このチュートリアルは、標準のJWTミドルウェアを使ってASP.NET Core Web APIアプリケーションに認可を追加する方法を説明します。" -sidebarTitle: ASP.NET Core Web API ---- - -import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; -import { LoggedInForm } from "/snippets/Login.jsx"; -import Appsettings from "/snippets/quickstart/backend/aspnet-core-webapi/appsettings.json.mdx"; -import Program from "/snippets/quickstart/backend/aspnet-core-webapi/Program.cs.mdx"; -import Hasscopehandler from "/snippets/quickstart/backend/aspnet-core-webapi/HasScopeHandler.cs.mdx"; -import Hasscoperequirement from "/snippets/quickstart/backend/aspnet-core-webapi/HasScopeRequirement.cs.mdx"; -import Apicontroller from "/snippets/quickstart/backend/aspnet-core-webapi/ApiController.cs.mdx"; - -export const sections = [ - { id: "アクセス許可を定義する", title: "アクセス許可を定義する" }, - { id: "依存関係をインストールする", title: "依存関係をインストールする" }, - { id: "ミドルウェアを構成する", title: "ミドルウェアを構成する" }, - { id: "スコープを検証する", title: "スコープを検証する" }, - { id: "apiエンドポイントを保護する", title: "APIエンドポイントを保護する" }, - { id: "apiを呼び出す", title: "APIを呼び出す" } -] - - - - Auth0を使用すると、アプリケーションに認証を追加して、アプリケーションの種類にかかわらず、ユーザープロファイル情報に手軽にアクセスすることができます。このガイドは、新規または既存のASP.NET Web APIアプリケーションに`Microsoft.AspNetCore.Authentication.JwtBearer`パッケージを使ってAuth0を統合する方法を説明します。 - - Auth0 DashboardでAPIをまだ作成していない場合は、対話型のセレクターを使ってAuth0 APIを新規作成します。そうでない場合は、統合したいプロジェクトを表す既存のAPIを選択することができます。 - - または、Auth0 Dashboardを使って初めてAPIをセットアップする方法を使用の開始ガイドで確認することもできます。 - - Auth0にあるAPIはそれぞれAPI識別子を使って構成され、アプリケーションのコードはAPI識別子をオーディエンスとしてアクセストークンを検証します。 - - - **Auth0を初めてご利用ですか?** Auth0の仕組みと、OAuth 2.0フレームワークを用いたAPI認証と認可の実装について説明します。 - - -
    - アクセス許可は、ユーザーの代わりに、提供されたアクセストークンを使ってどのようにしてリソースにアクセスできるのかを定義できるようにします。たとえば、ユーザーがマネージャーアクセスレベルを持つ場合には、`messages`リソースに対して読み取りアクセスを付与し、管理者アクセスレベルを持つ場合には、書き込みアクセスを付与することができます。 - - Auth0 Dashboardの[[API]](https://manage.auth0.com/#/apis)セクションにある**[Permissions(権限)]** ビューで使用可能なアクセス許可を定義することができます。以下の例では`read:messages`スコープを使用します。 - - ![[Auth0 Dashboard]>[Applications(アプリケーション)]>[APIs]>[Specific API(特定のAPI]>[Permissions(権限)]タブ](/docs/images/ja-jp/cdy7uua7fh8z/1s3Yp5zqJiKiSWqbPSezNO/acef814282795bef6921535f044f96e9/Quickstarts_API.png) -
    - -
    - アプリケーションがアクセストークンを検証できるようにするには、`Microsoft.AspNetCore.Authentication.JwtBearer` NuGetパッケージへの参照を追加します。 - - ``` - Install-Package Microsoft.AspNetCore.Authentication.JwtBearer - ``` -
    - -
    - アプリケーションの`Program.cs`ファイルを構成して、認証ミドルウェアをセットアップします: - - 1. `AddAuthentication`メソッドを呼び出して、認証サービスを登録します。`JwtBearerDefaults.AuthenticationScheme`をデフォルトのスキームとして構成します。 - 2. `AddJwtBearer`メソッドを呼び出して、JWTベアラー認証スキームを登録します。Auth0ドメインをオーソリティ、Auth0 API識別子をオーディエンスとして構成し、Auth0ドメインとAPI識別子がアプリケーションの**appsettings.json** ファイル内で設定されていることを確認します。 - - - 場合によっては、アクセストークンに`sub`クレームが含まれないことがあります。この場合には、`User.Identity.Name`が`null`になります。別のクレームを`User.Identity.Name`にマッピングしたい場合には、それを`AddJwtBearer()`への呼び出しの中で`options.TokenValidationParameters`に追加します。 - - 3. `UseAuthentication`メソッドと`UseAuthorization`メソッドの呼び出しを`var app = builder.Build();`メソッドの下に追加して、ミドルウェアパイプラインに認証ミドルウェアと認可ミドルウェアを追加します。 -
    - -
    - アクセストークンに正しいスコープが含まれていることを確認するには、ASP.NET Coreの[ポリシーベースの認可](https://docs.microsoft.com/en-us/aspnet/core/security/authorization/policies)を使用します。 - - 1. `HasScopeRequirement`という名前の新しい認可要求を作成します。これは、Auth0テナント発行の`scope`クレームが存在するかを確認し、存在する場合には、要求されたスコープがそのクレームに含まれているかを確認します。 - 2. `Program.cs`ファイルにある`var builder = WebApplication.CreateBuilder(args);`メソッドの下に、`app.AddAuthorization`メソッドへの呼び出しを追加します。 - 3. スコープのポリシーを追加するには、各スコープに`AddPolicy`を呼び出します。 - 4. `HasScopeHandler`クラスのシングルトンを登録します。 -
    - -
    - JWTミドルウェアは、ASP.NET Coreの標準の[認証](https://docs.microsoft.com/en-us/aspnet/core/security/authentication/)および[認可](https://docs.microsoft.com/en-us/aspnet/core/security/authorization/)メカニズムと統合します。 - - エンドポイントのセキュリティを保護するには、`[Authorize]`属性をコントローラーのアクション(すべてのアクションのセキュリティを保護するには、コントローラー)に追加します。 - - 特定のスコープが必要なエンドポイントのセキュリティを保護するには、正しいスコープが`access_token`に存在することを確認します。そのためには、`Authorize`属性を`Scoped`アクションに追加し、`read:messages`を`policy`パラメーターとして渡します。 -
    - -
    - APIの呼び出し方は、開発しているアプリケーションの種類と使用しているフレームワークに依存します。詳細については、該当するアプリケーションのクイックスタートをお読みください。 - - - [シングルページアプリケーション](/docs/ja-jp/quickstart/spa) - - [モバイル / ネイティブアプリケーション](/docs/ja-jp/quickstart/native) - - ### アクセストークン取得する - - 開発しているアプリケーションの種類や使用しているフレームワークが何であったとしても、APIを呼び出すにはアクセストークンが必要です。 - - シングルページアプリケーション(SPA)またはネイティブアプリケーションからAPIを呼び出すと、認可フローの完了後にアクセストークンを受け取ります。 - - コマンドラインツールや他のサービスなど、ユーザーが資格情報を入力しないものからAPIを呼び出す際には、[OAuthクライアントの資格情報フロー](https://auth0.com/docs/api/authentication#client-credentials)を使用します。そのためには、[マシンツーマシンアプリケーション](https://manage.auth0.com/#/applications)を登録し、要求内で以下の値を渡します。 - - - **クライアントID** を`client_id`パラメーターとして渡す。 - - **クライアントシークレット** を`client_secret`パラメーターとして渡す。 - - **API 識別子** (このクイックスタートで以前にミドルウェアの構成に使用したのと同じ値)を`audience`パラメーターとして渡す。 - - - マシンツーマシンアプリケーションにクライアントIDとクライアントシークレットを取得する詳細については、アプリケーションの設定をお読みください。 - - - **要求例** - - - ```sh cURL lines - curl --request post \ - --url 'https://dev-gja8kxz4ndtex3rq.us.auth0.com/oauth/token' \ - --header 'content-type: application/x-www-form-urlencoded' - ``` - - ```cs C# lines - var client = new RestClient("https://dev-gja8kxz4ndtex3rq.us.auth0.com/oauth/token"); - var request = new RestRequest(Method.POST); - request.AddHeader("content-type", "application/x-www-form-urlencoded"); - IRestResponse response = client.Execute(request); - ``` - - ```go Go lines - package main - import ( - "fmt" - "net/http" - "io/ioutil" - ) - func main() { - url := "https://dev-gja8kxz4ndtex3rq.us.auth0.com/oauth/token" - req, _ := http.NewRequest("post", url, nil) - req.Header.Add("content-type", "application/x-www-form-urlencoded") - res, _ := http.DefaultClient.Do(req) - defer res.Body.Close() - body, _ := ioutil.ReadAll(res.Body) - fmt.Println(res) - fmt.Println(string(body)) - } - ``` - - ```java Java lines - HttpResponse response = Unirest.post("https://dev-gja8kxz4ndtex3rq.us.auth0.com/oauth/token") - .header("content-type", "application/x-www-form-urlencoded") - .asString(); - ``` - - ```js Node.JS lines - var axios = require("axios").default; - var options = { - method: 'post', - url: 'https://dev-gja8kxz4ndtex3rq.us.auth0.com/oauth/token', - headers: {'content-type': 'application/x-www-form-urlencoded'} - }; - axios.request(options).then(function (response) { - console.log(response.data); - }).catch(function (error) { - console.error(error); - }); - ``` - - ```obj-c Obj-C lines - #import - NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; - NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://dev-gja8kxz4ndtex3rq.us.auth0.com/oauth/token"] - cachePolicy:NSURLRequestUseProtocolCachePolicy - - timeoutInterval:10.0]; - - [request setHTTPMethod:@"post"]; - [request setAllHTTPHeaderFields:headers]; - NSURLSession *session = [NSURLSession sharedSession]; - NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request - completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { - - if (error) { - - NSLog(@"%@", error); - - } else { - - NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response; - - NSLog(@"%@", httpResponse); - - } - - }]; - - [dataTask resume]; - ``` - - ```php PHP lines - $curl = curl_init(); - curl_setopt_array($curl, [ - CURLOPT_URL => "https://dev-gja8kxz4ndtex3rq.us.auth0.com/oauth/token", - CURLOPT_RETURNTRANSFER => true, - CURLOPT_ENCODING => "", - CURLOPT_MAXREDIRS => 10, - CURLOPT_TIMEOUT => 30, - CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, - CURLOPT_CUSTOMREQUEST => "post", - CURLOPT_HTTPHEADER => [ - "content-type: application/x-www-form-urlencoded" - - ], - ]); - $response = curl_exec($curl); - $err = curl_error($curl); - curl_close($curl); - if ($err) { - echo "cURL Error #:" . $err; - } else { - echo $response; - } - ``` - - ```python Python lines - import http.client - conn = http.client.HTTPSConnection("") - headers = { 'content-type': "application/x-www-form-urlencoded" } - conn.request("post", "/dev-gja8kxz4ndtex3rq.us.auth0.com/oauth/token", headers=headers) - res = conn.getresponse() - data = res.read() - print(data.decode("utf-8")) - ``` - - ```rb Ruby lines - require 'uri' - require 'net/http' - require 'openssl' - url = URI("https://dev-gja8kxz4ndtex3rq.us.auth0.com/oauth/token") - http = Net::HTTP.new(url.host, url.port) - http.use_ssl = true - http.verify_mode = OpenSSL::SSL::VERIFY_NONE - request = Net::HTTP::Post.new(url) - request["content-type"] = 'application/x-www-form-urlencoded' - response = http.request(request) - puts response.read_body - ``` - - ```swift Swift lines - require 'uri' - require 'net/http' - require 'openssl' - url = URI("https://dev-gja8kxz4ndtex3rq.us.auth0.com/oauth/token") - http = Net::HTTP.new(url.host, url.port) - http.use_ssl = true - http.verify_mode = OpenSSL::SSL::VERIFY_NONE - request = Net::HTTP::Post.new(url) - request["content-type"] = 'application/x-www-form-urlencoded' - response = http.request(request) - puts response.read_body - ``` - - - - - ### セキュリティ保護されたエンドポイントを呼び出す - - 取得したアクセストークン使用すると、セキュリティ保護されたAPIエンドポイントを呼び出すことができます。セキュリティ保護されたエンドポイントを呼び出す際には、アクセストークンをベアラートークンとして要求の**認可** ヘッダーに含める必要があります。たとえば、`/api/private`エンドポイントに要求を送信することができます: - - - ```sh cURL lines - curl --request get \ - --url http://localhost:3010/api/private \ - --header 'authorization: Bearer YOUR_ACCESS_TOKEN' - ``` - - ```cs C# lines - var client = new RestClient("http://localhost:3010/api/private"); - var request = new RestRequest(Method.GET); - request.AddHeader("authorization", "Bearer YOUR_ACCESS_TOKEN"); - IRestResponse response = client.Execute(request); - ``` - - ```go Go lines - package main - import ( - "fmt" - "net/http" - "io/ioutil" - ) - func main() { - url := "http://localhost:3010/api/private" - req, _ := http.NewRequest("get", url, nil) - req.Header.Add("authorization", "Bearer YOUR_ACCESS_TOKEN") - res, _ := http.DefaultClient.Do(req) - defer res.Body.Close() - body, _ := ioutil.ReadAll(res.Body) - fmt.Println(res) - fmt.Println(string(body)) - } - ``` - - ```java Java lines - HttpResponse response = Unirest.get("http://localhost:3010/api/private") - .header("authorization", "Bearer YOUR_ACCESS_TOKEN") - .asString(); - ``` - - ```js Node.JS lines - var axios = require("axios").default; - var options = { - method: 'get', - url: 'http://localhost:3010/api/private', - headers: {authorization: 'Bearer YOUR_ACCESS_TOKEN'} - }; - axios.request(options).then(function (response) { - console.log(response.data); - }).catch(function (error) { - console.error(error); - }); - ``` - - ```obj-c Obj-C lines - #import - NSDictionary *headers = @{ @"authorization": @"Bearer YOUR_ACCESS_TOKEN" }; - NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://localhost:3010/api/private"] - cachePolicy:NSURLRequestUseProtocolCachePolicy - - timeoutInterval:10.0]; - - [request setHTTPMethod:@"get"]; - [request setAllHTTPHeaderFields:headers]; - NSURLSession *session = [NSURLSession sharedSession]; - NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request - completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { - - if (error) { - - NSLog(@"%@", error); - - } else { - - NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response; - - NSLog(@"%@", httpResponse); - - } - - }]; - - [dataTask resume]; - ``` - - ```php PHP lines - $curl = curl_init(); - curl_setopt_array($curl, [ - CURLOPT_PORT => "3010", - CURLOPT_URL => "http://localhost:3010/api/private", - CURLOPT_RETURNTRANSFER => true, - CURLOPT_ENCODING => "", - CURLOPT_MAXREDIRS => 10, - CURLOPT_TIMEOUT => 30, - CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, - CURLOPT_CUSTOMREQUEST => "get", - CURLOPT_HTTPHEADER => [ - "authorization: Bearer YOUR_ACCESS_TOKEN" - - ], - ]); - $response = curl_exec($curl); - $err = curl_error($curl); - curl_close($curl); - if ($err) { - echo "cURL Error #:" . $err; - } else { - echo $response; - } - ``` - - ```python Python lines - import http.client - conn = http.client.HTTPConnection("localhost:3010") - headers = { 'authorization': "Bearer YOUR_ACCESS_TOKEN" } - conn.request("get", "/api/private", headers=headers) - res = conn.getresponse() - data = res.read() - print(data.decode("utf-8")) - ``` - - ```rb Ruby lines - require 'uri' - require 'net/http' - url = URI("http://localhost:3010/api/private") - http = Net::HTTP.new(url.host, url.port) - request = Net::HTTP::Get.new(url) - request["authorization"] = 'Bearer YOUR_ACCESS_TOKEN' - response = http.request(request) - puts response.read_body - ``` - - ```swift Swift lines - import Foundation - let headers = ["authorization": "Bearer YOUR_ACCESS_TOKEN"] - let request = NSMutableURLRequest(url: NSURL(string: "http://localhost:3010/api/private")! as URL, - cachePolicy: .useProtocolCachePolicy, - - timeoutInterval: 10.0) - - request.httpMethod = "get" - request.allHTTPHeaderFields = headers - let session = URLSession.shared - let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in - if (error != nil) { - print(error) - - } else { - let httpResponse = response as? HTTPURLResponse - - print(httpResponse) - - } - }) - dataTask.resume() - ``` - - - - `/api/private-scoped`エンドポイントも同様の方法で呼び出しますが、APIのアクセス許可が正しく構成され、アクセストークンに`read:messages`スコープがあることを確認してください。 - - - ##### チェックポイント - /api/privateと/api/private-scopedエンドポイントを呼び出すことができるはずです。 - アプリケーションを実行して次の点を確認します: - GET /api/privateが認証された要求に使用できる。 - GET /api/private-scopedがread:messagesスコープが付与されたアクセストークンを含む認証された要求に使用できる。 - -
    - - ## 次のステップ - - 成功です!ここまで来れば、アプリケーションにログイン、ログアウト、ユーザープロファイル情報が備わっているはずです。 - - これでクイックスタートチュートリアルは終了ですが、機能はまだまだたくさんあります。Auth0でできることについて詳しくは、以下をご覧ください。 - - * [Auth0 Dashboard](https://manage.auth0.com/#) - Auth0のテナントやアプリケーションを構成して管理する方法について説明します - * [Auth0 Marketplace](https://marketplace.auth0.com/) - Auth0の機能性を拡張できる各種の統合を見つけられます -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    +--- +title: "ASP.NET Core Web APIアプリケーションに認可を追加する" +permalink: "interactive" +'description': "このチュートリアルは、標準のJWTミドルウェアを使ってASP.NET Core Web APIアプリケーションに認可を追加する方法を説明します。" +'og:title': "ASP.NET Core Web APIアプリケーションに認可を追加する" +'og:description': "このチュートリアルは、標準のJWTミドルウェアを使ってASP.NET Core Web APIアプリケーションに認可を追加する方法を説明します。" +'og:image': "/docs/media/platforms/asp.png" +'twitter:title': "ASP.NET Core Web APIアプリケーションに認可を追加する" +'twitter:description': "このチュートリアルは、標準のJWTミドルウェアを使ってASP.NET Core Web APIアプリケーションに認可を追加する方法を説明します。" +sidebarTitle: ASP.NET Core Web API +--- + +import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; +import { LoggedInForm } from "/snippets/Login.jsx"; +import Appsettings from "/snippets/quickstart/backend/aspnet-core-webapi/appsettings.json.mdx"; +import Program from "/snippets/quickstart/backend/aspnet-core-webapi/Program.cs.mdx"; +import Hasscopehandler from "/snippets/quickstart/backend/aspnet-core-webapi/HasScopeHandler.cs.mdx"; +import Hasscoperequirement from "/snippets/quickstart/backend/aspnet-core-webapi/HasScopeRequirement.cs.mdx"; +import Apicontroller from "/snippets/quickstart/backend/aspnet-core-webapi/ApiController.cs.mdx"; + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + +export const sections = [ + { id: "アクセス許可を定義する", title: "アクセス許可を定義する" }, + { id: "依存関係をインストールする", title: "依存関係をインストールする" }, + { id: "ミドルウェアを構成する", title: "ミドルウェアを構成する" }, + { id: "スコープを検証する", title: "スコープを検証する" }, + { id: "apiエンドポイントを保護する", title: "APIエンドポイントを保護する" }, + { id: "apiを呼び出す", title: "APIを呼び出す" } +] + + + + Auth0を使用すると、アプリケーションに認証を追加して、アプリケーションの種類にかかわらず、ユーザープロファイル情報に手軽にアクセスすることができます。このガイドは、新規または既存のASP.NET Web APIアプリケーションに`Microsoft.AspNetCore.Authentication.JwtBearer`パッケージを使ってAuth0を統合する方法を説明します。 + + Auth0 DashboardでAPIをまだ作成していない場合は、対話型のセレクターを使ってAuth0 APIを新規作成します。そうでない場合は、統合したいプロジェクトを表す既存のAPIを選択することができます。 + + または、Auth0 Dashboardを使って初めてAPIをセットアップする方法を使用の開始ガイドで確認することもできます。 + + Auth0にあるAPIはそれぞれAPI識別子を使って構成され、アプリケーションのコードはAPI識別子をオーディエンスとしてアクセストークンを検証します。 + + + **Auth0を初めてご利用ですか?** Auth0の仕組みと、OAuth 2.0フレームワークを用いたAPI認証と認可の実装について説明します。 + + +
    + アクセス許可は、ユーザーの代わりに、提供されたアクセストークンを使ってどのようにしてリソースにアクセスできるのかを定義できるようにします。たとえば、ユーザーがマネージャーアクセスレベルを持つ場合には、`messages`リソースに対して読み取りアクセスを付与し、管理者アクセスレベルを持つ場合には、書き込みアクセスを付与することができます。 + + Auth0 Dashboardの[[API]](https://manage.auth0.com/#/apis)セクションにある**[Permissions(権限)]** ビューで使用可能なアクセス許可を定義することができます。以下の例では`read:messages`スコープを使用します。 + + ![[Auth0 Dashboard]>[Applications(アプリケーション)]>[APIs]>[Specific API(特定のAPI]>[Permissions(権限)]タブ](/docs/images/ja-jp/cdy7uua7fh8z/1s3Yp5zqJiKiSWqbPSezNO/acef814282795bef6921535f044f96e9/Quickstarts_API.png) +
    + +
    + アプリケーションがアクセストークンを検証できるようにするには、`Microsoft.AspNetCore.Authentication.JwtBearer` NuGetパッケージへの参照を追加します。 + + ``` + Install-Package Microsoft.AspNetCore.Authentication.JwtBearer + ``` +
    + +
    + アプリケーションの`Program.cs`ファイルを構成して、認証ミドルウェアをセットアップします: + + 1. `AddAuthentication`メソッドを呼び出して、認証サービスを登録します。`JwtBearerDefaults.AuthenticationScheme`をデフォルトのスキームとして構成します。 + 2. `AddJwtBearer`メソッドを呼び出して、JWTベアラー認証スキームを登録します。Auth0ドメインをオーソリティ、Auth0 API識別子をオーディエンスとして構成し、Auth0ドメインとAPI識別子がアプリケーションの**appsettings.json** ファイル内で設定されていることを確認します。 + + + 場合によっては、アクセストークンに`sub`クレームが含まれないことがあります。この場合には、`User.Identity.Name`が`null`になります。別のクレームを`User.Identity.Name`にマッピングしたい場合には、それを`AddJwtBearer()`への呼び出しの中で`options.TokenValidationParameters`に追加します。 + + 3. `UseAuthentication`メソッドと`UseAuthorization`メソッドの呼び出しを`var app = builder.Build();`メソッドの下に追加して、ミドルウェアパイプラインに認証ミドルウェアと認可ミドルウェアを追加します。 +
    + +
    + アクセストークンに正しいスコープが含まれていることを確認するには、ASP.NET Coreの[ポリシーベースの認可](https://docs.microsoft.com/en-us/aspnet/core/security/authorization/policies)を使用します。 + + 1. `HasScopeRequirement`という名前の新しい認可要求を作成します。これは、Auth0テナント発行の`scope`クレームが存在するかを確認し、存在する場合には、要求されたスコープがそのクレームに含まれているかを確認します。 + 2. `Program.cs`ファイルにある`var builder = WebApplication.CreateBuilder(args);`メソッドの下に、`app.AddAuthorization`メソッドへの呼び出しを追加します。 + 3. スコープのポリシーを追加するには、各スコープに`AddPolicy`を呼び出します。 + 4. `HasScopeHandler`クラスのシングルトンを登録します。 +
    + +
    + JWTミドルウェアは、ASP.NET Coreの標準の[認証](https://docs.microsoft.com/en-us/aspnet/core/security/authentication/)および[認可](https://docs.microsoft.com/en-us/aspnet/core/security/authorization/)メカニズムと統合します。 + + エンドポイントのセキュリティを保護するには、`[Authorize]`属性をコントローラーのアクション(すべてのアクションのセキュリティを保護するには、コントローラー)に追加します。 + + 特定のスコープが必要なエンドポイントのセキュリティを保護するには、正しいスコープが`access_token`に存在することを確認します。そのためには、`Authorize`属性を`Scoped`アクションに追加し、`read:messages`を`policy`パラメーターとして渡します。 +
    + +
    + APIの呼び出し方は、開発しているアプリケーションの種類と使用しているフレームワークに依存します。詳細については、該当するアプリケーションのクイックスタートをお読みください。 + + - [シングルページアプリケーション](/docs/ja-jp/quickstart/spa) + - [モバイル / ネイティブアプリケーション](/docs/ja-jp/quickstart/native) + + ### アクセストークン取得する + + 開発しているアプリケーションの種類や使用しているフレームワークが何であったとしても、APIを呼び出すにはアクセストークンが必要です。 + + シングルページアプリケーション(SPA)またはネイティブアプリケーションからAPIを呼び出すと、認可フローの完了後にアクセストークンを受け取ります。 + + コマンドラインツールや他のサービスなど、ユーザーが資格情報を入力しないものからAPIを呼び出す際には、[OAuthクライアントの資格情報フロー](https://auth0.com/docs/api/authentication#client-credentials)を使用します。そのためには、[マシンツーマシンアプリケーション](https://manage.auth0.com/#/applications)を登録し、要求内で以下の値を渡します。 + + - **クライアントID** を`client_id`パラメーターとして渡す。 + - **クライアントシークレット** を`client_secret`パラメーターとして渡す。 + - **API 識別子** (このクイックスタートで以前にミドルウェアの構成に使用したのと同じ値)を`audience`パラメーターとして渡す。 + + + マシンツーマシンアプリケーションにクライアントIDとクライアントシークレットを取得する詳細については、アプリケーションの設定をお読みください。 + + + **要求例** + + + ```sh cURL lines + curl --request post \ + --url 'https://dev-gja8kxz4ndtex3rq.us.auth0.com/oauth/token' \ + --header 'content-type: application/x-www-form-urlencoded' + ``` + + ```cs C# lines + var client = new RestClient("https://dev-gja8kxz4ndtex3rq.us.auth0.com/oauth/token"); + var request = new RestRequest(Method.POST); + request.AddHeader("content-type", "application/x-www-form-urlencoded"); + IRestResponse response = client.Execute(request); + ``` + + ```go Go lines + package main + import ( + "fmt" + "net/http" + "io/ioutil" + ) + func main() { + url := "https://dev-gja8kxz4ndtex3rq.us.auth0.com/oauth/token" + req, _ := http.NewRequest("post", url, nil) + req.Header.Add("content-type", "application/x-www-form-urlencoded") + res, _ := http.DefaultClient.Do(req) + defer res.Body.Close() + body, _ := ioutil.ReadAll(res.Body) + fmt.Println(res) + fmt.Println(string(body)) + } + ``` + + ```java Java lines + HttpResponse response = Unirest.post("https://dev-gja8kxz4ndtex3rq.us.auth0.com/oauth/token") + .header("content-type", "application/x-www-form-urlencoded") + .asString(); + ``` + + ```js Node.JS lines + var axios = require("axios").default; + var options = { + method: 'post', + url: 'https://dev-gja8kxz4ndtex3rq.us.auth0.com/oauth/token', + headers: {'content-type': 'application/x-www-form-urlencoded'} + }; + axios.request(options).then(function (response) { + console.log(response.data); + }).catch(function (error) { + console.error(error); + }); + ``` + + ```obj-c Obj-C lines + #import + NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; + NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://dev-gja8kxz4ndtex3rq.us.auth0.com/oauth/token"] + cachePolicy:NSURLRequestUseProtocolCachePolicy + + timeoutInterval:10.0]; + + [request setHTTPMethod:@"post"]; + [request setAllHTTPHeaderFields:headers]; + NSURLSession *session = [NSURLSession sharedSession]; + NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request + completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { + + if (error) { + + NSLog(@"%@", error); + + } else { + + NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response; + + NSLog(@"%@", httpResponse); + + } + + }]; + + [dataTask resume]; + ``` + + ```php PHP lines + $curl = curl_init(); + curl_setopt_array($curl, [ + CURLOPT_URL => "https://dev-gja8kxz4ndtex3rq.us.auth0.com/oauth/token", + CURLOPT_RETURNTRANSFER => true, + CURLOPT_ENCODING => "", + CURLOPT_MAXREDIRS => 10, + CURLOPT_TIMEOUT => 30, + CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, + CURLOPT_CUSTOMREQUEST => "post", + CURLOPT_HTTPHEADER => [ + "content-type: application/x-www-form-urlencoded" + + ], + ]); + $response = curl_exec($curl); + $err = curl_error($curl); + curl_close($curl); + if ($err) { + echo "cURL Error #:" . $err; + } else { + echo $response; + } + ``` + + ```python Python lines + import http.client + conn = http.client.HTTPSConnection("") + headers = { 'content-type': "application/x-www-form-urlencoded" } + conn.request("post", "/dev-gja8kxz4ndtex3rq.us.auth0.com/oauth/token", headers=headers) + res = conn.getresponse() + data = res.read() + print(data.decode("utf-8")) + ``` + + ```rb Ruby lines + require 'uri' + require 'net/http' + require 'openssl' + url = URI("https://dev-gja8kxz4ndtex3rq.us.auth0.com/oauth/token") + http = Net::HTTP.new(url.host, url.port) + http.use_ssl = true + http.verify_mode = OpenSSL::SSL::VERIFY_NONE + request = Net::HTTP::Post.new(url) + request["content-type"] = 'application/x-www-form-urlencoded' + response = http.request(request) + puts response.read_body + ``` + + ```swift Swift lines + require 'uri' + require 'net/http' + require 'openssl' + url = URI("https://dev-gja8kxz4ndtex3rq.us.auth0.com/oauth/token") + http = Net::HTTP.new(url.host, url.port) + http.use_ssl = true + http.verify_mode = OpenSSL::SSL::VERIFY_NONE + request = Net::HTTP::Post.new(url) + request["content-type"] = 'application/x-www-form-urlencoded' + response = http.request(request) + puts response.read_body + ``` + + + + + ### セキュリティ保護されたエンドポイントを呼び出す + + 取得したアクセストークン使用すると、セキュリティ保護されたAPIエンドポイントを呼び出すことができます。セキュリティ保護されたエンドポイントを呼び出す際には、アクセストークンをベアラートークンとして要求の**認可** ヘッダーに含める必要があります。たとえば、`/api/private`エンドポイントに要求を送信することができます: + + + ```sh cURL lines + curl --request get \ + --url http://localhost:3010/api/private \ + --header 'authorization: Bearer YOUR_ACCESS_TOKEN' + ``` + + ```cs C# lines + var client = new RestClient("http://localhost:3010/api/private"); + var request = new RestRequest(Method.GET); + request.AddHeader("authorization", "Bearer YOUR_ACCESS_TOKEN"); + IRestResponse response = client.Execute(request); + ``` + + ```go Go lines + package main + import ( + "fmt" + "net/http" + "io/ioutil" + ) + func main() { + url := "http://localhost:3010/api/private" + req, _ := http.NewRequest("get", url, nil) + req.Header.Add("authorization", "Bearer YOUR_ACCESS_TOKEN") + res, _ := http.DefaultClient.Do(req) + defer res.Body.Close() + body, _ := ioutil.ReadAll(res.Body) + fmt.Println(res) + fmt.Println(string(body)) + } + ``` + + ```java Java lines + HttpResponse response = Unirest.get("http://localhost:3010/api/private") + .header("authorization", "Bearer YOUR_ACCESS_TOKEN") + .asString(); + ``` + + ```js Node.JS lines + var axios = require("axios").default; + var options = { + method: 'get', + url: 'http://localhost:3010/api/private', + headers: {authorization: 'Bearer YOUR_ACCESS_TOKEN'} + }; + axios.request(options).then(function (response) { + console.log(response.data); + }).catch(function (error) { + console.error(error); + }); + ``` + + ```obj-c Obj-C lines + #import + NSDictionary *headers = @{ @"authorization": @"Bearer YOUR_ACCESS_TOKEN" }; + NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://localhost:3010/api/private"] + cachePolicy:NSURLRequestUseProtocolCachePolicy + + timeoutInterval:10.0]; + + [request setHTTPMethod:@"get"]; + [request setAllHTTPHeaderFields:headers]; + NSURLSession *session = [NSURLSession sharedSession]; + NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request + completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { + + if (error) { + + NSLog(@"%@", error); + + } else { + + NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response; + + NSLog(@"%@", httpResponse); + + } + + }]; + + [dataTask resume]; + ``` + + ```php PHP lines + $curl = curl_init(); + curl_setopt_array($curl, [ + CURLOPT_PORT => "3010", + CURLOPT_URL => "http://localhost:3010/api/private", + CURLOPT_RETURNTRANSFER => true, + CURLOPT_ENCODING => "", + CURLOPT_MAXREDIRS => 10, + CURLOPT_TIMEOUT => 30, + CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, + CURLOPT_CUSTOMREQUEST => "get", + CURLOPT_HTTPHEADER => [ + "authorization: Bearer YOUR_ACCESS_TOKEN" + + ], + ]); + $response = curl_exec($curl); + $err = curl_error($curl); + curl_close($curl); + if ($err) { + echo "cURL Error #:" . $err; + } else { + echo $response; + } + ``` + + ```python Python lines + import http.client + conn = http.client.HTTPConnection("localhost:3010") + headers = { 'authorization': "Bearer YOUR_ACCESS_TOKEN" } + conn.request("get", "/api/private", headers=headers) + res = conn.getresponse() + data = res.read() + print(data.decode("utf-8")) + ``` + + ```rb Ruby lines + require 'uri' + require 'net/http' + url = URI("http://localhost:3010/api/private") + http = Net::HTTP.new(url.host, url.port) + request = Net::HTTP::Get.new(url) + request["authorization"] = 'Bearer YOUR_ACCESS_TOKEN' + response = http.request(request) + puts response.read_body + ``` + + ```swift Swift lines + import Foundation + let headers = ["authorization": "Bearer YOUR_ACCESS_TOKEN"] + let request = NSMutableURLRequest(url: NSURL(string: "http://localhost:3010/api/private")! as URL, + cachePolicy: .useProtocolCachePolicy, + + timeoutInterval: 10.0) + + request.httpMethod = "get" + request.allHTTPHeaderFields = headers + let session = URLSession.shared + let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in + if (error != nil) { + print(error) + + } else { + let httpResponse = response as? HTTPURLResponse + + print(httpResponse) + + } + }) + dataTask.resume() + ``` + + + + `/api/private-scoped`エンドポイントも同様の方法で呼び出しますが、APIのアクセス許可が正しく構成され、アクセストークンに`read:messages`スコープがあることを確認してください。 + + + ##### チェックポイント + /api/privateと/api/private-scopedエンドポイントを呼び出すことができるはずです。 + アプリケーションを実行して次の点を確認します: + GET /api/privateが認証された要求に使用できる。 + GET /api/private-scopedがread:messagesスコープが付与されたアクセストークンを含む認証された要求に使用できる。 + +
    + + ## 次のステップ + + 成功です!ここまで来れば、アプリケーションにログイン、ログアウト、ユーザープロファイル情報が備わっているはずです。 + + これでクイックスタートチュートリアルは終了ですが、機能はまだまだたくさんあります。Auth0でできることについて詳しくは、以下をご覧ください。 + + * [Auth0 Dashboard](https://manage.auth0.com/#) - Auth0のテナントやアプリケーションを構成して管理する方法について説明します + * [Auth0 Marketplace](https://marketplace.auth0.com/) - Auth0の機能性を拡張できる各種の統合を見つけられます +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    diff --git a/main/docs/ja-jp/quickstart/backend/django/interactive.mdx b/main/docs/ja-jp/quickstart/backend/django/interactive.mdx index ddf83a22c..e518f611f 100644 --- a/main/docs/ja-jp/quickstart/backend/django/interactive.mdx +++ b/main/docs/ja-jp/quickstart/backend/django/interactive.mdx @@ -1,297 +1,299 @@ ---- -title: "Django APIアプリケーションに認可を追加する" -permalink: "interactive" -'description': "このチュートリアルは、Djangoを使ってビルドされたPython APIに認可を追加する方法を説明します。" -'og:title': "Django APIアプリケーションに認可を追加する" -'og:description': "このチュートリアルは、Djangoを使ってビルドされたPython APIに認可を追加する方法を説明します。" -'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/django.png" -'twitter:title': "Django APIアプリケーションに認可を追加する" -'twitter:description': "このチュートリアルは、Djangoを使ってビルドされたPython APIに認可を追加する方法を説明します。" -sidebarTitle: Django API ---- - -import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; -import { LoggedInForm } from "/snippets/Login.jsx"; -import Validator from "/snippets/quickstart/backend/django/validator.py.mdx"; -import Views from "/snippets/quickstart/backend/django/views.py.mdx"; -import Urls from "/snippets/quickstart/backend/django/urls.py.mdx"; - -export const sections = [ - { id: "アクセス許可を定義する", title: "アクセス許可を定義する" }, - { id: "djangoにauth0の使用を構成する", title: "DjangoにAuth0の使用を構成する" }, - { id: "jwtバリデーターを作成する", title: "JWTバリデーターを作成する" }, - { id: "apiビューを作成する", title: "APIビューを作成する" }, - { id: "urlマッピングを追加する", title: "URLマッピングを追加する" } -] - - - - このガイドは、[Django](https://www.djangoproject.com/)を使ってビルドされた新規または既存のPython APIアプリケーションにAuth0を統合する方法を説明します。 - - Auth0 DashboardでAPIをまだ作成していない場合は、対話型のセレクターを使ってAuth0 APIを新規作成します。そうでない場合は、統合したいプロジェクトを表す既存のAPIを選択することができます。 - - または、Auth0 Dashboardを使って初めてAPIをセットアップする方法を使用の開始ガイドで確認することもできます。 - - Auth0にあるAPIはそれぞれAPI識別子を使って構成され、アプリケーションのコードはAPI識別子をオーディエンスとしてアクセストークンを検証します。 - - - **Auth0を初めてご利用ですか?** Auth0の仕組みと、OAuth 2.0フレームワークを用いたAPI認証と認可の実装について説明します。 - - -
    - アクセス許可は、ユーザーの代わりに、提供されたアクセストークンを使ってどのようにしてリソースにアクセスできるのかを定義できるようにします。たとえば、ユーザーがマネージャーアクセスレベルを持つ場合には、`messages`リソースに対して読み取りアクセスを付与し、管理者アクセスレベルを持つ場合には、書き込みアクセスを付与することができます。 - - Auth0 Dashboardの[[API]](https://manage.auth0.com/#/apis)セクションにある**[Permissions(権限)]** ビューで使用可能なアクセス許可を定義することができます。以下の例では`read:messages`スコープを使用します。 - - ![[Auth0 Dashboard]>[Applications(アプリケーション)]>[APIs]>[Specific API(特定のAPI]>[Permissions(権限)]タブ](/docs/images/ja-jp/cdy7uua7fh8z/1s3Yp5zqJiKiSWqbPSezNO/acef814282795bef6921535f044f96e9/Quickstarts_API.png) -
    - -
    - ### 依存関係をインストールする - - 1. `requirements.txt`に次の依存関係を追加します: - 2. `pip install -r requirements.txt`を実行する - - ### Djangoアプリケーションを作成する -
    - -
    - [Authlib](https://github.com/lepture/authlib)という名前のライブラリーを使用して、[ResourceProtector](https://docs.authlib.org/en/latest/flask/1/resource-server.html)を作成します。これは[Djangoビューのデコレーター](https://docs.djangoproject.com/en/4.0/topics/http/decorators/)の一種で、該当するバリデーターを使ってリソース(APIビュー)を保護します。 - - バリデーターは、リソースに渡すアクセストークンに有効な署名とクレームがあることを確認して検証します。 - - AuthLibの`JWTBearerTokenValidator`バリデーターに多少の変更を加えて、[アクセストークンの検証](/docs/ja-jp/secure/tokens/access-tokens/validate-access-tokens)要件が満たされるようにします。 - - `Auth0JWTBearerTokenValidator`を作成するには、`domain`と`audience`(API識別子)に渡すことが必要です。そうすると、トークンの署名を検証するのに必要な公開鍵が取得され、`JWTBearerTokenValidator`クラスに渡されます。 - - そして、クラスの`claims_options`をオーバーライドし、トークンの`expiry`、`audience`、`issue`クレームが要件を満たして有効であることを確認します。 - - インタラクティブパネルからのコードを利用して、`apiexample/validator.py`ファイルを作成します。 -
    - -
    - 次に、`apiexample/views.py`に3つのAPIビューを作成します: - - - `/api/public`:認証を必要としないパブリックエンドポイントです。 - - `/api/private`:有効なJWTを必要とするプライベートエンドポイントです。 - - `/api/private-scoped`:与えられた`scope`を含む有効なJWTを必要とするプライベートエンドポイントです。 - - 保護されたルートには`require_auth`デコレーターがあり、これは、以前に作成した`Auth0JWTBearerTokenValidator`を使用する`ResourceProtector`です。 - - `Auth0JWTBearerTokenValidator`を作成するには、テナントのドメインと以前に作成したAPIのAPI識別子に渡します。 - - `private_scoped`ルートの`require_auth`デコレーターは、追加の引数である`"read:messages"`を受け付けます。これは、以前に作成したアクセス許可(スコープ)について、アクセストークンをチェックします。 -
    - -
    - 前の手順では、`views.py`ファイルにメソッドを追加しました。次に、Djangoの[URL dispatcher](https://docs.djangoproject.com/en/4.0/topics/http/urls/)を使用して、それらのメソッドをURLへマッピングします。URL dispatcherでは、URLパターンをビューにマッピングすることができます。 - - `apiexample/urls.py`ファイルにURLパターンを追加します。 - - ### APIを呼び出す - - APIを呼び出すにはアクセストークンが必要です。テスト用のアクセストークンは、[APIの設定](https://manage.auth0.com/#/apis)の**[Test(テスト)]** ビューから取得することができます。 - - ![[Auth0 Dashboard]>[Applications(アプリケーション)]>[API]>[Specific API(特定のAPI]>[Test(テスト)]タブ](/docs/images/ja-jp/cdy7uua7fh8z/6jeVBuypOGX5qMRXeJn5ow/dd20eb74e1e9079287762ce33dcf8e2d/Quickstart_Example_App_API.png) - - 要求の`Authorization`ヘッダーにアクセストークンを指定します。 - - - ```bash cURL lines - curl --request get \ - --url 'http:///%7ByourDomain%7D.com/api_path' \ - --header 'authorization: Bearer YOUR_ACCESS_TOKEN_HERE' - ``` - ```csharp C# lines - var client = new RestClient("http:///%7ByourDomain%7D.com/api_path"); - var request = new RestRequest(Method.GET); - request.AddHeader("authorization", "Bearer YOUR_ACCESS_TOKEN_HERE"); - IRestResponse response = client.Execute(request); - ``` - - ```go Go lines - package main - import ( - "fmt" - "net/http" - "io/ioutil" - ) - func main() { - url := "http:///%7ByourDomain%7D.com/api_path" - req, _ := http.NewRequest("get", url, nil) - req.Header.Add("authorization", "Bearer YOUR_ACCESS_TOKEN_HERE") - res, _ := http.DefaultClient.Do(req) - defer res.Body.Close() - body, _ := ioutil.ReadAll(res.Body) - fmt.Println(res) - fmt.Println(string(body)) - } - ``` - - ```java Java lines - HttpResponse response = Unirest.get("http:///%7ByourDomain%7D.com/api_path") - .header("authorization", "Bearer YOUR_ACCESS_TOKEN_HERE") - .asString(); - ``` - - ```javascript Node.JS lines - var axios = require("axios").default; - var options = { - method: 'get', - url: 'http:///%7ByourDomain%7D.com/api_path', - headers: {authorization: 'Bearer YOUR_ACCESS_TOKEN_HERE'} - }; - axios.request(options).then(function (response) { - console.log(response.data); - }).catch(function (error) { - console.error(error); - }); - ``` - ```obj-c Obj-C lines - #import - NSDictionary *headers = @{ @"authorization": @"Bearer YOUR_ACCESS_TOKEN_HERE" }; - NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http:///%7ByourDomain%7D.com/api_path"] - cachePolicy:NSURLRequestUseProtocolCachePolicy - - timeoutInterval:10.0]; - - [request setHTTPMethod:@"get"]; - [request setAllHTTPHeaderFields:headers]; - NSURLSession *session = [NSURLSession sharedSession]; - NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request - completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { - - if (error) { - - NSLog(@"%@", error); - - } else { - - NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response; - - NSLog(@"%@", httpResponse); - - } - - }]; - - [dataTask resume]; - ``` - - ```php PHP lines - $curl = curl_init(); - curl_setopt_array($curl, [ - CURLOPT_URL => "http:///%7ByourDomain%7D.com/api_path", - CURLOPT_RETURNTRANSFER => true, - CURLOPT_ENCODING => "", - CURLOPT_MAXREDIRS => 10, - CURLOPT_TIMEOUT => 30, - CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, - CURLOPT_CUSTOMREQUEST => "get", - CURLOPT_HTTPHEADER => [ - "authorization: Bearer YOUR_ACCESS_TOKEN_HERE" - - ], - ]); - $response = curl_exec($curl); - $err = curl_error($curl); - curl_close($curl); - if ($err) { - echo "cURL Error #:" . $err; - } else { - echo $response; - } - ``` - ```python Python lines - import http.client - conn = http.client.HTTPConnection("") - headers = { 'authorization': "Bearer YOUR_ACCESS_TOKEN_HERE" } - conn.request("get", "/dev-gja8kxz4ndtex3rq.us.auth0.com.com/api_path", headers=headers) - res = conn.getresponse() - data = res.read() - print(data.decode("utf-8")) - ``` - - ```ruby Ruby lines - require 'uri' - require 'net/http' - url = URI("http:///%7ByourDomain%7D.com/api_path") - http = Net::HTTP.new(url.host, url.port) - request = Net::HTTP::Get.new(url) - request["authorization"] = 'Bearer YOUR_ACCESS_TOKEN_HERE' - response = http.request(request) - puts response.read_body - ``` - ```swift Swift lines - import Foundation - let headers = ["authorization": "Bearer YOUR_ACCESS_TOKEN_HERE"] - let request = NSMutableURLRequest(url: NSURL(string: "http:///%7ByourDomain%7D.com/api_path")! as URL, - cachePolicy: .useProtocolCachePolicy, - - timeoutInterval: 10.0) - - request.httpMethod = "get" - request.allHTTPHeaderFields = headers - let session = URLSession.shared - let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in - if (error != nil) { - print(error) - - } else { - let httpResponse = response as? HTTPURLResponse - - print(httpResponse) - - } - }) - dataTask.resume() - ``` - - -
    - - ## 次のステップ - - 成功です!ここまで来れば、アプリケーションにログイン、ログアウト、ユーザープロファイル情報が備わっているはずです。 - - これでクイックスタートチュートリアルは終了ですが、機能はまだまだたくさんあります。Auth0でできることについて詳しくは、以下をご覧ください。 - - * [Auth0 Dashboard](https://manage.auth0.com/#) - Auth0のテナントやアプリケーションを構成して管理する方法について説明します - * [Auth0 Marketplace](https://marketplace.auth0.com/) - Auth0の機能性を拡張できる各種の統合を見つけられます -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    +--- +title: "Django APIアプリケーションに認可を追加する" +permalink: "interactive" +'description': "このチュートリアルは、Djangoを使ってビルドされたPython APIに認可を追加する方法を説明します。" +'og:title': "Django APIアプリケーションに認可を追加する" +'og:description': "このチュートリアルは、Djangoを使ってビルドされたPython APIに認可を追加する方法を説明します。" +'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/django.png" +'twitter:title': "Django APIアプリケーションに認可を追加する" +'twitter:description': "このチュートリアルは、Djangoを使ってビルドされたPython APIに認可を追加する方法を説明します。" +sidebarTitle: Django API +--- + +import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; +import { LoggedInForm } from "/snippets/Login.jsx"; +import Validator from "/snippets/quickstart/backend/django/validator.py.mdx"; +import Views from "/snippets/quickstart/backend/django/views.py.mdx"; +import Urls from "/snippets/quickstart/backend/django/urls.py.mdx"; + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + +export const sections = [ + { id: "アクセス許可を定義する", title: "アクセス許可を定義する" }, + { id: "djangoにauth0の使用を構成する", title: "DjangoにAuth0の使用を構成する" }, + { id: "jwtバリデーターを作成する", title: "JWTバリデーターを作成する" }, + { id: "apiビューを作成する", title: "APIビューを作成する" }, + { id: "urlマッピングを追加する", title: "URLマッピングを追加する" } +] + + + + このガイドは、[Django](https://www.djangoproject.com/)を使ってビルドされた新規または既存のPython APIアプリケーションにAuth0を統合する方法を説明します。 + + Auth0 DashboardでAPIをまだ作成していない場合は、対話型のセレクターを使ってAuth0 APIを新規作成します。そうでない場合は、統合したいプロジェクトを表す既存のAPIを選択することができます。 + + または、Auth0 Dashboardを使って初めてAPIをセットアップする方法を使用の開始ガイドで確認することもできます。 + + Auth0にあるAPIはそれぞれAPI識別子を使って構成され、アプリケーションのコードはAPI識別子をオーディエンスとしてアクセストークンを検証します。 + + + **Auth0を初めてご利用ですか?** Auth0の仕組みと、OAuth 2.0フレームワークを用いたAPI認証と認可の実装について説明します。 + + +
    + アクセス許可は、ユーザーの代わりに、提供されたアクセストークンを使ってどのようにしてリソースにアクセスできるのかを定義できるようにします。たとえば、ユーザーがマネージャーアクセスレベルを持つ場合には、`messages`リソースに対して読み取りアクセスを付与し、管理者アクセスレベルを持つ場合には、書き込みアクセスを付与することができます。 + + Auth0 Dashboardの[[API]](https://manage.auth0.com/#/apis)セクションにある**[Permissions(権限)]** ビューで使用可能なアクセス許可を定義することができます。以下の例では`read:messages`スコープを使用します。 + + ![[Auth0 Dashboard]>[Applications(アプリケーション)]>[APIs]>[Specific API(特定のAPI]>[Permissions(権限)]タブ](/docs/images/ja-jp/cdy7uua7fh8z/1s3Yp5zqJiKiSWqbPSezNO/acef814282795bef6921535f044f96e9/Quickstarts_API.png) +
    + +
    + ### 依存関係をインストールする + + 1. `requirements.txt`に次の依存関係を追加します: + 2. `pip install -r requirements.txt`を実行する + + ### Djangoアプリケーションを作成する +
    + +
    + [Authlib](https://github.com/lepture/authlib)という名前のライブラリーを使用して、[ResourceProtector](https://docs.authlib.org/en/latest/flask/1/resource-server.html)を作成します。これは[Djangoビューのデコレーター](https://docs.djangoproject.com/en/4.0/topics/http/decorators/)の一種で、該当するバリデーターを使ってリソース(APIビュー)を保護します。 + + バリデーターは、リソースに渡すアクセストークンに有効な署名とクレームがあることを確認して検証します。 + + AuthLibの`JWTBearerTokenValidator`バリデーターに多少の変更を加えて、[アクセストークンの検証](/docs/ja-jp/secure/tokens/access-tokens/validate-access-tokens)要件が満たされるようにします。 + + `Auth0JWTBearerTokenValidator`を作成するには、`domain`と`audience`(API識別子)に渡すことが必要です。そうすると、トークンの署名を検証するのに必要な公開鍵が取得され、`JWTBearerTokenValidator`クラスに渡されます。 + + そして、クラスの`claims_options`をオーバーライドし、トークンの`expiry`、`audience`、`issue`クレームが要件を満たして有効であることを確認します。 + + インタラクティブパネルからのコードを利用して、`apiexample/validator.py`ファイルを作成します。 +
    + +
    + 次に、`apiexample/views.py`に3つのAPIビューを作成します: + + - `/api/public`:認証を必要としないパブリックエンドポイントです。 + - `/api/private`:有効なJWTを必要とするプライベートエンドポイントです。 + - `/api/private-scoped`:与えられた`scope`を含む有効なJWTを必要とするプライベートエンドポイントです。 + + 保護されたルートには`require_auth`デコレーターがあり、これは、以前に作成した`Auth0JWTBearerTokenValidator`を使用する`ResourceProtector`です。 + + `Auth0JWTBearerTokenValidator`を作成するには、テナントのドメインと以前に作成したAPIのAPI識別子に渡します。 + + `private_scoped`ルートの`require_auth`デコレーターは、追加の引数である`"read:messages"`を受け付けます。これは、以前に作成したアクセス許可(スコープ)について、アクセストークンをチェックします。 +
    + +
    + 前の手順では、`views.py`ファイルにメソッドを追加しました。次に、Djangoの[URL dispatcher](https://docs.djangoproject.com/en/4.0/topics/http/urls/)を使用して、それらのメソッドをURLへマッピングします。URL dispatcherでは、URLパターンをビューにマッピングすることができます。 + + `apiexample/urls.py`ファイルにURLパターンを追加します。 + + ### APIを呼び出す + + APIを呼び出すにはアクセストークンが必要です。テスト用のアクセストークンは、[APIの設定](https://manage.auth0.com/#/apis)の**[Test(テスト)]** ビューから取得することができます。 + + ![[Auth0 Dashboard]>[Applications(アプリケーション)]>[API]>[Specific API(特定のAPI]>[Test(テスト)]タブ](/docs/images/ja-jp/cdy7uua7fh8z/6jeVBuypOGX5qMRXeJn5ow/dd20eb74e1e9079287762ce33dcf8e2d/Quickstart_Example_App_API.png) + + 要求の`Authorization`ヘッダーにアクセストークンを指定します。 + + + ```bash cURL lines + curl --request get \ + --url 'http:///%7ByourDomain%7D.com/api_path' \ + --header 'authorization: Bearer YOUR_ACCESS_TOKEN_HERE' + ``` + ```csharp C# lines + var client = new RestClient("http:///%7ByourDomain%7D.com/api_path"); + var request = new RestRequest(Method.GET); + request.AddHeader("authorization", "Bearer YOUR_ACCESS_TOKEN_HERE"); + IRestResponse response = client.Execute(request); + ``` + + ```go Go lines + package main + import ( + "fmt" + "net/http" + "io/ioutil" + ) + func main() { + url := "http:///%7ByourDomain%7D.com/api_path" + req, _ := http.NewRequest("get", url, nil) + req.Header.Add("authorization", "Bearer YOUR_ACCESS_TOKEN_HERE") + res, _ := http.DefaultClient.Do(req) + defer res.Body.Close() + body, _ := ioutil.ReadAll(res.Body) + fmt.Println(res) + fmt.Println(string(body)) + } + ``` + + ```java Java lines + HttpResponse response = Unirest.get("http:///%7ByourDomain%7D.com/api_path") + .header("authorization", "Bearer YOUR_ACCESS_TOKEN_HERE") + .asString(); + ``` + + ```javascript Node.JS lines + var axios = require("axios").default; + var options = { + method: 'get', + url: 'http:///%7ByourDomain%7D.com/api_path', + headers: {authorization: 'Bearer YOUR_ACCESS_TOKEN_HERE'} + }; + axios.request(options).then(function (response) { + console.log(response.data); + }).catch(function (error) { + console.error(error); + }); + ``` + ```obj-c Obj-C lines + #import + NSDictionary *headers = @{ @"authorization": @"Bearer YOUR_ACCESS_TOKEN_HERE" }; + NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http:///%7ByourDomain%7D.com/api_path"] + cachePolicy:NSURLRequestUseProtocolCachePolicy + + timeoutInterval:10.0]; + + [request setHTTPMethod:@"get"]; + [request setAllHTTPHeaderFields:headers]; + NSURLSession *session = [NSURLSession sharedSession]; + NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request + completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { + + if (error) { + + NSLog(@"%@", error); + + } else { + + NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response; + + NSLog(@"%@", httpResponse); + + } + + }]; + + [dataTask resume]; + ``` + + ```php PHP lines + $curl = curl_init(); + curl_setopt_array($curl, [ + CURLOPT_URL => "http:///%7ByourDomain%7D.com/api_path", + CURLOPT_RETURNTRANSFER => true, + CURLOPT_ENCODING => "", + CURLOPT_MAXREDIRS => 10, + CURLOPT_TIMEOUT => 30, + CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, + CURLOPT_CUSTOMREQUEST => "get", + CURLOPT_HTTPHEADER => [ + "authorization: Bearer YOUR_ACCESS_TOKEN_HERE" + + ], + ]); + $response = curl_exec($curl); + $err = curl_error($curl); + curl_close($curl); + if ($err) { + echo "cURL Error #:" . $err; + } else { + echo $response; + } + ``` + ```python Python lines + import http.client + conn = http.client.HTTPConnection("") + headers = { 'authorization': "Bearer YOUR_ACCESS_TOKEN_HERE" } + conn.request("get", "/dev-gja8kxz4ndtex3rq.us.auth0.com.com/api_path", headers=headers) + res = conn.getresponse() + data = res.read() + print(data.decode("utf-8")) + ``` + + ```ruby Ruby lines + require 'uri' + require 'net/http' + url = URI("http:///%7ByourDomain%7D.com/api_path") + http = Net::HTTP.new(url.host, url.port) + request = Net::HTTP::Get.new(url) + request["authorization"] = 'Bearer YOUR_ACCESS_TOKEN_HERE' + response = http.request(request) + puts response.read_body + ``` + ```swift Swift lines + import Foundation + let headers = ["authorization": "Bearer YOUR_ACCESS_TOKEN_HERE"] + let request = NSMutableURLRequest(url: NSURL(string: "http:///%7ByourDomain%7D.com/api_path")! as URL, + cachePolicy: .useProtocolCachePolicy, + + timeoutInterval: 10.0) + + request.httpMethod = "get" + request.allHTTPHeaderFields = headers + let session = URLSession.shared + let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in + if (error != nil) { + print(error) + + } else { + let httpResponse = response as? HTTPURLResponse + + print(httpResponse) + + } + }) + dataTask.resume() + ``` + + +
    + + ## 次のステップ + + 成功です!ここまで来れば、アプリケーションにログイン、ログアウト、ユーザープロファイル情報が備わっているはずです。 + + これでクイックスタートチュートリアルは終了ですが、機能はまだまだたくさんあります。Auth0でできることについて詳しくは、以下をご覧ください。 + + * [Auth0 Dashboard](https://manage.auth0.com/#) - Auth0のテナントやアプリケーションを構成して管理する方法について説明します + * [Auth0 Marketplace](https://marketplace.auth0.com/) - Auth0の機能性を拡張できる各種の統合を見つけられます +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    diff --git a/main/docs/ja-jp/quickstart/backend/golang/interactive.mdx b/main/docs/ja-jp/quickstart/backend/golang/interactive.mdx index c684d3984..94110e587 100644 --- a/main/docs/ja-jp/quickstart/backend/golang/interactive.mdx +++ b/main/docs/ja-jp/quickstart/backend/golang/interactive.mdx @@ -1,325 +1,327 @@ ---- -title: "Goアプリケーションに認可を追加する" -permalink: "interactive" -'description': "このチュートリアルは、Go APIに認可を追加する方法を説明します。" -'og:title': "Goアプリケーションに認可を追加する" -'og:description': "このチュートリアルは、Go APIに認可を追加する方法を説明します。" -'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/golang.png" -'twitter:title': "Goアプリケーションに認可を追加する" -'twitter:description': "このチュートリアルは、Go APIに認可を追加する方法を説明します。" -sidebarTitle: Go API ---- - -import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; -import { LoggedInForm } from "/snippets/Login.jsx"; -import Jwt from "/snippets/quickstart/backend/golang/jwt.go.mdx"; -import Main from "/snippets/quickstart/backend/golang/main.go.mdx"; - -export const sections = [ - { id: "アクセス許可を定義する", title: "アクセス許可を定義する" }, - { id: "依存関係をインストールする", title: "依存関係をインストールする" }, - { id: "アプリケーションを構成する", title: "アプリケーションを構成する" }, - { id: "アクセストークンを検証するミドルウェアを作成する", title: "アクセストークンを検証するミドルウェアを作成する" }, - { id: "apiエンドポイントを保護する", title: "APIエンドポイントを保護する" } -] - - - - このガイドは、新規または既存のGo APIアプリケーションに[go-jwt-middleware](https://github.com/auth0/go-jwt-middleware)パッケージを使ってAuth0を統合する方法を説明します。 - - Auth0 DashboardでAPIをまだ作成していない場合は、対話型のセレクターを使ってAuth0 APIを新規作成します。そうでない場合は、プロジェクトに既存のAPIを選択することができます。 - - Auth0 Dashboardを使って初めてAPIをセットアップする場合には、使用の開始ガイドを確認してください。 - - それぞれのAuth0 APIにはAPI識別子があり、アプリケーションにアクセストークンの検証で使用されます。 - - - **Auth0を初めてご利用ですか?** Auth0の仕組みと、OAuth 2.0フレームワークを用いたAPI認証と認可の実装について説明します。 - - -
    - アクセス許可は、ユーザーの代わりに、提供されたアクセストークンを使ってどのようにしてリソースにアクセスできるのかを定義できるようにします。たとえば、ユーザーがマネージャーアクセスレベルを持つ場合には、`messages`リソースに対して読み取りアクセスを付与し、管理者アクセスレベルを持つ場合には、書き込みアクセスを付与することができます。 - - Auth0 Dashboardの[[API]](https://manage.auth0.com/#/apis)セクションにある**[Permissions(権限)]** ビューで使用可能なアクセス許可を定義することができます。以下の例では`read:messages`スコープを使用します。 - - ![[Auth0 Dashboard]>[Applications(アプリケーション)]>[APIs]>[Specific API(特定のAPI]>[Permissions(権限)]タブ](/docs/images/ja-jp/cdy7uua7fh8z/1s3Yp5zqJiKiSWqbPSezNO/acef814282795bef6921535f044f96e9/Quickstarts_API.png) -
    - -
    - `go.mod`ファイルを追加して、必要な依存関係をすべてリストします。 - - ```mod - // go.mod - module 01-Authorization-RS256 - go 1.21 - require ( - github.com/auth0/go-jwt-middleware/v2 v2.2.0 - - github.com/joho/godotenv v1.5.1 - - ) - ``` - - 次のシェルコマンドを実行して、依存関係をダウンロードします: - - ```sh - go mod download - ``` -
    - -
    - アプリの構成を保存するために、`.env`ファイルをプロジェクトディレクトリのルート内に作成します。その後、環境変数を入力します: - - ``` - # The URL of our Auth0 Tenant Domain. - If you're using a Custom Domain, be sure to set this to that value instead. - AUTH0_DOMAIN='{yourDomain}' - Our Auth0 API's Identifier. - AUTH0_AUDIENCE='{yourApiIdentifier}' - ``` -
    - -
    - `EnsureValidToken`ミドルウェア関数はアクセストークンを検証します。この関数は、保護したいすべてのエンドポイントに適用することができます。トークンが有効であれば、エンドポイントがリソースを開放します。トークンが無効であれば、APIが`401 Authorization`エラーを返します。 - - 受信する要求のアクセストークンを検証するには、**go-jwt-middleware** ミドルウェア をセットアップします。 - - APIはデフォルトで、RS256をトークン署名アルゴリズムとしてセットアップします。RS256は秘密鍵と公開鍵のペアで機能するため、トークンはAuth0アカウントの公開鍵を使用して検証することができます。この公開鍵には、[https://{yourDomain}/.well-known/jwks.json](https://%7Byourdomain%7D/.well-known/jwks.json)でアクセスすることができます。 - - トークンが要求されたリソースへのアクセスに十分な**スコープ** を持っているか確認する機能を含めてください。 - - `HasScope`関数を作成して、応答を返す前に、アクセストークンに正しいスコープがあることを確認します。 -
    - -
    - この例では、`EnsureToken`ミドルウェアを使用しない`/api/public`エンドポイントを作成して、未認証の要求にも対応できるようにします。 - - `EnsureToken`ミドルウェアを必要とする`/api/private`エンドポイントを作成して、追加スコープのないアクセストークンを含む認証済み要求にのみ利用できるようにします。 - - `EnsureToken`ミドルウェアと`HasScope`を必要とする`/api/private-scoped`エンドポイントを作成して、`read:messages`スコープを付与されたアクセストークンを含む認証済み要求にのみ利用できるようにします。 - - - `read:messages`スコープのみが`HasScope`関数で検査されます。状況に応じて、複数のスコープを受け付けるように拡張するか、スタンドアローンのミドルウェアにすることをお勧めします。 - - - ### APIを呼び出す - - APIを呼び出すにはアクセストークンが必要です。テスト用のアクセストークンは、[API設定](https://manage.auth0.com/#/apis)の**[Test(テスト)]** ビューから取得することができます。 - - ![[Auth0 Dashboard]>[Applications(アプリケーション)]>[API]>[Specific API(特定のAPI]>[Test(テスト)]タブ](/docs/images/ja-jp/cdy7uua7fh8z/6jeVBuypOGX5qMRXeJn5ow/dd20eb74e1e9079287762ce33dcf8e2d/Quickstart_Example_App_API.png) - - 要求の`Authorization`ヘッダーにアクセストークンを指定します。 - - - ```bash cURL lines - curl --request get \ - --url 'http:///%7ByourDomain%7D/api_path' \ - --header 'authorization: Bearer YOUR_ACCESS_TOKEN_HERE' - ``` - - ```csharp C# lines - var client = new RestClient("http:///%7ByourDomain%7D/api_path"); - var request = new RestRequest(Method.GET); - request.AddHeader("authorization", "Bearer YOUR_ACCESS_TOKEN_HERE"); - IRestResponse response = client.Execute(request); - ``` - - ```go Go lines - package main - import ( - "fmt" - "net/http" - "io/ioutil" - ) - func main() { - url := "http:///%7ByourDomain%7D/api_path" - req, _ := http.NewRequest("get", url, nil) - req.Header.Add("authorization", "Bearer YOUR_ACCESS_TOKEN_HERE") - res, _ := http.DefaultClient.Do(req) - defer res.Body.Close() - body, _ := ioutil.ReadAll(res.Body) - fmt.Println(res) - fmt.Println(string(body)) - } - ``` - - ```java Java lines - HttpResponse response = Unirest.get("http:///%7ByourDomain%7D/api_path") - .header("authorization", "Bearer YOUR_ACCESS_TOKEN_HERE") - .asString(); - ``` - - ```javascript Node.JS lines - var axios = require("axios").default; - var options = { - method: 'get', - url: 'http:///%7ByourDomain%7D/api_path', - headers: {authorization: 'Bearer YOUR_ACCESS_TOKEN_HERE'} - }; - axios.request(options).then(function (response) { - console.log(response.data); - }).catch(function (error) { - console.error(error); - }); - ``` - - ```obj-c Obj-C lines - #import - NSDictionary *headers = @{ @"authorization": @"Bearer YOUR_ACCESS_TOKEN_HERE" }; - NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http:///%7ByourDomain%7D/api_path"] - cachePolicy:NSURLRequestUseProtocolCachePolicy - - timeoutInterval:10.0]; - - [request setHTTPMethod:@"get"]; - [request setAllHTTPHeaderFields:headers]; - NSURLSession *session = [NSURLSession sharedSession]; - NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request - completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { - - if (error) { - - NSLog(@"%@", error); - - } else { - - NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response; - - NSLog(@"%@", httpResponse); - - } - - }]; - - [dataTask resume]; - ``` - - ```php PHP lines - #import - NSDictionary *headers = @{ @"authorization": @"Bearer YOUR_ACCESS_TOKEN_HERE" }; - NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http:///%7ByourDomain%7D/api_path"] - cachePolicy:NSURLRequestUseProtocolCachePolicy - - timeoutInterval:10.0]; - - [request setHTTPMethod:@"get"]; - [request setAllHTTPHeaderFields:headers]; - NSURLSession *session = [NSURLSession sharedSession]; - NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request - completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { - - if (error) { - - NSLog(@"%@", error); - - } else { - - NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response; - - NSLog(@"%@", httpResponse); - - } - - }]; - - [dataTask resume]; - ``` - - ```python Python lines - import http.client - conn = http.client.HTTPConnection("") - headers = { 'authorization': "Bearer YOUR_ACCESS_TOKEN_HERE" } - conn.request("get", "/dev-gja8kxz4ndtex3rq.us.auth0.com/api_path", headers=headers) - res = conn.getresponse() - data = res.read() - print(data.decode("utf-8")) - ``` - - ```ruby Ruby lines - require 'uri' - require 'net/http' - url = URI("http:///%7ByourDomain%7D/api_path") - http = Net::HTTP.new(url.host, url.port) - request = Net::HTTP::Get.new(url) - request["authorization"] = 'Bearer YOUR_ACCESS_TOKEN_HERE' - response = http.request(request) - puts response.read_body - ``` - - ```swift Swift lines - import Foundation - let headers = ["authorization": "Bearer YOUR_ACCESS_TOKEN_HERE"] - let request = NSMutableURLRequest(url: NSURL(string: "http:///%7ByourDomain%7D/api_path")! as URL, - cachePolicy: .useProtocolCachePolicy, - - timeoutInterval: 10.0) - - request.httpMethod = "get" - request.allHTTPHeaderFields = headers - let session = URLSession.shared - let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in - if (error != nil) { - print(error) - - } else { - let httpResponse = response as? HTTPURLResponse - - print(httpResponse) - - } - }) - dataTask.resume() - ``` - - - - - - ##### チェックポイント - アプリケーションの構成が完了したら、アプリケーションを実行して次の点を確認します: - GET /api/publicが認証を必要としない要求に使用できる。 - GET /api/privateが認証された要求に使用できる。 - GET /api/private-scopedがread:messagesスコープが付与されたアクセストークンを含む認証された要求に使用できる。 - -
    - - ## 次のステップ - - 成功です!ここまで来れば、アプリケーションにログイン、ログアウト、ユーザープロファイル情報が備わっているはずです。 - - これでクイックスタートチュートリアルは終了ですが、機能はまだまだたくさんあります。Auth0でできることについて詳しくは、以下をご覧ください。 - - * [Auth0 Dashboard](https://manage.auth0.com/#) - Auth0のテナントやアプリケーションを構成して管理する方法について説明します - * [go-jwt-middleware SDK](https://github.com/auth0/go-jwt-middleware) - このチュートリアルで使用されているSDKをより詳しく説明します - * [Auth0 Marketplace](https://marketplace.auth0.com/) - Auth0の機能性を拡張できる各種の統合を見つけられます -
    - - - - - - - - - - - - - - - - - -
    - - - - - -
    - - - - - - +--- +title: "Goアプリケーションに認可を追加する" +permalink: "interactive" +'description': "このチュートリアルは、Go APIに認可を追加する方法を説明します。" +'og:title': "Goアプリケーションに認可を追加する" +'og:description': "このチュートリアルは、Go APIに認可を追加する方法を説明します。" +'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/golang.png" +'twitter:title': "Goアプリケーションに認可を追加する" +'twitter:description': "このチュートリアルは、Go APIに認可を追加する方法を説明します。" +sidebarTitle: Go API +--- + +import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; +import { LoggedInForm } from "/snippets/Login.jsx"; +import Jwt from "/snippets/quickstart/backend/golang/jwt.go.mdx"; +import Main from "/snippets/quickstart/backend/golang/main.go.mdx"; + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + +export const sections = [ + { id: "アクセス許可を定義する", title: "アクセス許可を定義する" }, + { id: "依存関係をインストールする", title: "依存関係をインストールする" }, + { id: "アプリケーションを構成する", title: "アプリケーションを構成する" }, + { id: "アクセストークンを検証するミドルウェアを作成する", title: "アクセストークンを検証するミドルウェアを作成する" }, + { id: "apiエンドポイントを保護する", title: "APIエンドポイントを保護する" } +] + + + + このガイドは、新規または既存のGo APIアプリケーションに[go-jwt-middleware](https://github.com/auth0/go-jwt-middleware)パッケージを使ってAuth0を統合する方法を説明します。 + + Auth0 DashboardでAPIをまだ作成していない場合は、対話型のセレクターを使ってAuth0 APIを新規作成します。そうでない場合は、プロジェクトに既存のAPIを選択することができます。 + + Auth0 Dashboardを使って初めてAPIをセットアップする場合には、使用の開始ガイドを確認してください。 + + それぞれのAuth0 APIにはAPI識別子があり、アプリケーションにアクセストークンの検証で使用されます。 + + + **Auth0を初めてご利用ですか?** Auth0の仕組みと、OAuth 2.0フレームワークを用いたAPI認証と認可の実装について説明します。 + + +
    + アクセス許可は、ユーザーの代わりに、提供されたアクセストークンを使ってどのようにしてリソースにアクセスできるのかを定義できるようにします。たとえば、ユーザーがマネージャーアクセスレベルを持つ場合には、`messages`リソースに対して読み取りアクセスを付与し、管理者アクセスレベルを持つ場合には、書き込みアクセスを付与することができます。 + + Auth0 Dashboardの[[API]](https://manage.auth0.com/#/apis)セクションにある**[Permissions(権限)]** ビューで使用可能なアクセス許可を定義することができます。以下の例では`read:messages`スコープを使用します。 + + ![[Auth0 Dashboard]>[Applications(アプリケーション)]>[APIs]>[Specific API(特定のAPI]>[Permissions(権限)]タブ](/docs/images/ja-jp/cdy7uua7fh8z/1s3Yp5zqJiKiSWqbPSezNO/acef814282795bef6921535f044f96e9/Quickstarts_API.png) +
    + +
    + `go.mod`ファイルを追加して、必要な依存関係をすべてリストします。 + + ```mod + // go.mod + module 01-Authorization-RS256 + go 1.21 + require ( + github.com/auth0/go-jwt-middleware/v2 v2.2.0 + + github.com/joho/godotenv v1.5.1 + + ) + ``` + + 次のシェルコマンドを実行して、依存関係をダウンロードします: + + ```sh + go mod download + ``` +
    + +
    + アプリの構成を保存するために、`.env`ファイルをプロジェクトディレクトリのルート内に作成します。その後、環境変数を入力します: + + ``` + # The URL of our Auth0 Tenant Domain. + If you're using a Custom Domain, be sure to set this to that value instead. + AUTH0_DOMAIN='{yourDomain}' + Our Auth0 API's Identifier. + AUTH0_AUDIENCE='{yourApiIdentifier}' + ``` +
    + +
    + `EnsureValidToken`ミドルウェア関数はアクセストークンを検証します。この関数は、保護したいすべてのエンドポイントに適用することができます。トークンが有効であれば、エンドポイントがリソースを開放します。トークンが無効であれば、APIが`401 Authorization`エラーを返します。 + + 受信する要求のアクセストークンを検証するには、**go-jwt-middleware** ミドルウェア をセットアップします。 + + APIはデフォルトで、RS256をトークン署名アルゴリズムとしてセットアップします。RS256は秘密鍵と公開鍵のペアで機能するため、トークンはAuth0アカウントの公開鍵を使用して検証することができます。この公開鍵には、[https://{yourDomain}/.well-known/jwks.json](https://%7Byourdomain%7D/.well-known/jwks.json)でアクセスすることができます。 + + トークンが要求されたリソースへのアクセスに十分な**スコープ** を持っているか確認する機能を含めてください。 + + `HasScope`関数を作成して、応答を返す前に、アクセストークンに正しいスコープがあることを確認します。 +
    + +
    + この例では、`EnsureToken`ミドルウェアを使用しない`/api/public`エンドポイントを作成して、未認証の要求にも対応できるようにします。 + + `EnsureToken`ミドルウェアを必要とする`/api/private`エンドポイントを作成して、追加スコープのないアクセストークンを含む認証済み要求にのみ利用できるようにします。 + + `EnsureToken`ミドルウェアと`HasScope`を必要とする`/api/private-scoped`エンドポイントを作成して、`read:messages`スコープを付与されたアクセストークンを含む認証済み要求にのみ利用できるようにします。 + + + `read:messages`スコープのみが`HasScope`関数で検査されます。状況に応じて、複数のスコープを受け付けるように拡張するか、スタンドアローンのミドルウェアにすることをお勧めします。 + + + ### APIを呼び出す + + APIを呼び出すにはアクセストークンが必要です。テスト用のアクセストークンは、[API設定](https://manage.auth0.com/#/apis)の**[Test(テスト)]** ビューから取得することができます。 + + ![[Auth0 Dashboard]>[Applications(アプリケーション)]>[API]>[Specific API(特定のAPI]>[Test(テスト)]タブ](/docs/images/ja-jp/cdy7uua7fh8z/6jeVBuypOGX5qMRXeJn5ow/dd20eb74e1e9079287762ce33dcf8e2d/Quickstart_Example_App_API.png) + + 要求の`Authorization`ヘッダーにアクセストークンを指定します。 + + + ```bash cURL lines + curl --request get \ + --url 'http:///%7ByourDomain%7D/api_path' \ + --header 'authorization: Bearer YOUR_ACCESS_TOKEN_HERE' + ``` + + ```csharp C# lines + var client = new RestClient("http:///%7ByourDomain%7D/api_path"); + var request = new RestRequest(Method.GET); + request.AddHeader("authorization", "Bearer YOUR_ACCESS_TOKEN_HERE"); + IRestResponse response = client.Execute(request); + ``` + + ```go Go lines + package main + import ( + "fmt" + "net/http" + "io/ioutil" + ) + func main() { + url := "http:///%7ByourDomain%7D/api_path" + req, _ := http.NewRequest("get", url, nil) + req.Header.Add("authorization", "Bearer YOUR_ACCESS_TOKEN_HERE") + res, _ := http.DefaultClient.Do(req) + defer res.Body.Close() + body, _ := ioutil.ReadAll(res.Body) + fmt.Println(res) + fmt.Println(string(body)) + } + ``` + + ```java Java lines + HttpResponse response = Unirest.get("http:///%7ByourDomain%7D/api_path") + .header("authorization", "Bearer YOUR_ACCESS_TOKEN_HERE") + .asString(); + ``` + + ```javascript Node.JS lines + var axios = require("axios").default; + var options = { + method: 'get', + url: 'http:///%7ByourDomain%7D/api_path', + headers: {authorization: 'Bearer YOUR_ACCESS_TOKEN_HERE'} + }; + axios.request(options).then(function (response) { + console.log(response.data); + }).catch(function (error) { + console.error(error); + }); + ``` + + ```obj-c Obj-C lines + #import + NSDictionary *headers = @{ @"authorization": @"Bearer YOUR_ACCESS_TOKEN_HERE" }; + NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http:///%7ByourDomain%7D/api_path"] + cachePolicy:NSURLRequestUseProtocolCachePolicy + + timeoutInterval:10.0]; + + [request setHTTPMethod:@"get"]; + [request setAllHTTPHeaderFields:headers]; + NSURLSession *session = [NSURLSession sharedSession]; + NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request + completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { + + if (error) { + + NSLog(@"%@", error); + + } else { + + NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response; + + NSLog(@"%@", httpResponse); + + } + + }]; + + [dataTask resume]; + ``` + + ```php PHP lines + #import + NSDictionary *headers = @{ @"authorization": @"Bearer YOUR_ACCESS_TOKEN_HERE" }; + NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http:///%7ByourDomain%7D/api_path"] + cachePolicy:NSURLRequestUseProtocolCachePolicy + + timeoutInterval:10.0]; + + [request setHTTPMethod:@"get"]; + [request setAllHTTPHeaderFields:headers]; + NSURLSession *session = [NSURLSession sharedSession]; + NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request + completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { + + if (error) { + + NSLog(@"%@", error); + + } else { + + NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response; + + NSLog(@"%@", httpResponse); + + } + + }]; + + [dataTask resume]; + ``` + + ```python Python lines + import http.client + conn = http.client.HTTPConnection("") + headers = { 'authorization': "Bearer YOUR_ACCESS_TOKEN_HERE" } + conn.request("get", "/dev-gja8kxz4ndtex3rq.us.auth0.com/api_path", headers=headers) + res = conn.getresponse() + data = res.read() + print(data.decode("utf-8")) + ``` + + ```ruby Ruby lines + require 'uri' + require 'net/http' + url = URI("http:///%7ByourDomain%7D/api_path") + http = Net::HTTP.new(url.host, url.port) + request = Net::HTTP::Get.new(url) + request["authorization"] = 'Bearer YOUR_ACCESS_TOKEN_HERE' + response = http.request(request) + puts response.read_body + ``` + + ```swift Swift lines + import Foundation + let headers = ["authorization": "Bearer YOUR_ACCESS_TOKEN_HERE"] + let request = NSMutableURLRequest(url: NSURL(string: "http:///%7ByourDomain%7D/api_path")! as URL, + cachePolicy: .useProtocolCachePolicy, + + timeoutInterval: 10.0) + + request.httpMethod = "get" + request.allHTTPHeaderFields = headers + let session = URLSession.shared + let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in + if (error != nil) { + print(error) + + } else { + let httpResponse = response as? HTTPURLResponse + + print(httpResponse) + + } + }) + dataTask.resume() + ``` + + + + + + ##### チェックポイント + アプリケーションの構成が完了したら、アプリケーションを実行して次の点を確認します: + GET /api/publicが認証を必要としない要求に使用できる。 + GET /api/privateが認証された要求に使用できる。 + GET /api/private-scopedがread:messagesスコープが付与されたアクセストークンを含む認証された要求に使用できる。 + +
    + + ## 次のステップ + + 成功です!ここまで来れば、アプリケーションにログイン、ログアウト、ユーザープロファイル情報が備わっているはずです。 + + これでクイックスタートチュートリアルは終了ですが、機能はまだまだたくさんあります。Auth0でできることについて詳しくは、以下をご覧ください。 + + * [Auth0 Dashboard](https://manage.auth0.com/#) - Auth0のテナントやアプリケーションを構成して管理する方法について説明します + * [go-jwt-middleware SDK](https://github.com/auth0/go-jwt-middleware) - このチュートリアルで使用されているSDKをより詳しく説明します + * [Auth0 Marketplace](https://marketplace.auth0.com/) - Auth0の機能性を拡張できる各種の統合を見つけられます +
    + + + + + + + + + + + + + + + + + +
    + + + + + +
    + + + + + + diff --git a/main/docs/ja-jp/quickstart/backend/java-spring-security5/interactive.mdx b/main/docs/ja-jp/quickstart/backend/java-spring-security5/interactive.mdx index 91ab9ada4..05b43aea2 100644 --- a/main/docs/ja-jp/quickstart/backend/java-spring-security5/interactive.mdx +++ b/main/docs/ja-jp/quickstart/backend/java-spring-security5/interactive.mdx @@ -1,233 +1,235 @@ ---- -title: "Spring Bootアプリケーションに認可を追加する" -permalink: "interactive" -'description': "このガイドは、新規または既存のSpring BootアプリケーションにAuth0を統合する方法を説明します。" -'og:title': "Spring Bootアプリケーションに認可を追加する" -'og:description': "このガイドは、新規または既存のSpring BootアプリケーションにAuth0を統合する方法を説明します。" -'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/java.png" -'twitter:title': "Spring Bootアプリケーションに認可を追加する" -'twitter:description': "このガイドは、新規または既存のSpring BootアプリケーションにAuth0を統合する方法を説明します。" -sidebarTitle: Spring Boot API ---- - -import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; -import { LoggedInForm } from "/snippets/Login.jsx"; -import Application from "/snippets/quickstart/backend/java-spring-security5/application.yml.mdx"; -import Securityconfig from "/snippets/quickstart/backend/java-spring-security5/SecurityConfig.java.mdx"; -import Apicontroller from "/snippets/quickstart/backend/java-spring-security5/APIController.java.mdx"; - -export const sections = [ - { id: "アクセス許可を定義する", title: "アクセス許可を定義する" }, - { id: "サンプルプロジェクトを構成する", title: "サンプルプロジェクトを構成する" }, - { id: "依存関係をインストールする", title: "依存関係をインストールする" }, - { id: "リソースサーバーを構成する", title: "リソースサーバーを構成する" }, - { id: "ドメインオブジェクトを作成する", title: "ドメインオブジェクトを作成する" }, - { id: "apiコントローラーを作成する", title: "APIコントローラーを作成する" }, - { id: "アプリケーションを実行する", title: "アプリケーションを実行する" } -] - - - - Auth0を使用すると、アプリケーションにすばやく認可を追加することができます。このガイドは、新規または既存のSpring BootアプリケーションにAuth0を統合する方法を説明します。 - - Auth0 DashboardでAPIをまだ作成していない場合は、対話型のセレクターを使ってAuth0 APIを新規作成します。そうでない場合は、統合したいプロジェクトを表す既存のAPIを選択します。 - - Auth0 Dashboardを使って初めてAPIをセットアップする場合には、[使用の開始ガイド](/docs/ja-jp/get-started/auth0-overview/set-up-apis)を確認してください。 - - それぞれのAuth0 APIにはAPI識別子があり、アプリケーションにアクセストークンの検証で使用されます。 - - - **Auth0を初めてご利用ですか?** [Auth0の仕組み](/docs/ja-jp/overview)と、OAuth 2.0フレームワークを用いた[API認証と認可の実装](/docs/ja-jp/api-auth)について説明します。 - - -
    - アクセス許可は、ユーザーの代わりに、提供されたアクセストークンを使ってどのようにしてリソースにアクセスできるのかを定義できるようにします。たとえば、ユーザーがマネージャーアクセスレベルを持つ場合には、`messages`リソースに対して読み出しアクセスを付与し、管理者アクセスレベルを持つ場合には、書き込みアクセスを付与することができます。 - - Auth0 Dashboardの[[APIs]](https://manage.auth0.com/dashboard/us/dev-1-2s2aq0/apis)セクションにある**[Permissions(権限)]** ビューで使用可能なアクセス許可を定義することができます。 - - ![[Auth0 Dashboard]>[Applications(アプリケーション)]>[APIs]>[Specific API(特定のAPI]>[Permissions(権限)]タブ](/docs/images/ja-jp/cdy7uua7fh8z/1s3Yp5zqJiKiSWqbPSezNO/acef814282795bef6921535f044f96e9/Quickstarts_API.png) - - - 以下の例では`read:messages`スコープを使用します。 - -
    - -
    - サンプルプロジェクトは`/src/main/resources/application.yml`ファイルを使用し、これをAPIに対して正しいAuth0**ドメイン** と**API識別子** を使用するように構成します。このページからコードをダウンロードすると、自動的に構成されます。GitHubから例を複製する場合は、ご自身で入力する必要があります。 -
    - -
    - Gradleを使用している場合、[Spring Boot Gradleプラグイン](https://docs.spring.io/spring-boot/docs/current/gradle-plugin/reference/html/)と[Dependency Managementプラグイン](https://docs.spring.io/dependency-management-plugin/docs/current/reference/html/)を使って必要な依存関係を追加し、依存関係のバージョンを解決することができます: - - ```gradle - // build.gradle - plugins { - - id 'java' - - id 'org.springframework.boot' - - version '3.1.5' - - id 'io.spring.dependency-management' - - version '1.1.3' - - } - - dependencies { - - implementation 'org.springframework.boot:spring-boot-starter-web' - - implementation 'com.okta.spring:okta-spring-boot-starter:3.0.5' - - } - ``` - - Mavenを使用している場合は、Springの依存関係を`pom.xml`ファイルに追加します: - - ```xml - // pom.xml - - org.springframework.boot - spring-boot-starter-parent - 3.1.5 - - - - - org.springframework.boot - spring-boot-starter-web - - - com.okta.spring - okta-spring-boot-starter - 3.0.5 - - - ``` -
    - -
    - アプリケーションをリソースサーバーとして構成し、JWTを検証するには、`SecurityFilterChain`のインスタンスを提供するクラスを作成し、`@Configuration`の注釈を追加します。 - - ### APIエンドポイントを保護する - - 以下に示されたルートは次の要求で使用することができます: - - - `GET /api/public`:認証を必要としない要求に使用できる - - `GET /api/private`:追加スコープのないアクセストークンを含む認証された要求に使用できる - - `GET /api/private-scoped`:`read:messages`スコープが付与されたアクセストークンを含む認証された要求に使用できる - - 以下の例は、`SecurityConfig`クラスの`filterChain()`メソッドで指定された`HttpSecurity`オブジェクトを使用して、APIメソッドのセキュリティを確保する方法を示します。ルートマッチャーは必要な認可レベルに基づいてアクセスを制限します。 - - - デフォルトで、Spring SecurityはJWTの`scope`クレームで、クレームごとに`GrantedAuthority`を作成します。このスコープでは、`hasAuthority("SCOPE_read:messages")`メソッドを使用して、`read:messages`スコープを含む有効なJWTへのアクセスを制限することができます。 - -
    - -
    - エンドポイントがJSONを返すには、Javaレコードを使用することができます。このオブジェクトのメンバー変数は、JSONのキー値にシリアル化されます。`Message`と呼ばれる新しいレコードを、API呼び出し中に返すサンプルドメインオブジェクトとして作成します。 -
    - -
    - `APIController`という名前の新しいクラスを作成し、エンドポイントへの要求を処理します。`APIController`には、[APIエンドポイントを保護する](/docs/ja-jp/quickstart/backend/java-spring-security5/interactive#configure-the-resource-server)セクションで定義されるように、3つのルートがあります。たとえば、`@CrossOrigin`の注釈からすべてのオリジンを許可します。実際のアプリケーションでは、ユースケースに対して`CORS`を構成する必要があります。 -
    - -
    - サンプルプロジェクトを構築し実行するには、`bootRun` Gradleタスクを実行します。 - - LinuxまたはmacOS: - - ```sh - ./gradlew bootRun - ``` - - Windows: - - ```ps - gradlew.bat bootRun - ``` - - Mavenと[Spring Boot Mavenプラグイン](https://docs.spring.io/spring-boot/docs/current/reference/html/build-tool-plugins-maven-plugin.html)で独自のアプリケーションを構成している場合は、`spring-boot:run`ゴールを実行することができます。 - - LinuxまたはmacOS: - - ```sh - mvn spring-boot:run - ``` - - Windows: - - ```ps - mvn.cmd spring-boot:run - ``` - - - ##### チェックポイント - サンプルアプリケーションはhttp://localhost:3010/で入手できます。「APIの使用」の記事でAPIをテストおよび使用する方法についてお読みください。 - -
    - - ## 次のステップ - - 成功です!ここまで来れば、アプリケーションにログイン、ログアウト、ユーザープロファイル情報が備わっているはずです。 - - これでクイックスタートチュートリアルは終了ですが、機能はまだまだたくさんあります。Auth0でできることについて詳しくは、以下をご覧ください。 - - * [Auth0 Dashboard](https://manage.auth0.com/#) - Auth0のテナントやアプリケーションを構成して管理する方法について説明します - * [Okta Spring Boot Starter SDK](https://github.com/okta/okta-spring-boot/) - このチュートリアルで使用されているSDKをより詳しく説明します - * [Auth0 Marketplace](https://marketplace.auth0.com/) - Auth0の機能性を拡張できる各種の統合を見つけられます -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    +--- +title: "Spring Bootアプリケーションに認可を追加する" +permalink: "interactive" +'description': "このガイドは、新規または既存のSpring BootアプリケーションにAuth0を統合する方法を説明します。" +'og:title': "Spring Bootアプリケーションに認可を追加する" +'og:description': "このガイドは、新規または既存のSpring BootアプリケーションにAuth0を統合する方法を説明します。" +'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/java.png" +'twitter:title': "Spring Bootアプリケーションに認可を追加する" +'twitter:description': "このガイドは、新規または既存のSpring BootアプリケーションにAuth0を統合する方法を説明します。" +sidebarTitle: Spring Boot API +--- + +import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; +import { LoggedInForm } from "/snippets/Login.jsx"; +import Application from "/snippets/quickstart/backend/java-spring-security5/application.yml.mdx"; +import Securityconfig from "/snippets/quickstart/backend/java-spring-security5/SecurityConfig.java.mdx"; +import Apicontroller from "/snippets/quickstart/backend/java-spring-security5/APIController.java.mdx"; + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + +export const sections = [ + { id: "アクセス許可を定義する", title: "アクセス許可を定義する" }, + { id: "サンプルプロジェクトを構成する", title: "サンプルプロジェクトを構成する" }, + { id: "依存関係をインストールする", title: "依存関係をインストールする" }, + { id: "リソースサーバーを構成する", title: "リソースサーバーを構成する" }, + { id: "ドメインオブジェクトを作成する", title: "ドメインオブジェクトを作成する" }, + { id: "apiコントローラーを作成する", title: "APIコントローラーを作成する" }, + { id: "アプリケーションを実行する", title: "アプリケーションを実行する" } +] + + + + Auth0を使用すると、アプリケーションにすばやく認可を追加することができます。このガイドは、新規または既存のSpring BootアプリケーションにAuth0を統合する方法を説明します。 + + Auth0 DashboardでAPIをまだ作成していない場合は、対話型のセレクターを使ってAuth0 APIを新規作成します。そうでない場合は、統合したいプロジェクトを表す既存のAPIを選択します。 + + Auth0 Dashboardを使って初めてAPIをセットアップする場合には、[使用の開始ガイド](/docs/ja-jp/get-started/auth0-overview/set-up-apis)を確認してください。 + + それぞれのAuth0 APIにはAPI識別子があり、アプリケーションにアクセストークンの検証で使用されます。 + + + **Auth0を初めてご利用ですか?** [Auth0の仕組み](/docs/ja-jp/overview)と、OAuth 2.0フレームワークを用いた[API認証と認可の実装](/docs/ja-jp/api-auth)について説明します。 + + +
    + アクセス許可は、ユーザーの代わりに、提供されたアクセストークンを使ってどのようにしてリソースにアクセスできるのかを定義できるようにします。たとえば、ユーザーがマネージャーアクセスレベルを持つ場合には、`messages`リソースに対して読み出しアクセスを付与し、管理者アクセスレベルを持つ場合には、書き込みアクセスを付与することができます。 + + Auth0 Dashboardの[[APIs]](https://manage.auth0.com/dashboard/us/dev-1-2s2aq0/apis)セクションにある**[Permissions(権限)]** ビューで使用可能なアクセス許可を定義することができます。 + + ![[Auth0 Dashboard]>[Applications(アプリケーション)]>[APIs]>[Specific API(特定のAPI]>[Permissions(権限)]タブ](/docs/images/ja-jp/cdy7uua7fh8z/1s3Yp5zqJiKiSWqbPSezNO/acef814282795bef6921535f044f96e9/Quickstarts_API.png) + + + 以下の例では`read:messages`スコープを使用します。 + +
    + +
    + サンプルプロジェクトは`/src/main/resources/application.yml`ファイルを使用し、これをAPIに対して正しいAuth0**ドメイン** と**API識別子** を使用するように構成します。このページからコードをダウンロードすると、自動的に構成されます。GitHubから例を複製する場合は、ご自身で入力する必要があります。 +
    + +
    + Gradleを使用している場合、[Spring Boot Gradleプラグイン](https://docs.spring.io/spring-boot/docs/current/gradle-plugin/reference/html/)と[Dependency Managementプラグイン](https://docs.spring.io/dependency-management-plugin/docs/current/reference/html/)を使って必要な依存関係を追加し、依存関係のバージョンを解決することができます: + + ```gradle + // build.gradle + plugins { + + id 'java' + + id 'org.springframework.boot' + + version '3.1.5' + + id 'io.spring.dependency-management' + + version '1.1.3' + + } + + dependencies { + + implementation 'org.springframework.boot:spring-boot-starter-web' + + implementation 'com.okta.spring:okta-spring-boot-starter:3.0.5' + + } + ``` + + Mavenを使用している場合は、Springの依存関係を`pom.xml`ファイルに追加します: + + ```xml + // pom.xml + + org.springframework.boot + spring-boot-starter-parent + 3.1.5 + + + + + org.springframework.boot + spring-boot-starter-web + + + com.okta.spring + okta-spring-boot-starter + 3.0.5 + + + ``` +
    + +
    + アプリケーションをリソースサーバーとして構成し、JWTを検証するには、`SecurityFilterChain`のインスタンスを提供するクラスを作成し、`@Configuration`の注釈を追加します。 + + ### APIエンドポイントを保護する + + 以下に示されたルートは次の要求で使用することができます: + + - `GET /api/public`:認証を必要としない要求に使用できる + - `GET /api/private`:追加スコープのないアクセストークンを含む認証された要求に使用できる + - `GET /api/private-scoped`:`read:messages`スコープが付与されたアクセストークンを含む認証された要求に使用できる + + 以下の例は、`SecurityConfig`クラスの`filterChain()`メソッドで指定された`HttpSecurity`オブジェクトを使用して、APIメソッドのセキュリティを確保する方法を示します。ルートマッチャーは必要な認可レベルに基づいてアクセスを制限します。 + + + デフォルトで、Spring SecurityはJWTの`scope`クレームで、クレームごとに`GrantedAuthority`を作成します。このスコープでは、`hasAuthority("SCOPE_read:messages")`メソッドを使用して、`read:messages`スコープを含む有効なJWTへのアクセスを制限することができます。 + +
    + +
    + エンドポイントがJSONを返すには、Javaレコードを使用することができます。このオブジェクトのメンバー変数は、JSONのキー値にシリアル化されます。`Message`と呼ばれる新しいレコードを、API呼び出し中に返すサンプルドメインオブジェクトとして作成します。 +
    + +
    + `APIController`という名前の新しいクラスを作成し、エンドポイントへの要求を処理します。`APIController`には、[APIエンドポイントを保護する](/docs/ja-jp/quickstart/backend/java-spring-security5/interactive#configure-the-resource-server)セクションで定義されるように、3つのルートがあります。たとえば、`@CrossOrigin`の注釈からすべてのオリジンを許可します。実際のアプリケーションでは、ユースケースに対して`CORS`を構成する必要があります。 +
    + +
    + サンプルプロジェクトを構築し実行するには、`bootRun` Gradleタスクを実行します。 + + LinuxまたはmacOS: + + ```sh + ./gradlew bootRun + ``` + + Windows: + + ```ps + gradlew.bat bootRun + ``` + + Mavenと[Spring Boot Mavenプラグイン](https://docs.spring.io/spring-boot/docs/current/reference/html/build-tool-plugins-maven-plugin.html)で独自のアプリケーションを構成している場合は、`spring-boot:run`ゴールを実行することができます。 + + LinuxまたはmacOS: + + ```sh + mvn spring-boot:run + ``` + + Windows: + + ```ps + mvn.cmd spring-boot:run + ``` + + + ##### チェックポイント + サンプルアプリケーションはhttp://localhost:3010/で入手できます。「APIの使用」の記事でAPIをテストおよび使用する方法についてお読みください。 + +
    + + ## 次のステップ + + 成功です!ここまで来れば、アプリケーションにログイン、ログアウト、ユーザープロファイル情報が備わっているはずです。 + + これでクイックスタートチュートリアルは終了ですが、機能はまだまだたくさんあります。Auth0でできることについて詳しくは、以下をご覧ください。 + + * [Auth0 Dashboard](https://manage.auth0.com/#) - Auth0のテナントやアプリケーションを構成して管理する方法について説明します + * [Okta Spring Boot Starter SDK](https://github.com/okta/okta-spring-boot/) - このチュートリアルで使用されているSDKをより詳しく説明します + * [Auth0 Marketplace](https://marketplace.auth0.com/) - Auth0の機能性を拡張できる各種の統合を見つけられます +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    diff --git a/main/docs/ja-jp/quickstart/backend/nodejs/interactive.mdx b/main/docs/ja-jp/quickstart/backend/nodejs/interactive.mdx index dabbdc8f8..0f266e364 100644 --- a/main/docs/ja-jp/quickstart/backend/nodejs/interactive.mdx +++ b/main/docs/ja-jp/quickstart/backend/nodejs/interactive.mdx @@ -1,283 +1,285 @@ ---- -title: "Express.js APIアプリケーションに認可を追加する" -permalink: "interactive" -'description': "このガイドは、新規または既存のExpress.js APIアプリケーションにexpress-oauth2-jwt-bearerパッケージを使ってAuth0を統合する方法を説明します。" -'og:title': "Express.js APIアプリケーションに認可を追加する" -'og:description': "このガイドは、新規または既存のExpress.js APIアプリケーションにexpress-oauth2-jwt-bearerパッケージを使ってAuth0を統合する方法を説明します。" -'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/node.png" -'twitter:title': "Express.js APIアプリケーションに認可を追加する" -'twitter:description': "このガイドは、新規または既存のExpress.js APIアプリケーションにexpress-oauth2-jwt-bearerパッケージを使ってAuth0を統合する方法を説明します。" -sidebarTitle: Node (Express) API ---- - -import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; -import { LoggedInForm } from "/snippets/Login.jsx"; -import Server from "/snippets/quickstart/backend/nodejs/server.js.mdx"; -import Server2 from "/snippets/quickstart/backend/nodejs/server.js2.mdx"; - -export const sections = [ - { id: "アクセス許可を定義する", title: "アクセス許可を定義する" }, - { id: "依存関係をインストールする", title: "依存関係をインストールする" }, - { id: "ミドルウェアを構成する", title: "ミドルウェアを構成する" }, - { id: "apiエンドポイントを保護する", title: "APIエンドポイントを保護する" } -] - - - - このガイドは、新規または既存のExpress.js APIアプリケーションに`express-oauth2-jwt-bearer`パッケージを使ってAuth0を統合する方法を説明します。 - - Auth0 DashboardでAPIをまだ作成していない場合は、対話型のセレクターを使ってAuth0 APIを新規作成します。そうでない場合は、既存のプロジェクトAPIを選択します。 - - Auth0 Dashboardを使って初めてAPIをセットアップする場合には、[使用の開始ガイド](/docs/ja-jp/get-started/auth0-overview/set-up-apis)を確認してください。それぞれのAuth0 APIにはAPI識別子があり、アプリケーションにアクセストークンの検証で使用されます。 - - - **Auth0を初めてご利用ですか?** [Auth0の仕組み](/docs/ja-jp/overview)と、OAuth 2.0フレームワークを用いた[API認証と認可の実装](/docs/ja-jp/api-auth)について説明します。 - - -
    - アクセス許可は、ユーザーの代わりに、提供されたアクセストークンを使ってどのようにしてリソースにアクセスできるのかを定義できるようにします。たとえば、ユーザーがマネージャーアクセスレベルを持つ場合には、`messages`リソースに対して読み出しアクセスを付与し、管理者アクセスレベルを持つ場合には、書き込みアクセスを付与することができます。 - - Auth0 Dashboardの[[APIs]](https://manage.auth0.com/#/apis)セクションにある**[Permissions(権限)]** ビューで使用可能なアクセス許可を定義することができます。 - - ![null](/docs/images/ja-jp/cdy7uua7fh8z/5EnGfdqLVZ8fuIxbUn7gm1/ee4278d6ae1910497771f3b9762c86f8/Quickstarts_API.png) - - - 以下の例では`read:messages`スコープを使用します。 - -
    - -
    - まず、`npm`でSDKをインストールします。 - - ```bash - npm install --save express-oauth2-jwt-bearer - ``` -
    - -
    - ドメインとAPI識別子を使って、`express-oauth2-jwt-bearer`を構成します。 - - 右に示した`checkJwt`ミドルウェアは、要求に含まれるユーザーのアクセストークンが有効かを確認します。トークンが有効でない場合、ユーザーがエンドポイントにアクセスしようとすると、「401 Authorization」というエラーが発生します。 - - ミドルウェアは、トークンに要求されたリソースにアクセスするだけの十分なスコープがあるかを確認しません。 -
    - -
    - 有効なJWTを必須して個々のルートを保護するには、`express-oauth2-jwt-bearer`から構築された`checkJwt`ミドルウェアでルートを構成します。 - - 特定のスコープを検索するために、個々のルートを構成することができます。これを実現するには、`requiresScope`メソッドで別のミドルウェアをセットアップします。必要なスコープを提供し、認可を追加したいルートにミドルウェアを適用します。 - - `checkJwt`と`requiredScopes`ミドルウェアを保護したいルートに渡します。 - - この構成では、`read:messages`スコープを持つアクセストークンのみがエンドポイントにアクセスすることができます。 - - ### APIを呼び出す - - APIを呼び出すにはアクセストークンが必要です。テスト用のアクセストークンは、[API設定](https://manage.auth0.com/#/apis)の**[Test(テスト)]** ビューから取得することができます。 - - ![null](/docs/images/ja-jp/cdy7uua7fh8z/5HUMcKGXoNOvdJNXFI73oi/f50dd78093814054a81903d1e478f3aa/API_access_tokens.png) - - 要求の`Authorization`ヘッダーにアクセストークンを指定します。 - - - ```bash cURL lines - curl --request get \ - --url 'http:///%7ByourDomain%7D/api_path' \ - --header 'authorization: Bearer YOUR_ACCESS_TOKEN_HERE' - ``` - - ```csharp C# lines - var client = new RestClient("http:///%7ByourDomain%7D/api_path"); - var request = new RestRequest(Method.GET); - request.AddHeader("authorization", "Bearer YOUR_ACCESS_TOKEN_HERE"); - IRestResponse response = client.Execute(request); - ``` - - ```go Go lines - package main - import ( - "fmt" - "net/http" - "io/ioutil" - ) - func main() { - url := "http:///%7ByourDomain%7D/api_path" - req, _ := http.NewRequest("get", url, nil) - req.Header.Add("authorization", "Bearer YOUR_ACCESS_TOKEN_HERE") - res, _ := http.DefaultClient.Do(req) - defer res.Body.Close() - body, _ := ioutil.ReadAll(res.Body) - fmt.Println(res) - fmt.Println(string(body)) - } - ``` - - ```java Java lines - HttpResponse response = Unirest.get("http:///%7ByourDomain%7D/api_path") - .header("authorization", "Bearer YOUR_ACCESS_TOKEN_HERE") - .asString(); - ``` - - ```javascript Node.JS lines - var axios = require("axios").default; - var options = { - method: 'get', - url: 'http:///%7ByourDomain%7D/api_path', - headers: {authorization: 'Bearer YOUR_ACCESS_TOKEN_HERE'} - }; - axios.request(options).then(function (response) { - console.log(response.data); - }).catch(function (error) { - console.error(error); - }); - ``` - - ```obj-c Obj-C lines - #import - NSDictionary *headers = @{ @"authorization": @"Bearer YOUR_ACCESS_TOKEN_HERE" }; - NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http:///%7ByourDomain%7D/api_path"] - cachePolicy:NSURLRequestUseProtocolCachePolicy - - timeoutInterval:10.0]; - - [request setHTTPMethod:@"get"]; - [request setAllHTTPHeaderFields:headers]; - NSURLSession *session = [NSURLSession sharedSession]; - NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request - completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { - - if (error) { - - NSLog(@"%@", error); - - } else { - - NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response; - - NSLog(@"%@", httpResponse); - - } - - }]; - - [dataTask resume]; - ``` - - ```php PHP lines - #import - NSDictionary *headers = @{ @"authorization": @"Bearer YOUR_ACCESS_TOKEN_HERE" }; - NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http:///%7ByourDomain%7D/api_path"] - cachePolicy:NSURLRequestUseProtocolCachePolicy - - timeoutInterval:10.0]; - - [request setHTTPMethod:@"get"]; - [request setAllHTTPHeaderFields:headers]; - NSURLSession *session = [NSURLSession sharedSession]; - NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request - completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { - - if (error) { - - NSLog(@"%@", error); - - } else { - - NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response; - - NSLog(@"%@", httpResponse); - - } - - }]; - - [dataTask resume]; - ``` - - ```python Python lines - import http.client - conn = http.client.HTTPConnection("") - headers = { 'authorization': "Bearer YOUR_ACCESS_TOKEN_HERE" } - conn.request("get", "/%7ByourDomain%7D/api_path", headers=headers) - res = conn.getresponse() - data = res.read() - print(data.decode("utf-8")) - ``` - - ```ruby Ruby lines - require 'uri' - require 'net/http' - url = URI("http:///%7ByourDomain%7D/api_path") - http = Net::HTTP.new(url.host, url.port) - request = Net::HTTP::Get.new(url) - request["authorization"] = 'Bearer YOUR_ACCESS_TOKEN_HERE' - response = http.request(request) - puts response.read_body - ``` - - ```swift Swift lines - import Foundation - let headers = ["authorization": "Bearer YOUR_ACCESS_TOKEN_HERE"] - let request = NSMutableURLRequest(url: NSURL(string: "http:///%7ByourDomain%7D/api_path")! as URL, - cachePolicy: .useProtocolCachePolicy, - - timeoutInterval: 10.0) - - request.httpMethod = "get" - request.allHTTPHeaderFields = headers - let session = URLSession.shared - let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in - if (error != nil) { - print(error) - - } else { - let httpResponse = response as? HTTPURLResponse - - print(httpResponse) - - } - }) - dataTask.resume() - ``` - - - - - ##### チェックポイント - アプリケーションの構成が完了したら、アプリケーションを実行して次の点を確認します: - GET /api/publicが認証を必要としない要求に使用できる。 - GET /api/privateが認証された要求に使用できる。 - GET /api/private-scopedがread:messagesスコープが付与されたアクセストークンを含む認証された要求に使用できる。 - -
    - - ## 次のステップ - - 成功です!ここまで来れば、アプリケーションにログイン、ログアウト、ユーザープロファイル情報が備わっているはずです。 - - これでクイックスタートチュートリアルは終了ですが、機能はまだまだたくさんあります。Auth0でできることについて詳しくは、以下をご覧ください。 - - * [Auth0 Dashboard](https://manage.auth0.com/#) - Auth0のテナントやアプリケーションを構成して管理する方法について説明します - * [express-oauth2-jwt-bearer SDK](https://github.com/auth0/node-oauth2-jwt-bearer/tree/main/packages/express-oauth2-jwt-bearer) - このチュートリアルで使用されているSDKをより詳しく説明します - * [Auth0 Marketplace](https://marketplace.auth0.com/) - Auth0の機能性を拡張できる各種の統合を見つけられます -
    - - - - - - - - - - - - - - - - - - - -
    +--- +title: "Express.js APIアプリケーションに認可を追加する" +permalink: "interactive" +'description': "このガイドは、新規または既存のExpress.js APIアプリケーションにexpress-oauth2-jwt-bearerパッケージを使ってAuth0を統合する方法を説明します。" +'og:title': "Express.js APIアプリケーションに認可を追加する" +'og:description': "このガイドは、新規または既存のExpress.js APIアプリケーションにexpress-oauth2-jwt-bearerパッケージを使ってAuth0を統合する方法を説明します。" +'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/node.png" +'twitter:title': "Express.js APIアプリケーションに認可を追加する" +'twitter:description': "このガイドは、新規または既存のExpress.js APIアプリケーションにexpress-oauth2-jwt-bearerパッケージを使ってAuth0を統合する方法を説明します。" +sidebarTitle: Node (Express) API +--- + +import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; +import { LoggedInForm } from "/snippets/Login.jsx"; +import Server from "/snippets/quickstart/backend/nodejs/server.js.mdx"; +import Server2 from "/snippets/quickstart/backend/nodejs/server.js2.mdx"; + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + +export const sections = [ + { id: "アクセス許可を定義する", title: "アクセス許可を定義する" }, + { id: "依存関係をインストールする", title: "依存関係をインストールする" }, + { id: "ミドルウェアを構成する", title: "ミドルウェアを構成する" }, + { id: "apiエンドポイントを保護する", title: "APIエンドポイントを保護する" } +] + + + + このガイドは、新規または既存のExpress.js APIアプリケーションに`express-oauth2-jwt-bearer`パッケージを使ってAuth0を統合する方法を説明します。 + + Auth0 DashboardでAPIをまだ作成していない場合は、対話型のセレクターを使ってAuth0 APIを新規作成します。そうでない場合は、既存のプロジェクトAPIを選択します。 + + Auth0 Dashboardを使って初めてAPIをセットアップする場合には、[使用の開始ガイド](/docs/ja-jp/get-started/auth0-overview/set-up-apis)を確認してください。それぞれのAuth0 APIにはAPI識別子があり、アプリケーションにアクセストークンの検証で使用されます。 + + + **Auth0を初めてご利用ですか?** [Auth0の仕組み](/docs/ja-jp/overview)と、OAuth 2.0フレームワークを用いた[API認証と認可の実装](/docs/ja-jp/api-auth)について説明します。 + + +
    + アクセス許可は、ユーザーの代わりに、提供されたアクセストークンを使ってどのようにしてリソースにアクセスできるのかを定義できるようにします。たとえば、ユーザーがマネージャーアクセスレベルを持つ場合には、`messages`リソースに対して読み出しアクセスを付与し、管理者アクセスレベルを持つ場合には、書き込みアクセスを付与することができます。 + + Auth0 Dashboardの[[APIs]](https://manage.auth0.com/#/apis)セクションにある**[Permissions(権限)]** ビューで使用可能なアクセス許可を定義することができます。 + + ![null](/docs/images/ja-jp/cdy7uua7fh8z/5EnGfdqLVZ8fuIxbUn7gm1/ee4278d6ae1910497771f3b9762c86f8/Quickstarts_API.png) + + + 以下の例では`read:messages`スコープを使用します。 + +
    + +
    + まず、`npm`でSDKをインストールします。 + + ```bash + npm install --save express-oauth2-jwt-bearer + ``` +
    + +
    + ドメインとAPI識別子を使って、`express-oauth2-jwt-bearer`を構成します。 + + 右に示した`checkJwt`ミドルウェアは、要求に含まれるユーザーのアクセストークンが有効かを確認します。トークンが有効でない場合、ユーザーがエンドポイントにアクセスしようとすると、「401 Authorization」というエラーが発生します。 + + ミドルウェアは、トークンに要求されたリソースにアクセスするだけの十分なスコープがあるかを確認しません。 +
    + +
    + 有効なJWTを必須して個々のルートを保護するには、`express-oauth2-jwt-bearer`から構築された`checkJwt`ミドルウェアでルートを構成します。 + + 特定のスコープを検索するために、個々のルートを構成することができます。これを実現するには、`requiresScope`メソッドで別のミドルウェアをセットアップします。必要なスコープを提供し、認可を追加したいルートにミドルウェアを適用します。 + + `checkJwt`と`requiredScopes`ミドルウェアを保護したいルートに渡します。 + + この構成では、`read:messages`スコープを持つアクセストークンのみがエンドポイントにアクセスすることができます。 + + ### APIを呼び出す + + APIを呼び出すにはアクセストークンが必要です。テスト用のアクセストークンは、[API設定](https://manage.auth0.com/#/apis)の**[Test(テスト)]** ビューから取得することができます。 + + ![null](/docs/images/ja-jp/cdy7uua7fh8z/5HUMcKGXoNOvdJNXFI73oi/f50dd78093814054a81903d1e478f3aa/API_access_tokens.png) + + 要求の`Authorization`ヘッダーにアクセストークンを指定します。 + + + ```bash cURL lines + curl --request get \ + --url 'http:///%7ByourDomain%7D/api_path' \ + --header 'authorization: Bearer YOUR_ACCESS_TOKEN_HERE' + ``` + + ```csharp C# lines + var client = new RestClient("http:///%7ByourDomain%7D/api_path"); + var request = new RestRequest(Method.GET); + request.AddHeader("authorization", "Bearer YOUR_ACCESS_TOKEN_HERE"); + IRestResponse response = client.Execute(request); + ``` + + ```go Go lines + package main + import ( + "fmt" + "net/http" + "io/ioutil" + ) + func main() { + url := "http:///%7ByourDomain%7D/api_path" + req, _ := http.NewRequest("get", url, nil) + req.Header.Add("authorization", "Bearer YOUR_ACCESS_TOKEN_HERE") + res, _ := http.DefaultClient.Do(req) + defer res.Body.Close() + body, _ := ioutil.ReadAll(res.Body) + fmt.Println(res) + fmt.Println(string(body)) + } + ``` + + ```java Java lines + HttpResponse response = Unirest.get("http:///%7ByourDomain%7D/api_path") + .header("authorization", "Bearer YOUR_ACCESS_TOKEN_HERE") + .asString(); + ``` + + ```javascript Node.JS lines + var axios = require("axios").default; + var options = { + method: 'get', + url: 'http:///%7ByourDomain%7D/api_path', + headers: {authorization: 'Bearer YOUR_ACCESS_TOKEN_HERE'} + }; + axios.request(options).then(function (response) { + console.log(response.data); + }).catch(function (error) { + console.error(error); + }); + ``` + + ```obj-c Obj-C lines + #import + NSDictionary *headers = @{ @"authorization": @"Bearer YOUR_ACCESS_TOKEN_HERE" }; + NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http:///%7ByourDomain%7D/api_path"] + cachePolicy:NSURLRequestUseProtocolCachePolicy + + timeoutInterval:10.0]; + + [request setHTTPMethod:@"get"]; + [request setAllHTTPHeaderFields:headers]; + NSURLSession *session = [NSURLSession sharedSession]; + NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request + completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { + + if (error) { + + NSLog(@"%@", error); + + } else { + + NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response; + + NSLog(@"%@", httpResponse); + + } + + }]; + + [dataTask resume]; + ``` + + ```php PHP lines + #import + NSDictionary *headers = @{ @"authorization": @"Bearer YOUR_ACCESS_TOKEN_HERE" }; + NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http:///%7ByourDomain%7D/api_path"] + cachePolicy:NSURLRequestUseProtocolCachePolicy + + timeoutInterval:10.0]; + + [request setHTTPMethod:@"get"]; + [request setAllHTTPHeaderFields:headers]; + NSURLSession *session = [NSURLSession sharedSession]; + NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request + completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { + + if (error) { + + NSLog(@"%@", error); + + } else { + + NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response; + + NSLog(@"%@", httpResponse); + + } + + }]; + + [dataTask resume]; + ``` + + ```python Python lines + import http.client + conn = http.client.HTTPConnection("") + headers = { 'authorization': "Bearer YOUR_ACCESS_TOKEN_HERE" } + conn.request("get", "/%7ByourDomain%7D/api_path", headers=headers) + res = conn.getresponse() + data = res.read() + print(data.decode("utf-8")) + ``` + + ```ruby Ruby lines + require 'uri' + require 'net/http' + url = URI("http:///%7ByourDomain%7D/api_path") + http = Net::HTTP.new(url.host, url.port) + request = Net::HTTP::Get.new(url) + request["authorization"] = 'Bearer YOUR_ACCESS_TOKEN_HERE' + response = http.request(request) + puts response.read_body + ``` + + ```swift Swift lines + import Foundation + let headers = ["authorization": "Bearer YOUR_ACCESS_TOKEN_HERE"] + let request = NSMutableURLRequest(url: NSURL(string: "http:///%7ByourDomain%7D/api_path")! as URL, + cachePolicy: .useProtocolCachePolicy, + + timeoutInterval: 10.0) + + request.httpMethod = "get" + request.allHTTPHeaderFields = headers + let session = URLSession.shared + let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in + if (error != nil) { + print(error) + + } else { + let httpResponse = response as? HTTPURLResponse + + print(httpResponse) + + } + }) + dataTask.resume() + ``` + + + + + ##### チェックポイント + アプリケーションの構成が完了したら、アプリケーションを実行して次の点を確認します: + GET /api/publicが認証を必要としない要求に使用できる。 + GET /api/privateが認証された要求に使用できる。 + GET /api/private-scopedがread:messagesスコープが付与されたアクセストークンを含む認証された要求に使用できる。 + +
    + + ## 次のステップ + + 成功です!ここまで来れば、アプリケーションにログイン、ログアウト、ユーザープロファイル情報が備わっているはずです。 + + これでクイックスタートチュートリアルは終了ですが、機能はまだまだたくさんあります。Auth0でできることについて詳しくは、以下をご覧ください。 + + * [Auth0 Dashboard](https://manage.auth0.com/#) - Auth0のテナントやアプリケーションを構成して管理する方法について説明します + * [express-oauth2-jwt-bearer SDK](https://github.com/auth0/node-oauth2-jwt-bearer/tree/main/packages/express-oauth2-jwt-bearer) - このチュートリアルで使用されているSDKをより詳しく説明します + * [Auth0 Marketplace](https://marketplace.auth0.com/) - Auth0の機能性を拡張できる各種の統合を見つけられます +
    + + + + + + + + + + + + + + + + + + + +
    diff --git a/main/docs/ja-jp/quickstart/backend/php/interactive.mdx b/main/docs/ja-jp/quickstart/backend/php/interactive.mdx index ab75bf4cc..7c70eeb08 100644 --- a/main/docs/ja-jp/quickstart/backend/php/interactive.mdx +++ b/main/docs/ja-jp/quickstart/backend/php/interactive.mdx @@ -1,171 +1,173 @@ ---- -title: "PHPアプリケーションに認可を追加する" -permalink: "interactive" -'description': "このガイドは、Auth0 PHP SDKを使ってAuth0を統合し、トークンベースの認可の追加とアプリケーションルートの保護を行う方法について説明します。" -'og:title': "PHPアプリケーションに認可を追加する" -'og:description': "このガイドは、Auth0 PHP SDKを使ってAuth0を統合し、トークンベースの認可の追加とアプリケーションルートの保護を行う方法について説明します。" -'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/php.png" -'twitter:title': "PHPアプリケーションに認可を追加する" -'twitter:description': "このガイドは、Auth0 PHP SDKを使ってAuth0を統合し、トークンベースの認可の追加とアプリケーションルートの保護を行う方法について説明します。" -sidebarTitle: PHP API ---- - -import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; -import { LoggedInForm } from "/snippets/Login.jsx"; -import Index from "/snippets/quickstart/backend/php/index.php.mdx"; -import Index2 from "/snippets/quickstart/backend/php/index.php2.mdx"; -import Router from "/snippets/quickstart/backend/php/router.php.mdx"; -import Router2 from "/snippets/quickstart/backend/php/router.php2.mdx"; -import Router3 from "/snippets/quickstart/backend/php/router.php3.mdx"; - -export const sections = [ - { id: "auth0を構成する", title: "Auth0を構成する" }, - { id: "auth0-php-sdkをインストールする", title: "Auth0 PHP SDKをインストールする" }, - { id: "ベアラートークンをリッスンする", title: "ベアラートークンをリッスンする" }, - { id: "ルートを作成-構成する", title: "ルートを作成・構成する" }, - { id: "エンドポイント認可を構成する", title: "エンドポイント認可を構成する" }, - { id: "スコープで認可する", title: "スコープで認可する" } -] - - - - Auth0を使用すると、アプリケーションに手軽にトークンベースのエンドポイント認可を追加することができます。このガイドは、Auth0 PHP SDKを使ってAuth0を統合し、トークンベースの認可の追加とアプリケーションルートの保護を行う方法について説明します。 - - このクイックスタートを使用するには、以下の手順に従います: - - - Auth0の無料アカウントにサインアップするか、Auth0にログインします。 - - Auth0に統合したいPHPプロジェクトを用意します。または、ログインした後に、サンプルアプリケーションを表示してダウンロードすることもできます。 - -
    - Auth0のサービスを利用するには、Auth0 Dashboadに登録済みのアプリケーションがある必要があります。Auth0アプリケーションは、プロジェクトに対してどのように認証が動作して欲しいかを構成する場所です。 - - ### アプリケーションを構成する - - 対話型のセレクターを使ってAuth0アプリケーションを新規作成するか、統合したいプロジェクトを表す既存のアプリケーションを選択します。Auth0のすべてのアプリケーションには英数字からなる一意のクライアントIDが割り当てられており、アプリケーションのコードがSDKを通じてAuth0 APIを呼び出す際に使用されます。 - - このクイックスタートを使って構成されたすべての設定は、[Dashboard](https://manage.auth0.com/#/)のアプリケーションを自動更新します。今後、アプリケーションの管理もDashboardで行えます。 - - 代わりに完了済みの構成を見てみたい場合は、サンプルアプリケーションをご覧ください。 - - ### APIを構成する - - 同様に、Auth0 APIを新規作成するか、[Dashboard](https://manage.auth0.com/#/)から統合するプロジェクトを表す既存のAPIを使用する必要があります。APIに一意の識別子を選択して記録します。以下のアプリケーションを構成するには、その識別子が必要です。 -
    - -
    - PHPアプリで、Auth0の認証・認可を手軽に実装できるように、Auth0は[PHP SDK](https://github.com/auth0/auth0-PHP)(Auth0-PHP)を提供しています。 - - Auth0 PHP SDKでは、ネットワーク要求を管理するために、[PSR-17](https://www.php-fig.org/psr/psr-17/)と[PSR-18](https://www.php-fig.org/psr/psr-18/)対応HTTPライブラリーをインストールする必要があります。ライブラリーがない場合は、ターミナルで以下のコマンドを実行して、信頼できる選択肢をインストールすることができます: - - ``` - cd - composer require symfony/http-client nyholm/psr7 - ``` - - ターミナルで以下のコマンドを実行してAuth0 PHP SDKをインストールします: - - ``` - composer require auth0/auth0-php - ``` - - ### Auth0 SDKを構成する - - SDKが正しく機能するためには、次のプロパティを初期化中にAuth0 SDKで設定しなければなりません: - - - `strategy`:アプリのユースケースでSDKの動作を導くのに役立ちます。この場合は、以下の定数に設定します。 - - `Auth0\SDK\Configuration\SdkConfiguration::STRATEGY_API` - - domain:Auth0テナントのドメインです。通常、Auth0 Dashboardにあるアプリケーションの[Settings(設定)]の[Domain(ドメイン)]フィールドで確認できます。カスタムドメインを使用している場合は、この値をカスタムドメインの値に設定してください。 - - clientId:このクイックスタートで前にセットアップした、Auth0アプリケーションのIDです。Auth0 Dashboardにあるアプリケーションの[Settings(設定)]の[Client ID(クライアントID)]フィールドで確認できます。 - - clientSecret:このクイックスタートで前にセットアップしたAuth0アプリケーションのシークレットです。Auth0 Dashboardにあるアプリケーションの[Settings(設定)]の[Client Secret(クライアントシークレット)]フィールドにあります。 - - audience:上で登録したAuth0 APIの識別子です。配列として指定されている必要があります。 - - - ##### チェックポイント - Auth0 SDKが正しく構成されました。アプリケーションを実行して次の点を確認します: - SDKが正しく初期化している。 - アプリケーションがAuth0に関連したエラーを投入していない。 - -
    - -
    - 次に、ベアラートークンを取得し処理するためにアプリケーションを拡張します。ベアラートークンはAPIに提供されるアクセストークンで、ユーザーに代わってクライアントから要求されます。アクセストークンは、アプリケーションでルートへのアクセスを承認または拒否します。これは、エンドポイント認可と呼ばれます。 - - 要求からアクセストークンを取得する最も簡単な方法は、PHP SDKの`getBearerToken()`メソッドを使用するものです。このメソッドは、GETパラメーター、POST本文、要求ヘッダー、および他のソースからトークンを取得します。この場合、PHP SDKは`token`パラメーターのGET要求、またはHTTP `Authorization`ヘッダーから渡されたトークンを処理します。 -
    - -
    - 次に、受信する要求をアプリケーションにダイレクトするために、ルーティングライブラリーをインストールします。これは必須手順ではありませんが、本クイックスタートの目的上、アプリケーション構造が簡略化されます。 - - ``` - composer require steampixel/simple-php-router - ``` - - アプリケーションで`router.php`と呼ばれる新規ファイルを作成し、ルートを定義します。**router.php** タブにある、右のインタラクティブパネルからコードをコピーします。 -
    - -
    - Auth0アプリケーションとAuth0 PHP SDKを構成し、アプリケーションで要求からベアラートークンを取得したら、次の手順はプロジェクトにエンドポイント認可をセットアップすることです。上で実装した`getBearerToken()`メソッドは、要求のアクセスに関する詳細を含む`Token`クラスを返します。 - - `getBearerToken()`メソッドは受信要求を自動的に検証・確認するため、アプリケーションはメソッドの応答を評価することで、アクセストークンの詳細を判定します。応答がnullの場合、提供される有効なトークンはありません。そうでない場合は、応答の内容を検査し、要求の詳細を確認してください。 - - 右のインタラクティブパネルで、応答がnullであるかどうかをチェックし、`/api/private`ルートへのアクセスをフィルターすることができます。 -
    - -
    - アクセストークンで要求されたスコープに基づいて、特定のルートへのアクセスをフィルターしたい場合もあるでしょう。右のインタラクティブパネルに示すように、`getBearerToken()`メソッドの応答から'scope'プロパティのコンテンツを評価し、アクセストークンで付与されたスコープをチェックします。 -
    - - ## 次のステップ - - 成功です!ここまで来れば、アプリケーションにログイン、ログアウト、ユーザープロファイル情報が備わっているはずです。 - - これでクイックスタートチュートリアルは終了ですが、機能はまだまだたくさんあります。Auth0でできることについて詳しくは、以下をご覧ください。 - - * [Auth0 Dashboard](https://manage.auth0.com/#) - Auth0のテナントやアプリケーションを構成して管理する方法について説明します - * [Auth0-PHP SDK](https://github.com/auth0/auth0-php) - このチュートリアルで使用されているSDKをより詳しく説明します - * [Auth0 Marketplace](https://marketplace.auth0.com/) - Auth0の機能性を拡張できる各種の統合を見つけられます -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    +--- +title: "PHPアプリケーションに認可を追加する" +permalink: "interactive" +'description': "このガイドは、Auth0 PHP SDKを使ってAuth0を統合し、トークンベースの認可の追加とアプリケーションルートの保護を行う方法について説明します。" +'og:title': "PHPアプリケーションに認可を追加する" +'og:description': "このガイドは、Auth0 PHP SDKを使ってAuth0を統合し、トークンベースの認可の追加とアプリケーションルートの保護を行う方法について説明します。" +'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/php.png" +'twitter:title': "PHPアプリケーションに認可を追加する" +'twitter:description': "このガイドは、Auth0 PHP SDKを使ってAuth0を統合し、トークンベースの認可の追加とアプリケーションルートの保護を行う方法について説明します。" +sidebarTitle: PHP API +--- + +import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; +import { LoggedInForm } from "/snippets/Login.jsx"; +import Index from "/snippets/quickstart/backend/php/index.php.mdx"; +import Index2 from "/snippets/quickstart/backend/php/index.php2.mdx"; +import Router from "/snippets/quickstart/backend/php/router.php.mdx"; +import Router2 from "/snippets/quickstart/backend/php/router.php2.mdx"; +import Router3 from "/snippets/quickstart/backend/php/router.php3.mdx"; + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + +export const sections = [ + { id: "auth0を構成する", title: "Auth0を構成する" }, + { id: "auth0-php-sdkをインストールする", title: "Auth0 PHP SDKをインストールする" }, + { id: "ベアラートークンをリッスンする", title: "ベアラートークンをリッスンする" }, + { id: "ルートを作成-構成する", title: "ルートを作成・構成する" }, + { id: "エンドポイント認可を構成する", title: "エンドポイント認可を構成する" }, + { id: "スコープで認可する", title: "スコープで認可する" } +] + + + + Auth0を使用すると、アプリケーションに手軽にトークンベースのエンドポイント認可を追加することができます。このガイドは、Auth0 PHP SDKを使ってAuth0を統合し、トークンベースの認可の追加とアプリケーションルートの保護を行う方法について説明します。 + + このクイックスタートを使用するには、以下の手順に従います: + + - Auth0の無料アカウントにサインアップするか、Auth0にログインします。 + - Auth0に統合したいPHPプロジェクトを用意します。または、ログインした後に、サンプルアプリケーションを表示してダウンロードすることもできます。 + +
    + Auth0のサービスを利用するには、Auth0 Dashboadに登録済みのアプリケーションがある必要があります。Auth0アプリケーションは、プロジェクトに対してどのように認証が動作して欲しいかを構成する場所です。 + + ### アプリケーションを構成する + + 対話型のセレクターを使ってAuth0アプリケーションを新規作成するか、統合したいプロジェクトを表す既存のアプリケーションを選択します。Auth0のすべてのアプリケーションには英数字からなる一意のクライアントIDが割り当てられており、アプリケーションのコードがSDKを通じてAuth0 APIを呼び出す際に使用されます。 + + このクイックスタートを使って構成されたすべての設定は、[Dashboard](https://manage.auth0.com/#/)のアプリケーションを自動更新します。今後、アプリケーションの管理もDashboardで行えます。 + + 代わりに完了済みの構成を見てみたい場合は、サンプルアプリケーションをご覧ください。 + + ### APIを構成する + + 同様に、Auth0 APIを新規作成するか、[Dashboard](https://manage.auth0.com/#/)から統合するプロジェクトを表す既存のAPIを使用する必要があります。APIに一意の識別子を選択して記録します。以下のアプリケーションを構成するには、その識別子が必要です。 +
    + +
    + PHPアプリで、Auth0の認証・認可を手軽に実装できるように、Auth0は[PHP SDK](https://github.com/auth0/auth0-PHP)(Auth0-PHP)を提供しています。 + + Auth0 PHP SDKでは、ネットワーク要求を管理するために、[PSR-17](https://www.php-fig.org/psr/psr-17/)と[PSR-18](https://www.php-fig.org/psr/psr-18/)対応HTTPライブラリーをインストールする必要があります。ライブラリーがない場合は、ターミナルで以下のコマンドを実行して、信頼できる選択肢をインストールすることができます: + + ``` + cd + composer require symfony/http-client nyholm/psr7 + ``` + + ターミナルで以下のコマンドを実行してAuth0 PHP SDKをインストールします: + + ``` + composer require auth0/auth0-php + ``` + + ### Auth0 SDKを構成する + + SDKが正しく機能するためには、次のプロパティを初期化中にAuth0 SDKで設定しなければなりません: + + - `strategy`:アプリのユースケースでSDKの動作を導くのに役立ちます。この場合は、以下の定数に設定します。 + + `Auth0\SDK\Configuration\SdkConfiguration::STRATEGY_API` + - domain:Auth0テナントのドメインです。通常、Auth0 Dashboardにあるアプリケーションの[Settings(設定)]の[Domain(ドメイン)]フィールドで確認できます。カスタムドメインを使用している場合は、この値をカスタムドメインの値に設定してください。 + - clientId:このクイックスタートで前にセットアップした、Auth0アプリケーションのIDです。Auth0 Dashboardにあるアプリケーションの[Settings(設定)]の[Client ID(クライアントID)]フィールドで確認できます。 + - clientSecret:このクイックスタートで前にセットアップしたAuth0アプリケーションのシークレットです。Auth0 Dashboardにあるアプリケーションの[Settings(設定)]の[Client Secret(クライアントシークレット)]フィールドにあります。 + - audience:上で登録したAuth0 APIの識別子です。配列として指定されている必要があります。 + + + ##### チェックポイント + Auth0 SDKが正しく構成されました。アプリケーションを実行して次の点を確認します: + SDKが正しく初期化している。 + アプリケーションがAuth0に関連したエラーを投入していない。 + +
    + +
    + 次に、ベアラートークンを取得し処理するためにアプリケーションを拡張します。ベアラートークンはAPIに提供されるアクセストークンで、ユーザーに代わってクライアントから要求されます。アクセストークンは、アプリケーションでルートへのアクセスを承認または拒否します。これは、エンドポイント認可と呼ばれます。 + + 要求からアクセストークンを取得する最も簡単な方法は、PHP SDKの`getBearerToken()`メソッドを使用するものです。このメソッドは、GETパラメーター、POST本文、要求ヘッダー、および他のソースからトークンを取得します。この場合、PHP SDKは`token`パラメーターのGET要求、またはHTTP `Authorization`ヘッダーから渡されたトークンを処理します。 +
    + +
    + 次に、受信する要求をアプリケーションにダイレクトするために、ルーティングライブラリーをインストールします。これは必須手順ではありませんが、本クイックスタートの目的上、アプリケーション構造が簡略化されます。 + + ``` + composer require steampixel/simple-php-router + ``` + + アプリケーションで`router.php`と呼ばれる新規ファイルを作成し、ルートを定義します。**router.php** タブにある、右のインタラクティブパネルからコードをコピーします。 +
    + +
    + Auth0アプリケーションとAuth0 PHP SDKを構成し、アプリケーションで要求からベアラートークンを取得したら、次の手順はプロジェクトにエンドポイント認可をセットアップすることです。上で実装した`getBearerToken()`メソッドは、要求のアクセスに関する詳細を含む`Token`クラスを返します。 + + `getBearerToken()`メソッドは受信要求を自動的に検証・確認するため、アプリケーションはメソッドの応答を評価することで、アクセストークンの詳細を判定します。応答がnullの場合、提供される有効なトークンはありません。そうでない場合は、応答の内容を検査し、要求の詳細を確認してください。 + + 右のインタラクティブパネルで、応答がnullであるかどうかをチェックし、`/api/private`ルートへのアクセスをフィルターすることができます。 +
    + +
    + アクセストークンで要求されたスコープに基づいて、特定のルートへのアクセスをフィルターしたい場合もあるでしょう。右のインタラクティブパネルに示すように、`getBearerToken()`メソッドの応答から'scope'プロパティのコンテンツを評価し、アクセストークンで付与されたスコープをチェックします。 +
    + + ## 次のステップ + + 成功です!ここまで来れば、アプリケーションにログイン、ログアウト、ユーザープロファイル情報が備わっているはずです。 + + これでクイックスタートチュートリアルは終了ですが、機能はまだまだたくさんあります。Auth0でできることについて詳しくは、以下をご覧ください。 + + * [Auth0 Dashboard](https://manage.auth0.com/#) - Auth0のテナントやアプリケーションを構成して管理する方法について説明します + * [Auth0-PHP SDK](https://github.com/auth0/auth0-php) - このチュートリアルで使用されているSDKをより詳しく説明します + * [Auth0 Marketplace](https://marketplace.auth0.com/) - Auth0の機能性を拡張できる各種の統合を見つけられます +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    diff --git a/main/docs/ja-jp/quickstart/backend/python/interactive.mdx b/main/docs/ja-jp/quickstart/backend/python/interactive.mdx index 2163a2a98..d72fce39e 100644 --- a/main/docs/ja-jp/quickstart/backend/python/interactive.mdx +++ b/main/docs/ja-jp/quickstart/backend/python/interactive.mdx @@ -1,294 +1,296 @@ ---- -title: "Flask APIアプリケーションに認可を追加する" -permalink: "interactive" -'description': "このガイドは、Flaskを使ってビルドされた新規または既存のPython APIにAuth0を統合する方法を説明します。" -'og:title': "Flask APIアプリケーションに認可を追加する" -'og:description': "このガイドは、Flaskを使ってビルドされた新規または既存のPython APIにAuth0を統合する方法を説明します。" -'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/python.png" -'twitter:title': "Flask APIアプリケーションに認可を追加する" -'twitter:description': "このガイドは、Flaskを使ってビルドされた新規または既存のPython APIにAuth0を統合する方法を説明します。" -sidebarTitle: Python API ---- - -import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; -import { LoggedInForm } from "/snippets/Login.jsx"; -import Validator from "/snippets/quickstart/backend/python/validator.py.mdx"; -import Server from "/snippets/quickstart/backend/python/server.py.mdx"; - -export const sections = [ - { id: "アクセス許可を定義する", title: "アクセス許可を定義する" }, - { id: "依存関係をインストールする", title: "依存関係をインストールする" }, - { id: "jwtバリデーターを作成する", title: "JWTバリデーターを作成する" }, - { id: "flaskアプリケーションを作成する", title: "Flaskアプリケーションを作成する" } -] - - - - このガイドは、[Flask](https://flask.palletsprojects.com/)を使ってビルドされた新規または既存のPython APIにAuth0を統合する方法を説明します。 - - Auth0 DashboardでAPIをまだ作成していない場合は、対話型のセレクターを使ってAuth0 APIを新規作成します。そうでない場合は、統合したいプロジェクトを表す既存のAPIを選択することができます。 - - または、Auth0 Dashboardを使って初めてAPIをセットアップする方法を[使用の開始ガイド](/docs/ja-jp/get-started/auth0-overview/set-up-apis)で確認することもできます。 - - Auth0にあるAPIはそれぞれAPI識別子を使って構成され、アプリケーションのコードはAPI識別子をオーディエンスとしてアクセストークンを検証します。 - - - **Auth0を初めてご利用ですか?** [Auth0の仕組み](/docs/ja-jp/overview)と、OAuth 2.0フレームワークを用いた[API認証と認可の実装](/docs/ja-jp/api-auth)について説明します。 - - -
    - アクセス許可は、ユーザーの代わりに、提供されたアクセストークンを使ってどのようにしてリソースにアクセスできるのかを定義できるようにします。たとえば、ユーザーがマネージャーアクセスレベルを持つ場合には、`messages`リソースに対して読み出しアクセスを付与し、管理者アクセスレベルを持つ場合には、書き込みアクセスを付与することができます。 - - Auth0 Dashboardの[[APIs]](https://manage.auth0.com/#/apis)セクションにある**[Permissions(権限)]** ビューで使用可能なアクセス許可を定義することができます。 - - ![[Auth0 Dashboard]>[Applications(アプリケーション)]>[APIs]>[Specific API(特定のAPI]>[Permissions(権限)]タブ](/docs/images/ja-jp/cdy7uua7fh8z/1s3Yp5zqJiKiSWqbPSezNO/acef814282795bef6921535f044f96e9/Quickstarts_API.png) - - - 以下の例では`read:messages`スコープを使用します。 - -
    - -
    - `requirements.txt`に次の依存関係を追加します: - - ``` - # /requirements.txt - flask - - Authlib - ``` -
    - -
    - [Authlib](https://github.com/lepture/authlib)という名前のライブラリーを使用して、[ResourceProtector](https://docs.authlib.org/en/latest/flask/1/resource-server.html)を作成します。これは[Flaskデコレーター](https://flask.palletsprojects.com/patterns/viewdecorators/)の一種で、該当するバリデーターを使ってリソース(APIルート)を保護します。 - - バリデーターは、リソースに渡すアクセストークンに有効な署名とクレームがあることを検証します。 - - AuthLibの`JWTBearerTokenValidator`バリデーターに多少の変更を加えて、[アクセストークンの検証](/docs/ja-jp/secure/tokens/access-tokens/validate-access-tokens)要件が満たされるようにします。 - - `Auth0JWTBearerTokenValidator`を作成するには、`domain`と`audience`(API識別子)に渡すことが必要です。そうすると、トークンの署名を検証するのに必要な公開鍵が取得され、`JWTBearerTokenValidator`クラスに渡されます。 - - そして、クラスの`claims_options`をオーバーライドし、トークンのexpiry、audience、issueクレームが要件を満たして有効であることを確認します。 -
    - -
    - 次に、3つのAPIルートを使ってFlaskアプリケーションを作成します。 - - - `/api/public`:認証を必要としないパブリックエンドポイントです。 - - `/api/private`:有効なJWTアクセストークンを必要とするプライベートエンドポイントです。 - - `/api/private-scoped`:与えられた`scope`を含む有効なJWTアクセストークンを必要とするプライベートエンドポイントです。 - - 保護されたルートには`require_auth`デコレーターがあり、これは、以前に作成した`Auth0JWTBearerTokenValidator`を使用する`ResourceProtector`です。 - - `Auth0JWTBearerTokenValidator`を作成するには、テナントのドメインと以前に作成したAPIのAPI識別子に渡します。 - - `private_scoped`ルートの`require_auth`デコレーターは、追加の引数である`"read:messages"`を受け付けます。これは、以前に作成したアクセス許可(スコープ)について、アクセストークンをチェックします。 - - ### APIを呼び出す - - APIを呼び出すにはアクセストークンが必要です。テスト用のアクセストークンは、[API設定](https://manage.auth0.com/#/apis)の**[Test(テスト)]** ビューから取得することができます。 - - ![[Auth0 Dashboard]>[Applications(アプリケーション)]>[API]>[Specific API(特定のAPI]>[Test(テスト)]タブ](/docs/images/ja-jp/cdy7uua7fh8z/6jeVBuypOGX5qMRXeJn5ow/dd20eb74e1e9079287762ce33dcf8e2d/Quickstart_Example_App_API.png) - - 要求の`Authorization`ヘッダーにアクセストークンを指定します。 - - - ```bash cURL lines - curl --request get \ - --url 'http:///%7ByourDomain%7D/api_path' \ - --header 'authorization: Bearer YOUR_ACCESS_TOKEN_HERE' - ``` - - ```csharp C# lines - var client = new RestClient("http:///%7ByourDomain%7D/api_path"); - var request = new RestRequest(Method.GET); - request.AddHeader("authorization", "Bearer YOUR_ACCESS_TOKEN_HERE"); - IRestResponse response = client.Execute(request); - ``` - - ```go Go lines - package main - import ( - "fmt" - "net/http" - "io/ioutil" - ) - func main() { - url := "http:///%7ByourDomain%7D/api_path" - req, _ := http.NewRequest("get", url, nil) - req.Header.Add("authorization", "Bearer YOUR_ACCESS_TOKEN_HERE") - res, _ := http.DefaultClient.Do(req) - defer res.Body.Close() - body, _ := ioutil.ReadAll(res.Body) - fmt.Println(res) - fmt.Println(string(body)) - } - ``` - - ```java Java lines - HttpResponse response = Unirest.get("http:///%7ByourDomain%7D/api_path") - .header("authorization", "Bearer YOUR_ACCESS_TOKEN_HERE") - .asString(); - ``` - - ```javascript Node.JS lines - var axios = require("axios").default; - var options = { - method: 'get', - url: 'http:///%7ByourDomain%7D/api_path', - headers: {authorization: 'Bearer YOUR_ACCESS_TOKEN_HERE'} - }; - axios.request(options).then(function (response) { - console.log(response.data); - }).catch(function (error) { - console.error(error); - }); - ``` - - ```obj-c Obj-C lines - #import - NSDictionary *headers = @{ @"authorization": @"Bearer YOUR_ACCESS_TOKEN_HERE" }; - NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http:///%7ByourDomain%7D/api_path"] - cachePolicy:NSURLRequestUseProtocolCachePolicy - - timeoutInterval:10.0]; - - [request setHTTPMethod:@"get"]; - [request setAllHTTPHeaderFields:headers]; - NSURLSession *session = [NSURLSession sharedSession]; - NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request - completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { - - if (error) { - - NSLog(@"%@", error); - - } else { - - NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response; - - NSLog(@"%@", httpResponse); - - } - - }]; - - [dataTask resume]; - ``` - - ```php PHP lines - #import - NSDictionary *headers = @{ @"authorization": @"Bearer YOUR_ACCESS_TOKEN_HERE" }; - NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http:///%7ByourDomain%7D/api_path"] - cachePolicy:NSURLRequestUseProtocolCachePolicy - - timeoutInterval:10.0]; - - [request setHTTPMethod:@"get"]; - [request setAllHTTPHeaderFields:headers]; - NSURLSession *session = [NSURLSession sharedSession]; - NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request - completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { - - if (error) { - - NSLog(@"%@", error); - - } else { - - NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response; - - NSLog(@"%@", httpResponse); - - } - - }]; - - [dataTask resume]; - ``` - - ```python Python lines - import http.client - conn = http.client.HTTPConnection("") - headers = { 'authorization': "Bearer YOUR_ACCESS_TOKEN_HERE" } - conn.request("get", "/%7ByourDomain%7D/api_path", headers=headers) - res = conn.getresponse() - data = res.read() - print(data.decode("utf-8")) - ``` - - ```ruby Ruby lines - require 'uri' - require 'net/http' - url = URI("http:///%7ByourDomain%7D/api_path") - http = Net::HTTP.new(url.host, url.port) - request = Net::HTTP::Get.new(url) - request["authorization"] = 'Bearer YOUR_ACCESS_TOKEN_HERE' - response = http.request(request) - puts response.read_body - ``` - - ```swift Swift lines - import Foundation - let headers = ["authorization": "Bearer YOUR_ACCESS_TOKEN_HERE"] - let request = NSMutableURLRequest(url: NSURL(string: "http:///%7ByourDomain%7D/api_path")! as URL, - cachePolicy: .useProtocolCachePolicy, - - timeoutInterval: 10.0) - - request.httpMethod = "get" - request.allHTTPHeaderFields = headers - let session = URLSession.shared - let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in - if (error != nil) { - print(error) - - } else { - let httpResponse = response as? HTTPURLResponse - - print(httpResponse) - - } - }) - dataTask.resume() - ``` - - -
    - - ## 次のステップ - - 成功です!ここまで来れば、アプリケーションにログイン、ログアウト、ユーザープロファイル情報が備わっているはずです。 - - これでクイックスタートチュートリアルは終了ですが、機能はまだまだたくさんあります。Auth0でできることについて詳しくは、以下をご覧ください。 - - * [Auth0 Dashboard](https://manage.auth0.com/#) - Auth0のテナントやアプリケーションを構成して管理する方法について説明します - * [auth0-python SDK](https://github.com/auth0/auth0-python) - このチュートリアルで使用されているSDKをより詳しく説明します - * [Auth0 Marketplace](https://marketplace.auth0.com/) - Auth0の機能性を拡張できる各種の統合を見つけられます -
    - - - - - - - - - - - - - - - - - - - - - - - - - -
    +--- +title: "Flask APIアプリケーションに認可を追加する" +permalink: "interactive" +'description': "このガイドは、Flaskを使ってビルドされた新規または既存のPython APIにAuth0を統合する方法を説明します。" +'og:title': "Flask APIアプリケーションに認可を追加する" +'og:description': "このガイドは、Flaskを使ってビルドされた新規または既存のPython APIにAuth0を統合する方法を説明します。" +'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/python.png" +'twitter:title': "Flask APIアプリケーションに認可を追加する" +'twitter:description': "このガイドは、Flaskを使ってビルドされた新規または既存のPython APIにAuth0を統合する方法を説明します。" +sidebarTitle: Python API +--- + +import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; +import { LoggedInForm } from "/snippets/Login.jsx"; +import Validator from "/snippets/quickstart/backend/python/validator.py.mdx"; +import Server from "/snippets/quickstart/backend/python/server.py.mdx"; + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + +export const sections = [ + { id: "アクセス許可を定義する", title: "アクセス許可を定義する" }, + { id: "依存関係をインストールする", title: "依存関係をインストールする" }, + { id: "jwtバリデーターを作成する", title: "JWTバリデーターを作成する" }, + { id: "flaskアプリケーションを作成する", title: "Flaskアプリケーションを作成する" } +] + + + + このガイドは、[Flask](https://flask.palletsprojects.com/)を使ってビルドされた新規または既存のPython APIにAuth0を統合する方法を説明します。 + + Auth0 DashboardでAPIをまだ作成していない場合は、対話型のセレクターを使ってAuth0 APIを新規作成します。そうでない場合は、統合したいプロジェクトを表す既存のAPIを選択することができます。 + + または、Auth0 Dashboardを使って初めてAPIをセットアップする方法を[使用の開始ガイド](/docs/ja-jp/get-started/auth0-overview/set-up-apis)で確認することもできます。 + + Auth0にあるAPIはそれぞれAPI識別子を使って構成され、アプリケーションのコードはAPI識別子をオーディエンスとしてアクセストークンを検証します。 + + + **Auth0を初めてご利用ですか?** [Auth0の仕組み](/docs/ja-jp/overview)と、OAuth 2.0フレームワークを用いた[API認証と認可の実装](/docs/ja-jp/api-auth)について説明します。 + + +
    + アクセス許可は、ユーザーの代わりに、提供されたアクセストークンを使ってどのようにしてリソースにアクセスできるのかを定義できるようにします。たとえば、ユーザーがマネージャーアクセスレベルを持つ場合には、`messages`リソースに対して読み出しアクセスを付与し、管理者アクセスレベルを持つ場合には、書き込みアクセスを付与することができます。 + + Auth0 Dashboardの[[APIs]](https://manage.auth0.com/#/apis)セクションにある**[Permissions(権限)]** ビューで使用可能なアクセス許可を定義することができます。 + + ![[Auth0 Dashboard]>[Applications(アプリケーション)]>[APIs]>[Specific API(特定のAPI]>[Permissions(権限)]タブ](/docs/images/ja-jp/cdy7uua7fh8z/1s3Yp5zqJiKiSWqbPSezNO/acef814282795bef6921535f044f96e9/Quickstarts_API.png) + + + 以下の例では`read:messages`スコープを使用します。 + +
    + +
    + `requirements.txt`に次の依存関係を追加します: + + ``` + # /requirements.txt + flask + + Authlib + ``` +
    + +
    + [Authlib](https://github.com/lepture/authlib)という名前のライブラリーを使用して、[ResourceProtector](https://docs.authlib.org/en/latest/flask/1/resource-server.html)を作成します。これは[Flaskデコレーター](https://flask.palletsprojects.com/patterns/viewdecorators/)の一種で、該当するバリデーターを使ってリソース(APIルート)を保護します。 + + バリデーターは、リソースに渡すアクセストークンに有効な署名とクレームがあることを検証します。 + + AuthLibの`JWTBearerTokenValidator`バリデーターに多少の変更を加えて、[アクセストークンの検証](/docs/ja-jp/secure/tokens/access-tokens/validate-access-tokens)要件が満たされるようにします。 + + `Auth0JWTBearerTokenValidator`を作成するには、`domain`と`audience`(API識別子)に渡すことが必要です。そうすると、トークンの署名を検証するのに必要な公開鍵が取得され、`JWTBearerTokenValidator`クラスに渡されます。 + + そして、クラスの`claims_options`をオーバーライドし、トークンのexpiry、audience、issueクレームが要件を満たして有効であることを確認します。 +
    + +
    + 次に、3つのAPIルートを使ってFlaskアプリケーションを作成します。 + + - `/api/public`:認証を必要としないパブリックエンドポイントです。 + - `/api/private`:有効なJWTアクセストークンを必要とするプライベートエンドポイントです。 + - `/api/private-scoped`:与えられた`scope`を含む有効なJWTアクセストークンを必要とするプライベートエンドポイントです。 + + 保護されたルートには`require_auth`デコレーターがあり、これは、以前に作成した`Auth0JWTBearerTokenValidator`を使用する`ResourceProtector`です。 + + `Auth0JWTBearerTokenValidator`を作成するには、テナントのドメインと以前に作成したAPIのAPI識別子に渡します。 + + `private_scoped`ルートの`require_auth`デコレーターは、追加の引数である`"read:messages"`を受け付けます。これは、以前に作成したアクセス許可(スコープ)について、アクセストークンをチェックします。 + + ### APIを呼び出す + + APIを呼び出すにはアクセストークンが必要です。テスト用のアクセストークンは、[API設定](https://manage.auth0.com/#/apis)の**[Test(テスト)]** ビューから取得することができます。 + + ![[Auth0 Dashboard]>[Applications(アプリケーション)]>[API]>[Specific API(特定のAPI]>[Test(テスト)]タブ](/docs/images/ja-jp/cdy7uua7fh8z/6jeVBuypOGX5qMRXeJn5ow/dd20eb74e1e9079287762ce33dcf8e2d/Quickstart_Example_App_API.png) + + 要求の`Authorization`ヘッダーにアクセストークンを指定します。 + + + ```bash cURL lines + curl --request get \ + --url 'http:///%7ByourDomain%7D/api_path' \ + --header 'authorization: Bearer YOUR_ACCESS_TOKEN_HERE' + ``` + + ```csharp C# lines + var client = new RestClient("http:///%7ByourDomain%7D/api_path"); + var request = new RestRequest(Method.GET); + request.AddHeader("authorization", "Bearer YOUR_ACCESS_TOKEN_HERE"); + IRestResponse response = client.Execute(request); + ``` + + ```go Go lines + package main + import ( + "fmt" + "net/http" + "io/ioutil" + ) + func main() { + url := "http:///%7ByourDomain%7D/api_path" + req, _ := http.NewRequest("get", url, nil) + req.Header.Add("authorization", "Bearer YOUR_ACCESS_TOKEN_HERE") + res, _ := http.DefaultClient.Do(req) + defer res.Body.Close() + body, _ := ioutil.ReadAll(res.Body) + fmt.Println(res) + fmt.Println(string(body)) + } + ``` + + ```java Java lines + HttpResponse response = Unirest.get("http:///%7ByourDomain%7D/api_path") + .header("authorization", "Bearer YOUR_ACCESS_TOKEN_HERE") + .asString(); + ``` + + ```javascript Node.JS lines + var axios = require("axios").default; + var options = { + method: 'get', + url: 'http:///%7ByourDomain%7D/api_path', + headers: {authorization: 'Bearer YOUR_ACCESS_TOKEN_HERE'} + }; + axios.request(options).then(function (response) { + console.log(response.data); + }).catch(function (error) { + console.error(error); + }); + ``` + + ```obj-c Obj-C lines + #import + NSDictionary *headers = @{ @"authorization": @"Bearer YOUR_ACCESS_TOKEN_HERE" }; + NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http:///%7ByourDomain%7D/api_path"] + cachePolicy:NSURLRequestUseProtocolCachePolicy + + timeoutInterval:10.0]; + + [request setHTTPMethod:@"get"]; + [request setAllHTTPHeaderFields:headers]; + NSURLSession *session = [NSURLSession sharedSession]; + NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request + completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { + + if (error) { + + NSLog(@"%@", error); + + } else { + + NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response; + + NSLog(@"%@", httpResponse); + + } + + }]; + + [dataTask resume]; + ``` + + ```php PHP lines + #import + NSDictionary *headers = @{ @"authorization": @"Bearer YOUR_ACCESS_TOKEN_HERE" }; + NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http:///%7ByourDomain%7D/api_path"] + cachePolicy:NSURLRequestUseProtocolCachePolicy + + timeoutInterval:10.0]; + + [request setHTTPMethod:@"get"]; + [request setAllHTTPHeaderFields:headers]; + NSURLSession *session = [NSURLSession sharedSession]; + NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request + completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { + + if (error) { + + NSLog(@"%@", error); + + } else { + + NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response; + + NSLog(@"%@", httpResponse); + + } + + }]; + + [dataTask resume]; + ``` + + ```python Python lines + import http.client + conn = http.client.HTTPConnection("") + headers = { 'authorization': "Bearer YOUR_ACCESS_TOKEN_HERE" } + conn.request("get", "/%7ByourDomain%7D/api_path", headers=headers) + res = conn.getresponse() + data = res.read() + print(data.decode("utf-8")) + ``` + + ```ruby Ruby lines + require 'uri' + require 'net/http' + url = URI("http:///%7ByourDomain%7D/api_path") + http = Net::HTTP.new(url.host, url.port) + request = Net::HTTP::Get.new(url) + request["authorization"] = 'Bearer YOUR_ACCESS_TOKEN_HERE' + response = http.request(request) + puts response.read_body + ``` + + ```swift Swift lines + import Foundation + let headers = ["authorization": "Bearer YOUR_ACCESS_TOKEN_HERE"] + let request = NSMutableURLRequest(url: NSURL(string: "http:///%7ByourDomain%7D/api_path")! as URL, + cachePolicy: .useProtocolCachePolicy, + + timeoutInterval: 10.0) + + request.httpMethod = "get" + request.allHTTPHeaderFields = headers + let session = URLSession.shared + let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in + if (error != nil) { + print(error) + + } else { + let httpResponse = response as? HTTPURLResponse + + print(httpResponse) + + } + }) + dataTask.resume() + ``` + + +
    + + ## 次のステップ + + 成功です!ここまで来れば、アプリケーションにログイン、ログアウト、ユーザープロファイル情報が備わっているはずです。 + + これでクイックスタートチュートリアルは終了ですが、機能はまだまだたくさんあります。Auth0でできることについて詳しくは、以下をご覧ください。 + + * [Auth0 Dashboard](https://manage.auth0.com/#) - Auth0のテナントやアプリケーションを構成して管理する方法について説明します + * [auth0-python SDK](https://github.com/auth0/auth0-python) - このチュートリアルで使用されているSDKをより詳しく説明します + * [Auth0 Marketplace](https://marketplace.auth0.com/) - Auth0の機能性を拡張できる各種の統合を見つけられます +
    + + + + + + + + + + + + + + + + + + + + + + + + + +
    diff --git a/main/docs/ja-jp/quickstart/backend/rails/interactive.mdx b/main/docs/ja-jp/quickstart/backend/rails/interactive.mdx index 7e4ce4de1..cbb979cf8 100644 --- a/main/docs/ja-jp/quickstart/backend/rails/interactive.mdx +++ b/main/docs/ja-jp/quickstart/backend/rails/interactive.mdx @@ -1,352 +1,354 @@ ---- -title: "Ruby on Rails APIに認可を追加する" -permalink: "interactive" -'description': "このチュートリアルでは、カスタムAuth0Clientクラス内のjwt Gemを使って、アクセストークンの検証を実施します。" -'og:title': "Ruby on Rails APIに認可を追加する" -'og:description': "このチュートリアルでは、カスタムAuth0Clientクラス内のjwt Gemを使って、アクセストークンの検証を実施します。" -'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/rails.png" -'twitter:title': "Ruby on Rails APIに認可を追加する" -'twitter:description': "このチュートリアルでは、カスタムAuth0Clientクラス内のjwt Gemを使って、アクセストークンの検証を実施します。" -sidebarTitle: Ruby on Rails API ---- - -import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; -import { LoggedInForm } from "/snippets/Login.jsx"; -import ApplicationController from "/snippets/quickstart/backend/rails/application_controller.rb.mdx"; -import Auth0Client from "/snippets/quickstart/backend/rails/auth0_client.rb.mdx"; -import Secured from "/snippets/quickstart/backend/rails/secured.rb.mdx"; -import PublicController from "/snippets/quickstart/backend/rails/public_controller.rb.mdx"; -import PrivateController from "/snippets/quickstart/backend/rails/private_controller.rb.mdx"; - -export const sections = [ - { id: "アクセス許可を定義する", title: "アクセス許可を定義する" }, - { id: "依存関係をインストールする", title: "依存関係をインストールする" }, - { id: "auth0clientクラスを作成する", title: "Auth0Clientクラスを作成する" }, - { id: "secured-concernを定義する", title: "Secured concernを定義する" }, - { id: "applicationcontrollerにsecure-concernを含める", title: "ApplicationControllerにSecure concernを含める" }, - { id: "パブリックエンドポイントを作成する", title: "パブリックエンドポイントを作成する" }, - { id: "プライベートエンドポイントを作成する", title: "プライベートエンドポイントを作成する" } -] - - - - このチュートリアルでは、カスタム`Auth0Client`クラス内の[**jwt** ](https://github.com/jwt/ruby-jwt) Gemを使って、アクセストークンの検証を実施します。`Secured`と呼ばれるConcernを使って、受信アクセストークンからの認証を必要とするエンドポイントを認可します。 - - Auth0 DashboardでAPIをまだ作成していない場合は、対話型のセレクターを使ってAuth0 APIを新規作成します。そうでない場合は、プロジェクトに既存のAPIを選択します。 - - Auth0 Dashboardを使って初めてAPIをセットアップする場合には、[使用の開始ガイド](/docs/ja-jp/get-started/auth0-overview/set-up-apis)を確認してください。 - - それぞれのAuth0 APIにはAPI識別子があり、アプリケーションにアクセストークンの検証で使用されます。 - - - **Auth0を初めてご利用ですか?** [Auth0の仕組み](/docs/ja-jp/overview)と、OAuth 2.0フレームワークを用いた[API認証と認可の実装](/docs/ja-jp/api-auth)について説明します。 - - -
    - アクセス許可は、ユーザーの代わりに、提供されたアクセストークンを使ってどのようにしてリソースにアクセスできるのかを定義できるようにします。たとえば、ユーザーがマネージャーアクセスレベルを持つ場合には、`messages`リソースに対して読み出しアクセスを付与し、管理者アクセスレベルを持つ場合には、書き込みアクセスを付与することができます。 - - Auth0 Dashboardの[[APIs]](https://manage.auth0.com/#/apis)セクションにある**[Permissions(権限)]** ビューで使用可能なアクセス許可を定義することができます。 - - ![[Auth0 Dashboard]>[Applications(アプリケーション)]>[APIs]>[Specific API(特定のAPI]>[Permissions(権限)]タブ](/docs/images/ja-jp/cdy7uua7fh8z/1s3Yp5zqJiKiSWqbPSezNO/acef814282795bef6921535f044f96e9/Quickstarts_API.png) - - - 以下の例では`read:messages`スコープを使用します。 - -
    - -
    - **jwt** Gemをインストールします。 - - ``` - gem 'jwt' - bundle install - ``` -
    - -
    - `Auth0Client`と呼ばれるクラスを作成します。このクラスは要求の`Authorization`ヘッダーから得た受信アクセストークンをデコードし検証します。 - - `Auth0Client`クラスはAuth0テナントの公開鍵を取得し、これを使ってアクセストークンの署名を検証します。`Token`構造体は`validate_permissions`メソッドを定義し、必要なスコープの配列を指定してアクセストークン内の特定の`scope`を検索し、トークンのペイロードに存在するかを確認します。 -
    - -
    - 受信要求の`Authorization`ヘッダー内でアクセストークンを検索する`Secured`と呼ばれるConcernを作成します。 - - トークンが存在する場合、`Auth0Client.validate_token`は`jwt` Gemを使用してトークンの署名を確認し、トークンのクレームを検証します。 - - Concernには、アクセストークンが有効であることを検証するほか、トークンに要求されたリソースにアクセスするのに十分な**スコープ** があることを確認するためのメカニズムも整備されています。この例では、`Auth0Client`クラスから`Token.validate_permissions`メソッドを呼び出すことで、ブロックを受け取りアクセス許可を確認する`validate_permissions`メソッドを定義します。 - - `/private-scoped`ルートでは、定義されたスコープはペイロードに入ってくるスコープと交差され、別の配列から1つ以上の項目が含まれているかを判定します。 -
    - -
    - アプリケーションコントローラーに`Secure` concernを追加すると、認可を必要とするコントローラーで`before_action`フィルターのみを使用すればよいことになります。 -
    - -
    - パブリックエンドポイント`/api/public`を処理するようにコントローラーを作成します。 - - `/public`エンドポイントでは認可は必要でないため、`before_action`は必要ありません。 -
    - -
    - `/api/private`と`/api/private-scoped`というプライベートエンドポイントを処理するようにコントローラーを作成します。 - - `/api/private`は、追加スコープのないアクセストークンを含む認証された要求に使用することができます。 - - `/api/private-scoped`は、`read:messages`スコープが付与されたアクセストークンを含む認証された要求に使用することができます。 - - 保護されたエンドポイントは`Secured` concernから`authorize`メソッドを呼び出す必要があります。そのためには、`before_action :authorize`を使用します。これによって、`Secured.authorize`メソッドが`PrivateController`の各アクションの前に呼び出されます。 - - ### APIを呼び出す - - APIを呼び出すにはアクセストークンが必要です。テスト用のアクセストークンは、[API設定](https://manage.auth0.com/#/apis)の**[Test(テスト)]** ビューから取得することができます。 - - ![[Auth0 Dashboard]>[Applications(アプリケーション)]>[API]>[Specific API(特定のAPI]>[Test(テスト)]タブ](/docs/images/ja-jp/cdy7uua7fh8z/6jeVBuypOGX5qMRXeJn5ow/dd20eb74e1e9079287762ce33dcf8e2d/Quickstart_Example_App_API.png) - - 要求の`Authorization`ヘッダーにアクセストークンを指定します。 - - - ```bash cURL lines - curl --request get \ - --url 'http:///%7ByourDomain%7D/api_path' \ - --header 'authorization: Bearer YOUR_ACCESS_TOKEN_HERE' - ``` - - ```csharp C# lines - var client = new RestClient("http:///%7ByourDomain%7D/api_path"); - var request = new RestRequest(Method.GET); - request.AddHeader("authorization", "Bearer YOUR_ACCESS_TOKEN_HERE"); - IRestResponse response = client.Execute(request); - ``` - - ```go Go lines - package main - import ( - "fmt" - "net/http" - "io/ioutil" - ) - func main() { - url := "http:///%7ByourDomain%7D/api_path" - req, _ := http.NewRequest("get", url, nil) - req.Header.Add("authorization", "Bearer YOUR_ACCESS_TOKEN_HERE") - res, _ := http.DefaultClient.Do(req) - defer res.Body.Close() - body, _ := ioutil.ReadAll(res.Body) - fmt.Println(res) - fmt.Println(string(body)) - } - ``` - - ```java Java lines - HttpResponse response = Unirest.get("http:///%7ByourDomain%7D/api_path") - .header("authorization", "Bearer YOUR_ACCESS_TOKEN_HERE") - .asString(); - ``` - - ```javascript Node.JS lines - var axios = require("axios").default; - var options = { - method: 'get', - url: 'http:///%7ByourDomain%7D/api_path', - headers: {authorization: 'Bearer YOUR_ACCESS_TOKEN_HERE'} - }; - axios.request(options).then(function (response) { - console.log(response.data); - }).catch(function (error) { - console.error(error); - }); - ``` - - ```obj-c Obj-C lines - #import - NSDictionary *headers = @{ @"authorization": @"Bearer YOUR_ACCESS_TOKEN_HERE" }; - NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http:///%7ByourDomain%7D/api_path"] - cachePolicy:NSURLRequestUseProtocolCachePolicy - - timeoutInterval:10.0]; - - [request setHTTPMethod:@"get"]; - [request setAllHTTPHeaderFields:headers]; - NSURLSession *session = [NSURLSession sharedSession]; - NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request - completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { - - if (error) { - - NSLog(@"%@", error); - - } else { - - NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response; - - NSLog(@"%@", httpResponse); - - } - - }]; - - [dataTask resume]; - ``` - - ```php PHP lines - #import - NSDictionary *headers = @{ @"authorization": @"Bearer YOUR_ACCESS_TOKEN_HERE" }; - NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http:///%7ByourDomain%7D/api_path"] - cachePolicy:NSURLRequestUseProtocolCachePolicy - - timeoutInterval:10.0]; - - [request setHTTPMethod:@"get"]; - [request setAllHTTPHeaderFields:headers]; - NSURLSession *session = [NSURLSession sharedSession]; - NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request - completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { - - if (error) { - - NSLog(@"%@", error); - - } else { - - NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response; - - NSLog(@"%@", httpResponse); - - } - - }]; - - [dataTask resume]; - ``` - - ```python Python lines - import http.client - conn = http.client.HTTPConnection("") - headers = { 'authorization': "Bearer YOUR_ACCESS_TOKEN_HERE" } - conn.request("get", "/%7ByourDomain%7D/api_path", headers=headers) - res = conn.getresponse() - data = res.read() - print(data.decode("utf-8")) - ``` - - ```ruby Ruby lines - require 'uri' - require 'net/http' - url = URI("http:///%7ByourDomain%7D/api_path") - http = Net::HTTP.new(url.host, url.port) - request = Net::HTTP::Get.new(url) - request["authorization"] = 'Bearer YOUR_ACCESS_TOKEN_HERE' - response = http.request(request) - puts response.read_body - ``` - - ```swift Swift lines - import Foundation - let headers = ["authorization": "Bearer YOUR_ACCESS_TOKEN_HERE"] - let request = NSMutableURLRequest(url: NSURL(string: "http:///%7ByourDomain%7D/api_path")! as URL, - cachePolicy: .useProtocolCachePolicy, - - timeoutInterval: 10.0) - - request.httpMethod = "get" - request.allHTTPHeaderFields = headers - let session = URLSession.shared - let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in - if (error != nil) { - print(error) - - } else { - let httpResponse = response as? HTTPURLResponse - - print(httpResponse) - - } - }) - dataTask.resume() - ``` - - - - - ##### チェックポイント - アプリケーションの構成が完了したら、アプリケーションを実行して次の点を確認します: - GET /api/publicが認証を必要としない要求に使用できる。 - GET /api/privateが認証された要求に使用できる。 - GET /api/private-scopedがread:messagesスコープが付与されたアクセストークンを含む認証された要求に使用できる。 - -
    - - ## 次のステップ - - 成功です!ここまで来れば、アプリケーションにログイン、ログアウト、ユーザープロファイル情報が備わっているはずです。 - - これでクイックスタートチュートリアルは終了ですが、機能はまだまだたくさんあります。Auth0でできることについて詳しくは、以下をご覧ください。 - - * [Auth0 Dashboard](https://manage.auth0.com/#) - Auth0のテナントやアプリケーションを構成して管理する方法について説明します - * [omniauth-auth0 SDK](https://github.com/auth0/omniauth-auth0) - このチュートリアルで使用されているSDKをより詳しく説明します - * [Auth0 Marketplace](https://marketplace.auth0.com/) - Auth0の機能性を拡張できる各種の統合を見つけられます -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    +--- +title: "Ruby on Rails APIに認可を追加する" +permalink: "interactive" +'description': "このチュートリアルでは、カスタムAuth0Clientクラス内のjwt Gemを使って、アクセストークンの検証を実施します。" +'og:title': "Ruby on Rails APIに認可を追加する" +'og:description': "このチュートリアルでは、カスタムAuth0Clientクラス内のjwt Gemを使って、アクセストークンの検証を実施します。" +'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/rails.png" +'twitter:title': "Ruby on Rails APIに認可を追加する" +'twitter:description': "このチュートリアルでは、カスタムAuth0Clientクラス内のjwt Gemを使って、アクセストークンの検証を実施します。" +sidebarTitle: Ruby on Rails API +--- + +import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; +import { LoggedInForm } from "/snippets/Login.jsx"; +import ApplicationController from "/snippets/quickstart/backend/rails/application_controller.rb.mdx"; +import Auth0Client from "/snippets/quickstart/backend/rails/auth0_client.rb.mdx"; +import Secured from "/snippets/quickstart/backend/rails/secured.rb.mdx"; +import PublicController from "/snippets/quickstart/backend/rails/public_controller.rb.mdx"; +import PrivateController from "/snippets/quickstart/backend/rails/private_controller.rb.mdx"; + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + +export const sections = [ + { id: "アクセス許可を定義する", title: "アクセス許可を定義する" }, + { id: "依存関係をインストールする", title: "依存関係をインストールする" }, + { id: "auth0clientクラスを作成する", title: "Auth0Clientクラスを作成する" }, + { id: "secured-concernを定義する", title: "Secured concernを定義する" }, + { id: "applicationcontrollerにsecure-concernを含める", title: "ApplicationControllerにSecure concernを含める" }, + { id: "パブリックエンドポイントを作成する", title: "パブリックエンドポイントを作成する" }, + { id: "プライベートエンドポイントを作成する", title: "プライベートエンドポイントを作成する" } +] + + + + このチュートリアルでは、カスタム`Auth0Client`クラス内の[**jwt** ](https://github.com/jwt/ruby-jwt) Gemを使って、アクセストークンの検証を実施します。`Secured`と呼ばれるConcernを使って、受信アクセストークンからの認証を必要とするエンドポイントを認可します。 + + Auth0 DashboardでAPIをまだ作成していない場合は、対話型のセレクターを使ってAuth0 APIを新規作成します。そうでない場合は、プロジェクトに既存のAPIを選択します。 + + Auth0 Dashboardを使って初めてAPIをセットアップする場合には、[使用の開始ガイド](/docs/ja-jp/get-started/auth0-overview/set-up-apis)を確認してください。 + + それぞれのAuth0 APIにはAPI識別子があり、アプリケーションにアクセストークンの検証で使用されます。 + + + **Auth0を初めてご利用ですか?** [Auth0の仕組み](/docs/ja-jp/overview)と、OAuth 2.0フレームワークを用いた[API認証と認可の実装](/docs/ja-jp/api-auth)について説明します。 + + +
    + アクセス許可は、ユーザーの代わりに、提供されたアクセストークンを使ってどのようにしてリソースにアクセスできるのかを定義できるようにします。たとえば、ユーザーがマネージャーアクセスレベルを持つ場合には、`messages`リソースに対して読み出しアクセスを付与し、管理者アクセスレベルを持つ場合には、書き込みアクセスを付与することができます。 + + Auth0 Dashboardの[[APIs]](https://manage.auth0.com/#/apis)セクションにある**[Permissions(権限)]** ビューで使用可能なアクセス許可を定義することができます。 + + ![[Auth0 Dashboard]>[Applications(アプリケーション)]>[APIs]>[Specific API(特定のAPI]>[Permissions(権限)]タブ](/docs/images/ja-jp/cdy7uua7fh8z/1s3Yp5zqJiKiSWqbPSezNO/acef814282795bef6921535f044f96e9/Quickstarts_API.png) + + + 以下の例では`read:messages`スコープを使用します。 + +
    + +
    + **jwt** Gemをインストールします。 + + ``` + gem 'jwt' + bundle install + ``` +
    + +
    + `Auth0Client`と呼ばれるクラスを作成します。このクラスは要求の`Authorization`ヘッダーから得た受信アクセストークンをデコードし検証します。 + + `Auth0Client`クラスはAuth0テナントの公開鍵を取得し、これを使ってアクセストークンの署名を検証します。`Token`構造体は`validate_permissions`メソッドを定義し、必要なスコープの配列を指定してアクセストークン内の特定の`scope`を検索し、トークンのペイロードに存在するかを確認します。 +
    + +
    + 受信要求の`Authorization`ヘッダー内でアクセストークンを検索する`Secured`と呼ばれるConcernを作成します。 + + トークンが存在する場合、`Auth0Client.validate_token`は`jwt` Gemを使用してトークンの署名を確認し、トークンのクレームを検証します。 + + Concernには、アクセストークンが有効であることを検証するほか、トークンに要求されたリソースにアクセスするのに十分な**スコープ** があることを確認するためのメカニズムも整備されています。この例では、`Auth0Client`クラスから`Token.validate_permissions`メソッドを呼び出すことで、ブロックを受け取りアクセス許可を確認する`validate_permissions`メソッドを定義します。 + + `/private-scoped`ルートでは、定義されたスコープはペイロードに入ってくるスコープと交差され、別の配列から1つ以上の項目が含まれているかを判定します。 +
    + +
    + アプリケーションコントローラーに`Secure` concernを追加すると、認可を必要とするコントローラーで`before_action`フィルターのみを使用すればよいことになります。 +
    + +
    + パブリックエンドポイント`/api/public`を処理するようにコントローラーを作成します。 + + `/public`エンドポイントでは認可は必要でないため、`before_action`は必要ありません。 +
    + +
    + `/api/private`と`/api/private-scoped`というプライベートエンドポイントを処理するようにコントローラーを作成します。 + + `/api/private`は、追加スコープのないアクセストークンを含む認証された要求に使用することができます。 + + `/api/private-scoped`は、`read:messages`スコープが付与されたアクセストークンを含む認証された要求に使用することができます。 + + 保護されたエンドポイントは`Secured` concernから`authorize`メソッドを呼び出す必要があります。そのためには、`before_action :authorize`を使用します。これによって、`Secured.authorize`メソッドが`PrivateController`の各アクションの前に呼び出されます。 + + ### APIを呼び出す + + APIを呼び出すにはアクセストークンが必要です。テスト用のアクセストークンは、[API設定](https://manage.auth0.com/#/apis)の**[Test(テスト)]** ビューから取得することができます。 + + ![[Auth0 Dashboard]>[Applications(アプリケーション)]>[API]>[Specific API(特定のAPI]>[Test(テスト)]タブ](/docs/images/ja-jp/cdy7uua7fh8z/6jeVBuypOGX5qMRXeJn5ow/dd20eb74e1e9079287762ce33dcf8e2d/Quickstart_Example_App_API.png) + + 要求の`Authorization`ヘッダーにアクセストークンを指定します。 + + + ```bash cURL lines + curl --request get \ + --url 'http:///%7ByourDomain%7D/api_path' \ + --header 'authorization: Bearer YOUR_ACCESS_TOKEN_HERE' + ``` + + ```csharp C# lines + var client = new RestClient("http:///%7ByourDomain%7D/api_path"); + var request = new RestRequest(Method.GET); + request.AddHeader("authorization", "Bearer YOUR_ACCESS_TOKEN_HERE"); + IRestResponse response = client.Execute(request); + ``` + + ```go Go lines + package main + import ( + "fmt" + "net/http" + "io/ioutil" + ) + func main() { + url := "http:///%7ByourDomain%7D/api_path" + req, _ := http.NewRequest("get", url, nil) + req.Header.Add("authorization", "Bearer YOUR_ACCESS_TOKEN_HERE") + res, _ := http.DefaultClient.Do(req) + defer res.Body.Close() + body, _ := ioutil.ReadAll(res.Body) + fmt.Println(res) + fmt.Println(string(body)) + } + ``` + + ```java Java lines + HttpResponse response = Unirest.get("http:///%7ByourDomain%7D/api_path") + .header("authorization", "Bearer YOUR_ACCESS_TOKEN_HERE") + .asString(); + ``` + + ```javascript Node.JS lines + var axios = require("axios").default; + var options = { + method: 'get', + url: 'http:///%7ByourDomain%7D/api_path', + headers: {authorization: 'Bearer YOUR_ACCESS_TOKEN_HERE'} + }; + axios.request(options).then(function (response) { + console.log(response.data); + }).catch(function (error) { + console.error(error); + }); + ``` + + ```obj-c Obj-C lines + #import + NSDictionary *headers = @{ @"authorization": @"Bearer YOUR_ACCESS_TOKEN_HERE" }; + NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http:///%7ByourDomain%7D/api_path"] + cachePolicy:NSURLRequestUseProtocolCachePolicy + + timeoutInterval:10.0]; + + [request setHTTPMethod:@"get"]; + [request setAllHTTPHeaderFields:headers]; + NSURLSession *session = [NSURLSession sharedSession]; + NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request + completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { + + if (error) { + + NSLog(@"%@", error); + + } else { + + NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response; + + NSLog(@"%@", httpResponse); + + } + + }]; + + [dataTask resume]; + ``` + + ```php PHP lines + #import + NSDictionary *headers = @{ @"authorization": @"Bearer YOUR_ACCESS_TOKEN_HERE" }; + NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http:///%7ByourDomain%7D/api_path"] + cachePolicy:NSURLRequestUseProtocolCachePolicy + + timeoutInterval:10.0]; + + [request setHTTPMethod:@"get"]; + [request setAllHTTPHeaderFields:headers]; + NSURLSession *session = [NSURLSession sharedSession]; + NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request + completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { + + if (error) { + + NSLog(@"%@", error); + + } else { + + NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response; + + NSLog(@"%@", httpResponse); + + } + + }]; + + [dataTask resume]; + ``` + + ```python Python lines + import http.client + conn = http.client.HTTPConnection("") + headers = { 'authorization': "Bearer YOUR_ACCESS_TOKEN_HERE" } + conn.request("get", "/%7ByourDomain%7D/api_path", headers=headers) + res = conn.getresponse() + data = res.read() + print(data.decode("utf-8")) + ``` + + ```ruby Ruby lines + require 'uri' + require 'net/http' + url = URI("http:///%7ByourDomain%7D/api_path") + http = Net::HTTP.new(url.host, url.port) + request = Net::HTTP::Get.new(url) + request["authorization"] = 'Bearer YOUR_ACCESS_TOKEN_HERE' + response = http.request(request) + puts response.read_body + ``` + + ```swift Swift lines + import Foundation + let headers = ["authorization": "Bearer YOUR_ACCESS_TOKEN_HERE"] + let request = NSMutableURLRequest(url: NSURL(string: "http:///%7ByourDomain%7D/api_path")! as URL, + cachePolicy: .useProtocolCachePolicy, + + timeoutInterval: 10.0) + + request.httpMethod = "get" + request.allHTTPHeaderFields = headers + let session = URLSession.shared + let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in + if (error != nil) { + print(error) + + } else { + let httpResponse = response as? HTTPURLResponse + + print(httpResponse) + + } + }) + dataTask.resume() + ``` + + + + + ##### チェックポイント + アプリケーションの構成が完了したら、アプリケーションを実行して次の点を確認します: + GET /api/publicが認証を必要としない要求に使用できる。 + GET /api/privateが認証された要求に使用できる。 + GET /api/private-scopedがread:messagesスコープが付与されたアクセストークンを含む認証された要求に使用できる。 + +
    + + ## 次のステップ + + 成功です!ここまで来れば、アプリケーションにログイン、ログアウト、ユーザープロファイル情報が備わっているはずです。 + + これでクイックスタートチュートリアルは終了ですが、機能はまだまだたくさんあります。Auth0でできることについて詳しくは、以下をご覧ください。 + + * [Auth0 Dashboard](https://manage.auth0.com/#) - Auth0のテナントやアプリケーションを構成して管理する方法について説明します + * [omniauth-auth0 SDK](https://github.com/auth0/omniauth-auth0) - このチュートリアルで使用されているSDKをより詳しく説明します + * [Auth0 Marketplace](https://marketplace.auth0.com/) - Auth0の機能性を拡張できる各種の統合を見つけられます +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    diff --git a/main/docs/ja-jp/quickstart/backend/webapi-owin/interactive.mdx b/main/docs/ja-jp/quickstart/backend/webapi-owin/interactive.mdx index 571428ab2..1da4519b2 100644 --- a/main/docs/ja-jp/quickstart/backend/webapi-owin/interactive.mdx +++ b/main/docs/ja-jp/quickstart/backend/webapi-owin/interactive.mdx @@ -1,154 +1,156 @@ ---- -title: "ASP.NET OWIN Web APIアプリケーションに認可を追加する" -permalink: "interactive" -'description': "このチュートリアルは、標準のJWTミドルウェアを使ってASP.NET OWIN APIアプリケーションに認可を追加する方法を説明します。" -'og:title': "ASP.NET OWIN Web APIアプリケーションに認可を追加する" -'og:description': "このチュートリアルは、標準のJWTミドルウェアを使ってASP.NET OWIN APIアプリケーションに認可を追加する方法を説明します。" -'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/asp.png" -'twitter:title': "ASP.NET OWIN Web APIアプリケーションに認可を追加する" -'twitter:description': "このチュートリアルは、標準のJWTミドルウェアを使ってASP.NET OWIN APIアプリケーションに認可を追加する方法を説明します。" -sidebarTitle: ASP.NET Web API (OWIN) ---- - -import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; -import { LoggedInForm } from "/snippets/Login.jsx"; -import Openidconnectsigningkeyresolver from "/snippets/quickstart/backend/webapi-owin/OpenIdConnectSigningKeyResolver.cs.mdx"; -import Scopeauthorizeattribute from "/snippets/quickstart/backend/webapi-owin/ScopeAuthorizeAttribute.cs.mdx"; -import Apicontroller from "/snippets/quickstart/backend/webapi-owin/ApiController.cs.mdx"; - -export const sections = [ - { id: "アクセス許可を定義する", title: "アクセス許可を定義する" }, - { id: "依存関係をインストールする", title: "依存関係をインストールする" }, - { id: "ミドルウェアを構成する", title: "ミドルウェアを構成する" }, - { id: "トークンの署名を検証する", title: "トークンの署名を検証する" }, - { id: "スコープを検証する", title: "スコープを検証する" }, - { id: "apiエンドポイントを保護する", title: "APIエンドポイントを保護する" } -] - - - - Auth0を使用すると、アプリケーションに認可を追加することができます。このガイドは、新規または既存のASP.NET Owin Web APIアプリケーションに`Microsoft.Owin.Security.Jwt`パッケージを使ってAuth0を統合する方法を説明します。 - - Auth0 DashboardでAPIをまだ作成していない場合は、対話型のセレクターを使ってAuth0 APIを新規作成します。そうでない場合は、プロジェクトに既存のAPIを選択することができます。 - - Auth0 Dashboardを使って初めてAPIをセットアップする場合には、使用の開始ガイドを確認してください。 - - それぞれのAuth0 APIにはAPI識別子があり、アプリケーションにアクセストークンの検証で使用されます。 - - - **Auth0を初めてご利用ですか?** Auth0の仕組みと、OAuth 2.0フレームワークを用いたAPI認証と認可の実装について説明します。 - - -
    - アクセス許可は、ユーザーの代わりに、提供されたアクセストークンを使ってどのようにしてリソースにアクセスできるのかを定義できるようにします。たとえば、ユーザーがマネージャーアクセスレベルを持つ場合には、`messages`リソースに対して読み取りアクセスを付与し、管理者アクセスレベルを持つ場合には、書き込みアクセスを付与することができます。 - - Auth0 Dashboardの[[API]](https://manage.auth0.com/#/apis)セクションにある**[Permissions(権限)]** ビューで使用可能なアクセス許可を定義することができます。以下の例では`read:messages`スコープを使用します。 - - ![[Auth0 Dashboard]>[Applications(アプリケーション)]>[APIs]>[Specific API(特定のAPI]>[Permissions(権限)]タブ](/docs/images/ja-jp/cdy7uua7fh8z/1s3Yp5zqJiKiSWqbPSezNO/acef814282795bef6921535f044f96e9/Quickstarts_API.png) -
    - -
    - `Microsoft.Owin.Security.Jwt` NuGetパッケージをインストールします。このパッケージには、Auth0のアクセストークンをASP.NET Owin Web APIで使用するために必要なOWIN JWTミドルウェアが含まれています。 - - ``` - Install-Package Microsoft.Owin.Security.Jwt - ``` -
    - -
    - `Startup`クラスの`Configuration`メソッドに移動し、構成した`JwtBearerAuthenticationOptions`を渡して`UseJwtBearerAuthentication`の呼び出しを追加します。 - - `JwtBearerAuthenticationOptions`では、Auth0 API識別子を`ValidAudience`プロパティで指定し、Auth0ドメインへのフルパスを`ValidIssuer`として指定する必要があります。`OpenIdConnectSigningKeyResolver`のインスタンスを使用するように`IssuerSigningKeyResolver`を構成して、署名鍵を解決できるようにします。 - - - **末尾のスラッシュを忘れてはいけません。** - - `ValidIssuer`に指定したURLの末尾にフォワードスラッシュ(`/`)があることを必ず確認してください。これは、JWTの発行者クレームと一致しなければなりません。この値の構成を誤ると、APIの呼び出しが正しく認証されません。 - -
    - -
    - OWINのJWTミドルウェアはOpen ID Connect Discoveryをデフォルトでは使用しないため、カスタムの`IssuerSigningKeyResolver`を提供する必要があります。 - - `OpenIdConnectSigningKeyResolver`クラスを作成し、`GetSigningKey`を実装して、正しい`SecurityKey`が返されることを確認します。このクラスは、`Startup.cs`でミドルウェアを構成する際に、`TokenValidationParameters.IssuerSigningKeyResolver`として使用されます。 -
    - -
    - JWTミドルウェアは、要求に含まれたアクセストークンが有効であることを検証しますが、現時点では、トークンが要求されたリソースへのアクセスに十分な**scope** を持っているのかを確認する手段はありません。 - - `System.Web.Http.AuthorizeAttribute`を継承する`ScopeAuthorizeAttribute`という名前のクラスを作成してください。この属性はAuth0テナントが発行した`scope`クレームが存在することを確認し、存在する場合には、`scope`クレームが要求されたスコープを含んでいることを確認します。 -
    - -
    - 以下に示されたルートは次の要求で使用することができます: - - - `GET /api/public`:認証を必要としない要求に使用することができます。 - - `GET /api/private`:追加スコープのないアクセストークンを含む認証された要求に使用することができます。 - - `GET /api/private-scoped`:`read:messages`スコープが付与されたアクセストークンを含む認証された要求に使用することができます。 - - JWTミドルウェアは標準のASP.NETの認証および認可メカニズムと統合できるため、コントローラーのアクションを`[Authorize]`属性で装飾するだけで、エンドポイントのセキュリティを確保できます。 - - アクションを`ScopeAuthorize`属性で更新し、必要な`scope`の名前を`scope`パラメーターに渡します。これにより、特定のAPIエンドポイントを呼び出すために、正しいスコープが利用できることが確実になります。 - - - ##### チェックポイント - アプリケーションの構成が完了したら、アプリケーションを実行して次の点を検証します: - GET /api/public が認証を必要としない要求に使用できる。 - GET /api/private が認証された要求に使用できる。 - GET /api/private-scoped がread:messagesスコープが付与されたアクセストークンを含む認証された要求に使用できる。 - -
    - - ## 次のステップ - - 成功です!ここまで来れば、アプリケーションにログイン、ログアウト、ユーザープロファイル情報が備わっているはずです。 - - これでクイックスタートチュートリアルは終了ですが、機能はまだまだたくさんあります。Auth0でできることについて詳しくは、以下をご覧ください。 - - * [Auth0 Dashboard](https://manage.auth0.com/#) - Auth0のテナントやアプリケーションを構成して管理する方法について説明します - * [Auth0 Marketplace](https://marketplace.auth0.com/) - Auth0の機能性を拡張できる各種の統合を見つけられます -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    +--- +title: "ASP.NET OWIN Web APIアプリケーションに認可を追加する" +permalink: "interactive" +'description': "このチュートリアルは、標準のJWTミドルウェアを使ってASP.NET OWIN APIアプリケーションに認可を追加する方法を説明します。" +'og:title': "ASP.NET OWIN Web APIアプリケーションに認可を追加する" +'og:description': "このチュートリアルは、標準のJWTミドルウェアを使ってASP.NET OWIN APIアプリケーションに認可を追加する方法を説明します。" +'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/asp.png" +'twitter:title': "ASP.NET OWIN Web APIアプリケーションに認可を追加する" +'twitter:description': "このチュートリアルは、標準のJWTミドルウェアを使ってASP.NET OWIN APIアプリケーションに認可を追加する方法を説明します。" +sidebarTitle: ASP.NET Web API (OWIN) +--- + +import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; +import { LoggedInForm } from "/snippets/Login.jsx"; +import Openidconnectsigningkeyresolver from "/snippets/quickstart/backend/webapi-owin/OpenIdConnectSigningKeyResolver.cs.mdx"; +import Scopeauthorizeattribute from "/snippets/quickstart/backend/webapi-owin/ScopeAuthorizeAttribute.cs.mdx"; +import Apicontroller from "/snippets/quickstart/backend/webapi-owin/ApiController.cs.mdx"; + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + +export const sections = [ + { id: "アクセス許可を定義する", title: "アクセス許可を定義する" }, + { id: "依存関係をインストールする", title: "依存関係をインストールする" }, + { id: "ミドルウェアを構成する", title: "ミドルウェアを構成する" }, + { id: "トークンの署名を検証する", title: "トークンの署名を検証する" }, + { id: "スコープを検証する", title: "スコープを検証する" }, + { id: "apiエンドポイントを保護する", title: "APIエンドポイントを保護する" } +] + + + + Auth0を使用すると、アプリケーションに認可を追加することができます。このガイドは、新規または既存のASP.NET Owin Web APIアプリケーションに`Microsoft.Owin.Security.Jwt`パッケージを使ってAuth0を統合する方法を説明します。 + + Auth0 DashboardでAPIをまだ作成していない場合は、対話型のセレクターを使ってAuth0 APIを新規作成します。そうでない場合は、プロジェクトに既存のAPIを選択することができます。 + + Auth0 Dashboardを使って初めてAPIをセットアップする場合には、使用の開始ガイドを確認してください。 + + それぞれのAuth0 APIにはAPI識別子があり、アプリケーションにアクセストークンの検証で使用されます。 + + + **Auth0を初めてご利用ですか?** Auth0の仕組みと、OAuth 2.0フレームワークを用いたAPI認証と認可の実装について説明します。 + + +
    + アクセス許可は、ユーザーの代わりに、提供されたアクセストークンを使ってどのようにしてリソースにアクセスできるのかを定義できるようにします。たとえば、ユーザーがマネージャーアクセスレベルを持つ場合には、`messages`リソースに対して読み取りアクセスを付与し、管理者アクセスレベルを持つ場合には、書き込みアクセスを付与することができます。 + + Auth0 Dashboardの[[API]](https://manage.auth0.com/#/apis)セクションにある**[Permissions(権限)]** ビューで使用可能なアクセス許可を定義することができます。以下の例では`read:messages`スコープを使用します。 + + ![[Auth0 Dashboard]>[Applications(アプリケーション)]>[APIs]>[Specific API(特定のAPI]>[Permissions(権限)]タブ](/docs/images/ja-jp/cdy7uua7fh8z/1s3Yp5zqJiKiSWqbPSezNO/acef814282795bef6921535f044f96e9/Quickstarts_API.png) +
    + +
    + `Microsoft.Owin.Security.Jwt` NuGetパッケージをインストールします。このパッケージには、Auth0のアクセストークンをASP.NET Owin Web APIで使用するために必要なOWIN JWTミドルウェアが含まれています。 + + ``` + Install-Package Microsoft.Owin.Security.Jwt + ``` +
    + +
    + `Startup`クラスの`Configuration`メソッドに移動し、構成した`JwtBearerAuthenticationOptions`を渡して`UseJwtBearerAuthentication`の呼び出しを追加します。 + + `JwtBearerAuthenticationOptions`では、Auth0 API識別子を`ValidAudience`プロパティで指定し、Auth0ドメインへのフルパスを`ValidIssuer`として指定する必要があります。`OpenIdConnectSigningKeyResolver`のインスタンスを使用するように`IssuerSigningKeyResolver`を構成して、署名鍵を解決できるようにします。 + + + **末尾のスラッシュを忘れてはいけません。** + + `ValidIssuer`に指定したURLの末尾にフォワードスラッシュ(`/`)があることを必ず確認してください。これは、JWTの発行者クレームと一致しなければなりません。この値の構成を誤ると、APIの呼び出しが正しく認証されません。 + +
    + +
    + OWINのJWTミドルウェアはOpen ID Connect Discoveryをデフォルトでは使用しないため、カスタムの`IssuerSigningKeyResolver`を提供する必要があります。 + + `OpenIdConnectSigningKeyResolver`クラスを作成し、`GetSigningKey`を実装して、正しい`SecurityKey`が返されることを確認します。このクラスは、`Startup.cs`でミドルウェアを構成する際に、`TokenValidationParameters.IssuerSigningKeyResolver`として使用されます。 +
    + +
    + JWTミドルウェアは、要求に含まれたアクセストークンが有効であることを検証しますが、現時点では、トークンが要求されたリソースへのアクセスに十分な**scope** を持っているのかを確認する手段はありません。 + + `System.Web.Http.AuthorizeAttribute`を継承する`ScopeAuthorizeAttribute`という名前のクラスを作成してください。この属性はAuth0テナントが発行した`scope`クレームが存在することを確認し、存在する場合には、`scope`クレームが要求されたスコープを含んでいることを確認します。 +
    + +
    + 以下に示されたルートは次の要求で使用することができます: + + - `GET /api/public`:認証を必要としない要求に使用することができます。 + - `GET /api/private`:追加スコープのないアクセストークンを含む認証された要求に使用することができます。 + - `GET /api/private-scoped`:`read:messages`スコープが付与されたアクセストークンを含む認証された要求に使用することができます。 + + JWTミドルウェアは標準のASP.NETの認証および認可メカニズムと統合できるため、コントローラーのアクションを`[Authorize]`属性で装飾するだけで、エンドポイントのセキュリティを確保できます。 + + アクションを`ScopeAuthorize`属性で更新し、必要な`scope`の名前を`scope`パラメーターに渡します。これにより、特定のAPIエンドポイントを呼び出すために、正しいスコープが利用できることが確実になります。 + + + ##### チェックポイント + アプリケーションの構成が完了したら、アプリケーションを実行して次の点を検証します: + GET /api/public が認証を必要としない要求に使用できる。 + GET /api/private が認証された要求に使用できる。 + GET /api/private-scoped がread:messagesスコープが付与されたアクセストークンを含む認証された要求に使用できる。 + +
    + + ## 次のステップ + + 成功です!ここまで来れば、アプリケーションにログイン、ログアウト、ユーザープロファイル情報が備わっているはずです。 + + これでクイックスタートチュートリアルは終了ですが、機能はまだまだたくさんあります。Auth0でできることについて詳しくは、以下をご覧ください。 + + * [Auth0 Dashboard](https://manage.auth0.com/#) - Auth0のテナントやアプリケーションを構成して管理する方法について説明します + * [Auth0 Marketplace](https://marketplace.auth0.com/) - Auth0の機能性を拡張できる各種の統合を見つけられます +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    diff --git a/main/docs/ja-jp/quickstart/native/android-facebook-login/interactive.mdx b/main/docs/ja-jp/quickstart/native/android-facebook-login/interactive.mdx index 125ab2bc2..7c1e13c12 100644 --- a/main/docs/ja-jp/quickstart/native/android-facebook-login/interactive.mdx +++ b/main/docs/ja-jp/quickstart/native/android-facebook-login/interactive.mdx @@ -1,274 +1,276 @@ ---- -title: "Android - Facebookログイン" -permalink: "interactive" -'description': "このチュートリアルは、ネイティブFacebookログインを使用して、Androidアプリケーションにユーザーログインを追加する方法について説明します。" -'og:title': "Android - Facebookログイン" -'og:description': "このチュートリアルは、ネイティブFacebookログインを使用して、Androidアプリケーションにユーザーログインを追加する方法について説明します。" -'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/android.png" -'twitter:title': "Android - Facebookログイン" -'twitter:description': "このチュートリアルは、ネイティブFacebookログインを使用して、Androidアプリケーションにユーザーログインを追加する方法について説明します。" ---- - -import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; -import { LoggedInForm } from "/snippets/Login.jsx"; -import Performloginsimplecallback from "/snippets/quickstart/native/android-facebook-login/performLogin + SimpleCallback.mdx"; -import Oncreate from "/snippets/quickstart/native/android-facebook-login/onCreate.mdx"; -import Fetchsessiontoken from "/snippets/quickstart/native/android-facebook-login/fetchSessionToken.mdx"; -import Fetchuserprofile from "/snippets/quickstart/native/android-facebook-login/fetchUserProfile.mdx"; -import Exchangetokens from "/snippets/quickstart/native/android-facebook-login/exchangeTokens.mdx"; -import Performlogin from "/snippets/quickstart/native/android-facebook-login/performLogin.mdx"; - -export const sections = [ - { id: "システム要件", title: "システム要件" }, - { id: "始める前に", title: "始める前に" }, - { id: "facebookのアクセス許可を要求する", title: "Facebookのアクセス許可を要求する" }, - { id: "performloginメソッドを作成する", title: "performLoginメソッドを作成する" }, - { id: "performloginメソッドを呼び出す", title: "performLoginメソッドを呼び出す" }, - { id: "facebookを統合する", title: "Facebookを統合する" }, - { id: "facebookセッションアクセストークンを取得する", title: "Facebookセッションアクセストークンを取得する" }, - { id: "facebookのユーザープロファイルを取得する", title: "Facebookのユーザープロファイルを取得する" }, - { id: "auth0を統合する", title: "Auth0を統合する" }, - { id: "受け取ったデータをauth0トークンに交換する", title: "受け取ったデータをAuth0トークンに交換する" }, - { id: "performloginメソッドを更新する", title: "performLoginメソッドを更新する" } -] - - - - このチュートリアルは、ネイティブFacebookログインを使用して、Androidアプリケーションにユーザーログインを追加する方法について説明します。ログインして、アカウント用に構成された例を参考にして、このクリックスタートに従うことをお勧めします。 - -
    - - Android Studio 3.6.1 - - Android SDK 25 - - Emulator - Nexus 5X - Android 6.0 - - このチュートリアルは、[Facebook SDK](https://developers.facebook.com/docs/)でログインを実装する方法について説明します。​ -
    - -
    - - [FacebookログインSDK](https://developers.facebook.com/docs/facebook-login/)をインストールして構成します。[https://developers.facebook.com](https://developers.facebook.com/)でFacebookアプリの作成プロセスも行います。**この手順が終了したら、Facebookログインが統合された状態でモバイルアプリが稼働しているはずです。** - - DashboardでFacebookネイティブサインインを使用するようにAuth0アプリケーションを構成します。「[Facebookログインをネイティブアプリに追加する](/docs/ja-jp/connections/nativesocial/facebook)」を参照してください。**この手順が終了したら、アプリケーションはFacebookネイティブログインを実装できるようになります。** -
    - -
    - アプリケーションでは既にFacebookでサインインすることができますが、リッチユーザープロファイルを確保するには、Facebookログインボタンがセットアップされたアクセス許可を更新する必要があります。 - - 要求されたアクセス許可を`public_profile`と`email`に設定します。これで、アクセス要求がユーザーによって受け入れられたという前提で、ユーザーメールも応答の一部に含まれます。 - - `loginButton.setPermissions(Arrays.asList("public_profile", "email"));` -
    - -
    - 次に、Auth0で認証プロセスを始めるために、送信するペイロードの準備を行う新しいメソッドを作成します。 - - 内部コールバックを処理するために、小さなインターフェイスを利用します。 - - サンプルでは、メソッドの名前は`performLogin`、インターフェイスの名前は`SimpleCallback`に指定されています。両方を追加してください。 -
    - -
    - 次に、Facebookログインのコールバックの`onSuccess`メソッドから特定のメソッドを呼び出します。 -
    - -
    - Auth0でFacebookを使ってサインインすると、バックエンドはユーザーが主張する通りの本人であることを確認するために、バックグラウンドで確認作業を実施します。これを実現するには、セッションアクセストークンを提供する必要があります。 - - さらに、このFacebookユーザーを表すために、ユーザーをAuth0で作成する必要がある場合、バックエンドでは姓名やメールなどの一部の情報が必要になります。Auth0ユーザープロファイルでは、メールは(提供された場合)未検証としてフラグが付けられます。 - - セッションアクセストークンとユーザープロファイルを取得するには、Facebook APIに対してさらに2つの要求を行う必要があります。 -
    - -
    - Facebook APIの`/oauth/access_token`エンドポイントに対して新しいGET要求を行います。以下のクエリパラメーターを使用します: - - - `grant_type`: `fb_attenuate_token`。 - - `fb_exchange_token`:ログイン時に受け取るアクセストークンです。 - - `client_id`:アプリIDです。この値は、Facebook開発者のダッシュボードから取得したもので、Facebookログインの統合に成功している場合は、アプリケーションで既に使用されているはずです。 - - この手順で得たロジックを独自のメソッドに投入します。これを前に追加したメソッドから後で呼び出します。 - - サンプルはFacebook SDKの`GraphRequest`クラスを使用して、この要求を実行します。 -
    - -
    - 上の手順と同様に、別のGET要求を行います。エンドポイントパスは、Facebookログイン結果から得たユーザーID値(`/904636746222815`など)になります。次のパラメーターを使用します: - - - `access_token`:ログイン時に受け取るアクセストークンです。 - - `fields`:応答で取得したいユーザープロファイルからのフィールドです。これらは、初めに構成されたFacebookログインボタンのアクセス許可に直接関連付けられています。アクセス許可が任意の場合、ユーザーはまずアクセス許可を付与することに同意する必要があります。Auth0でユーザーをサインアップするには、フルネームとメールを入力するだけで十分です。 -
    - -
    - 必要なアーティファクトを取得したら、IDやアクセストークンなどAuth0のユーザー資格情報に交換する準備ができました。しかしまず、その最後の要求を行うためにAuth0 SDKをセットアップする必要があります。 - - ### アプリケーションキーを取得する - - 1. [Auth0 Dashboard](https://manage.auth0.com/)の**[Applications(アプリケーション)]** セクションで、**[Sign in with Facebook(Facebookでサインイン)]** を有効にした既存のアプリケーションを選択します。この手順で不明な点があれば、この記事の上に記載された要件セクションを確認してください。 - 2. アプリケーションの設定ページから**[Domain(ドメイン)]** と**[Client ID(クライアントID)]** の値をコピーします。これらはSDKで必要です。 - 3. Androidアプリケーションのstrings.xmlファイルで2つの新しいリソースを作成して保存します。キーの名前は以下で使用するキーと一致しなければなりません。 - - ``` - - {yourDomain} - {yourClientId} - - ``` - - ### Auth0 SDKをインストールする - - Androidアプリケーションで、この行をapp/build.gradleファイルに追加します: - - ``` - dependencies { - implementation 'com.auth0.android:auth0:1.+' - } - ``` - - 次に、Gradle Syncタスクを実行し、プロジェクトとその依存関係を更新します。 - - ### Web認証のマニフェストを更新する - - アプリケーションがSDKによって提供されるWeb認証モジュールを利用する予定がない場合は、未使用のアクティビティをAndroidManifest.xmlファイルから削除し、マニフェストのプレースホルダー問題を防ぐ必要があります。これを実現するには、アクティビティの宣言を追加し、tools:node="remove"の注釈を加えます。 - - ``` - - - - - ``` - - ただし、Web認証をサポートする予定の場合は、[ここ](/docs/ja-jp/libraries/auth0-android#authentication-via-universal-login)でマニフェストのプレースホルダーを宣言する方法を確認してください。 -
    - -
    - SDKは、使用する前にインスタンス化する必要があります。クラスレベルでフィールドを定義し、`onCreate`メソッドで初期化します。上の手順で定義した資格情報が`Auth0`コンストラクターに渡されたら、`AuthenticationAPIClient`の新しいインスタンスが作成されます。 - - ``` - private AuthenticationAPIClient auth0Client; - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - - setContentView(R.layout.activity_login); - - Auth0 account = new Auth0(getString(R.string.com_auth0_client_id), getString(R.string.com_auth0_domain)); - - auth0Client = new AuthenticationAPIClient(account); - - //... - - } - ``` - - ロジックを維持するメソッドを作成し、取得した2つのアーティファクトをAuth0のユーザー資格情報に交換します。サンプルでは、このメソッドの名前は`exchangeTokens`です。 - - APIクライアントは、トークンとサブジェクトタイプを受け取る`loginWithNativeSocialToken`メソッドを宣言します。前者はセッショントークンに対応し、後者はバックエンドが認証しようとする接続のタイプを示します。 - - ネイティブFacebookログインでは、以下の値を使用します:`"http://auth0.com/oauth/token-type/facebook-info-session-access-token"` - - 構成する必要がある他の値は、ユーザープロファイル(`user_profile`キーを使用)とAuth0トークンに含まれる要求されたスコープです。 - - - 変化しないことを把握している値はすべて、クラスの上部で定数として維持しておくと便利です。サンプルは、件名トークンタイプ、Facebookのアクセス許可、およびAuth0のスコープに対して定数を利用します。Auth0のスコープの詳細については、特集記事をお読みください。 - -
    - -
    - すべての手順が独自のメソッドで定義されたら、`performLogin`メソッドに全部まとめて入れましょう。 - - すべて正常に実行されると、FacebookログインSDKでネイティブ認証ができるようになります。つまり、Facebookアプリがデバイスにインストールされていると、認証はブラウザーアプリでなくアプリケーションを介して処理されます。 -
    - - ## 次のステップ - 成功です!ここまで来れば、アプリケーションにログイン、ログアウト、ユーザープロファイル情報が備わっているはずです。 - - これでクイックスタートチュートリアルは終了ですが、機能はまだまだたくさんあります。Auth0でできることについて詳しくは、以下をご覧ください。 - - - [Auth0 Dashboard](https://manage.auth0.com/#) - Auth0のテナントやアプリケーションを構成して管理する方法について説明します - - - [Auth0 Marketplace](https://marketplace.auth0.com/) - Auth0の機能性を拡張できる各種の統合を見つけられます -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    +--- +title: "Android - Facebookログイン" +permalink: "interactive" +'description': "このチュートリアルは、ネイティブFacebookログインを使用して、Androidアプリケーションにユーザーログインを追加する方法について説明します。" +'og:title': "Android - Facebookログイン" +'og:description': "このチュートリアルは、ネイティブFacebookログインを使用して、Androidアプリケーションにユーザーログインを追加する方法について説明します。" +'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/android.png" +'twitter:title': "Android - Facebookログイン" +'twitter:description': "このチュートリアルは、ネイティブFacebookログインを使用して、Androidアプリケーションにユーザーログインを追加する方法について説明します。" +--- + +import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; +import { LoggedInForm } from "/snippets/Login.jsx"; +import Performloginsimplecallback from "/snippets/quickstart/native/android-facebook-login/performLogin + SimpleCallback.mdx"; +import Oncreate from "/snippets/quickstart/native/android-facebook-login/onCreate.mdx"; +import Fetchsessiontoken from "/snippets/quickstart/native/android-facebook-login/fetchSessionToken.mdx"; +import Fetchuserprofile from "/snippets/quickstart/native/android-facebook-login/fetchUserProfile.mdx"; +import Exchangetokens from "/snippets/quickstart/native/android-facebook-login/exchangeTokens.mdx"; +import Performlogin from "/snippets/quickstart/native/android-facebook-login/performLogin.mdx"; + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + +export const sections = [ + { id: "システム要件", title: "システム要件" }, + { id: "始める前に", title: "始める前に" }, + { id: "facebookのアクセス許可を要求する", title: "Facebookのアクセス許可を要求する" }, + { id: "performloginメソッドを作成する", title: "performLoginメソッドを作成する" }, + { id: "performloginメソッドを呼び出す", title: "performLoginメソッドを呼び出す" }, + { id: "facebookを統合する", title: "Facebookを統合する" }, + { id: "facebookセッションアクセストークンを取得する", title: "Facebookセッションアクセストークンを取得する" }, + { id: "facebookのユーザープロファイルを取得する", title: "Facebookのユーザープロファイルを取得する" }, + { id: "auth0を統合する", title: "Auth0を統合する" }, + { id: "受け取ったデータをauth0トークンに交換する", title: "受け取ったデータをAuth0トークンに交換する" }, + { id: "performloginメソッドを更新する", title: "performLoginメソッドを更新する" } +] + + + + このチュートリアルは、ネイティブFacebookログインを使用して、Androidアプリケーションにユーザーログインを追加する方法について説明します。ログインして、アカウント用に構成された例を参考にして、このクリックスタートに従うことをお勧めします。 + +
    + - Android Studio 3.6.1 + - Android SDK 25 + - Emulator - Nexus 5X - Android 6.0 + + このチュートリアルは、[Facebook SDK](https://developers.facebook.com/docs/)でログインを実装する方法について説明します。​ +
    + +
    + - [FacebookログインSDK](https://developers.facebook.com/docs/facebook-login/)をインストールして構成します。[https://developers.facebook.com](https://developers.facebook.com/)でFacebookアプリの作成プロセスも行います。**この手順が終了したら、Facebookログインが統合された状態でモバイルアプリが稼働しているはずです。** + + DashboardでFacebookネイティブサインインを使用するようにAuth0アプリケーションを構成します。「[Facebookログインをネイティブアプリに追加する](/docs/ja-jp/connections/nativesocial/facebook)」を参照してください。**この手順が終了したら、アプリケーションはFacebookネイティブログインを実装できるようになります。** +
    + +
    + アプリケーションでは既にFacebookでサインインすることができますが、リッチユーザープロファイルを確保するには、Facebookログインボタンがセットアップされたアクセス許可を更新する必要があります。 + + 要求されたアクセス許可を`public_profile`と`email`に設定します。これで、アクセス要求がユーザーによって受け入れられたという前提で、ユーザーメールも応答の一部に含まれます。 + + `loginButton.setPermissions(Arrays.asList("public_profile", "email"));` +
    + +
    + 次に、Auth0で認証プロセスを始めるために、送信するペイロードの準備を行う新しいメソッドを作成します。 + + 内部コールバックを処理するために、小さなインターフェイスを利用します。 + + サンプルでは、メソッドの名前は`performLogin`、インターフェイスの名前は`SimpleCallback`に指定されています。両方を追加してください。 +
    + +
    + 次に、Facebookログインのコールバックの`onSuccess`メソッドから特定のメソッドを呼び出します。 +
    + +
    + Auth0でFacebookを使ってサインインすると、バックエンドはユーザーが主張する通りの本人であることを確認するために、バックグラウンドで確認作業を実施します。これを実現するには、セッションアクセストークンを提供する必要があります。 + + さらに、このFacebookユーザーを表すために、ユーザーをAuth0で作成する必要がある場合、バックエンドでは姓名やメールなどの一部の情報が必要になります。Auth0ユーザープロファイルでは、メールは(提供された場合)未検証としてフラグが付けられます。 + + セッションアクセストークンとユーザープロファイルを取得するには、Facebook APIに対してさらに2つの要求を行う必要があります。 +
    + +
    + Facebook APIの`/oauth/access_token`エンドポイントに対して新しいGET要求を行います。以下のクエリパラメーターを使用します: + + - `grant_type`: `fb_attenuate_token`。 + - `fb_exchange_token`:ログイン時に受け取るアクセストークンです。 + - `client_id`:アプリIDです。この値は、Facebook開発者のダッシュボードから取得したもので、Facebookログインの統合に成功している場合は、アプリケーションで既に使用されているはずです。 + + この手順で得たロジックを独自のメソッドに投入します。これを前に追加したメソッドから後で呼び出します。 + + サンプルはFacebook SDKの`GraphRequest`クラスを使用して、この要求を実行します。 +
    + +
    + 上の手順と同様に、別のGET要求を行います。エンドポイントパスは、Facebookログイン結果から得たユーザーID値(`/904636746222815`など)になります。次のパラメーターを使用します: + + - `access_token`:ログイン時に受け取るアクセストークンです。 + - `fields`:応答で取得したいユーザープロファイルからのフィールドです。これらは、初めに構成されたFacebookログインボタンのアクセス許可に直接関連付けられています。アクセス許可が任意の場合、ユーザーはまずアクセス許可を付与することに同意する必要があります。Auth0でユーザーをサインアップするには、フルネームとメールを入力するだけで十分です。 +
    + +
    + 必要なアーティファクトを取得したら、IDやアクセストークンなどAuth0のユーザー資格情報に交換する準備ができました。しかしまず、その最後の要求を行うためにAuth0 SDKをセットアップする必要があります。 + + ### アプリケーションキーを取得する + + 1. [Auth0 Dashboard](https://manage.auth0.com/)の**[Applications(アプリケーション)]** セクションで、**[Sign in with Facebook(Facebookでサインイン)]** を有効にした既存のアプリケーションを選択します。この手順で不明な点があれば、この記事の上に記載された要件セクションを確認してください。 + 2. アプリケーションの設定ページから**[Domain(ドメイン)]** と**[Client ID(クライアントID)]** の値をコピーします。これらはSDKで必要です。 + 3. Androidアプリケーションのstrings.xmlファイルで2つの新しいリソースを作成して保存します。キーの名前は以下で使用するキーと一致しなければなりません。 + + ``` + + {yourDomain} + {yourClientId} + + ``` + + ### Auth0 SDKをインストールする + + Androidアプリケーションで、この行をapp/build.gradleファイルに追加します: + + ``` + dependencies { + implementation 'com.auth0.android:auth0:1.+' + } + ``` + + 次に、Gradle Syncタスクを実行し、プロジェクトとその依存関係を更新します。 + + ### Web認証のマニフェストを更新する + + アプリケーションがSDKによって提供されるWeb認証モジュールを利用する予定がない場合は、未使用のアクティビティをAndroidManifest.xmlファイルから削除し、マニフェストのプレースホルダー問題を防ぐ必要があります。これを実現するには、アクティビティの宣言を追加し、tools:node="remove"の注釈を加えます。 + + ``` + + + + + ``` + + ただし、Web認証をサポートする予定の場合は、[ここ](/docs/ja-jp/libraries/auth0-android#authentication-via-universal-login)でマニフェストのプレースホルダーを宣言する方法を確認してください。 +
    + +
    + SDKは、使用する前にインスタンス化する必要があります。クラスレベルでフィールドを定義し、`onCreate`メソッドで初期化します。上の手順で定義した資格情報が`Auth0`コンストラクターに渡されたら、`AuthenticationAPIClient`の新しいインスタンスが作成されます。 + + ``` + private AuthenticationAPIClient auth0Client; + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + setContentView(R.layout.activity_login); + + Auth0 account = new Auth0(getString(R.string.com_auth0_client_id), getString(R.string.com_auth0_domain)); + + auth0Client = new AuthenticationAPIClient(account); + + //... + + } + ``` + + ロジックを維持するメソッドを作成し、取得した2つのアーティファクトをAuth0のユーザー資格情報に交換します。サンプルでは、このメソッドの名前は`exchangeTokens`です。 + + APIクライアントは、トークンとサブジェクトタイプを受け取る`loginWithNativeSocialToken`メソッドを宣言します。前者はセッショントークンに対応し、後者はバックエンドが認証しようとする接続のタイプを示します。 + + ネイティブFacebookログインでは、以下の値を使用します:`"http://auth0.com/oauth/token-type/facebook-info-session-access-token"` + + 構成する必要がある他の値は、ユーザープロファイル(`user_profile`キーを使用)とAuth0トークンに含まれる要求されたスコープです。 + + + 変化しないことを把握している値はすべて、クラスの上部で定数として維持しておくと便利です。サンプルは、件名トークンタイプ、Facebookのアクセス許可、およびAuth0のスコープに対して定数を利用します。Auth0のスコープの詳細については、特集記事をお読みください。 + +
    + +
    + すべての手順が独自のメソッドで定義されたら、`performLogin`メソッドに全部まとめて入れましょう。 + + すべて正常に実行されると、FacebookログインSDKでネイティブ認証ができるようになります。つまり、Facebookアプリがデバイスにインストールされていると、認証はブラウザーアプリでなくアプリケーションを介して処理されます。 +
    + + ## 次のステップ + 成功です!ここまで来れば、アプリケーションにログイン、ログアウト、ユーザープロファイル情報が備わっているはずです。 + + これでクイックスタートチュートリアルは終了ですが、機能はまだまだたくさんあります。Auth0でできることについて詳しくは、以下をご覧ください。 + + - [Auth0 Dashboard](https://manage.auth0.com/#) - Auth0のテナントやアプリケーションを構成して管理する方法について説明します + + - [Auth0 Marketplace](https://marketplace.auth0.com/) - Auth0の機能性を拡張できる各種の統合を見つけられます +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    diff --git a/main/docs/ja-jp/quickstart/native/android/interactive.mdx b/main/docs/ja-jp/quickstart/native/android/interactive.mdx index 56dcd59db..17f81d977 100644 --- a/main/docs/ja-jp/quickstart/native/android/interactive.mdx +++ b/main/docs/ja-jp/quickstart/native/android/interactive.mdx @@ -1,218 +1,220 @@ ---- -title: "Androidアプリケーションにログインを追加する" -permalink: "interactive" -'description': "このガイドでは、AndroidアプリケーションにAuth0 Android SDKを使ってAuth0を統合する方法を説明します。" -'og:title': "Androidアプリケーションにログインを追加する" -'og:description': "このガイドでは、AndroidアプリケーションにAuth0 Android SDKを使ってAuth0を統合する方法を説明します。" -'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/android.png" -'twitter:title': "Androidアプリケーションにログインを追加する" -'twitter:description': "このガイドでは、AndroidアプリケーションにAuth0 Android SDKを使ってAuth0を統合する方法を説明します。" -sidebarTitle: Android ---- - - -import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; -import { LoggedInForm } from "/snippets/Login.jsx"; -import Build from "/snippets/quickstart/native/android/build.gradle.mdx"; -import Build2 from "/snippets/quickstart/native/android/build.gradle2.mdx"; -import Strings from "/snippets/quickstart/native/android/strings.xml.mdx"; -import Mainactivity from "/snippets/quickstart/native/android/MainActivity.kt.mdx"; -import Mainactivity2 from "/snippets/quickstart/native/android/MainActivity.kt2.mdx"; -import Mainactivity3 from "/snippets/quickstart/native/android/MainActivity.kt3.mdx"; - -export const sections = [ - { id: "auth0を構成する", title: "Auth0を構成する" }, - { id: "auth0-android-sdkをインストールする", title: "Auth0 Android SDKをインストールする" }, - { id: "マニフェストのプレースホルダーを追加する", title: "マニフェストのプレースホルダーを追加する" }, - { id: "アプリケーションを構成する", title: "アプリケーションを構成する" }, - { id: "アプリケーションにログインを追加する", title: "アプリケーションにログインを追加する" }, - { id: "アプリケーションにログアウトを追加する", title: "アプリケーションにログアウトを追加する" }, - { id: "ユーザープロファイル情報を表示する", title: "ユーザープロファイル情報を表示する" } -] - - - -
    - Auth0のサービスを利用するには、Auth0 Dashboadに設定済みのアプリケーションがある必要があります。Auth0アプリケーションは、プロジェクトに認証を構成する場所です。 - - ### アプリケーションを構成する - - 対話型のセレクターを使ってAuth0アプリケーションを新規作成するか、統合したいプロジェクトを表す既存のアプリケーションを選択します。Auth0のすべてのアプリケーションには英数字からなる一意のクライアントIDが割り当てられており、アプリケーションのコードがSDKを通じてAuth0 APIを呼び出す際に使用されます。 - - このクイックスタートを使って構成されたすべての設定は、[Dashboard](https://manage.auth0.com/#/)のアプリケーションを自動更新します。今後、アプリケーションの管理もDashboardで行えます。 - - 代わりに完了済みの構成を見てみたい場合は、サンプルアプリケーションをご覧ください。 - - ### Callback URLを構成する - - Callback URLとは、Auth0によって認証後のユーザーをダイレクトするアプリケーションURLです。この値を設定していない場合、ユーザーはログイン後にアプリケーションに戻りません。 - - - サンプルプロジェクトに沿って進めている場合は、`demo://{yourDomain}/android/YOUR_APP_PACKAGE_NAME/callback`に設定してください。 - - - ### ログアウトURLを構成する - - ログアウトURLとは、Auth0によってログアウト後のユーザーをリダイレクトするアプリケーションURLです。この値を設定していない場合、ユーザーはアプリケーションからログアウトできず、エラーを受け取ります。 - - - サンプルプロジェクトに沿って進めている場合は、`demo://{yourDomain}/android/YOUR_APP_PACKAGE_NAME/callback`に設定してください。 - -
    - -
    - [Auth0 Android](https://github.com/auth0/Auth0.Android) SDKをプロジェクトに追加します。ライブラリーはAuth0のAuthentication APIとManagement APIに要求を行います。 - - アプリの`build.gradle`依存関係セクションで、以下を追加します。 - - ``` - implementation 'com.auth0.android:auth0:2. ' - ``` - - AndroidとKotlinのプラグインのそれぞれに対して、Java 8+バイトコードをターゲットにするようにします。 -
    - -
    - SDKにはマニフェストのプレースホルダーが必要です。Auth0は内部でプレースホルダーを使用して、認証のCallback URLを捉える`intent-filter`を定義します。Auth0テナントのドメインとCallback URLスキームを設定する必要があります。 - - アクティビティーに特別な`intent-filter`を宣言する必要はありません。これは、マニフェストのプレースホルダーをAuth0**ドメイン** と**スキーム** の値で定義したため、ライブラリーがリダイレクトを処理します。 - - - ここでは、`auth0Scheme`に`demo`の値を使用したため、カスタムURLスキームをログイン後にAuth0がリダイレクトするURLに使用することができます。[Androidアプリのリンク](/docs/ja-jp/applications/enable-android-app-links)を使用したい場合は、`https`を使用する方法もあります。この値の設定に関する詳細情報は、[Auth0.Android SDKのREADME](https://github.com/auth0/Auth0.Android#a-note-about-app-deep-linking)をお読みください。 - -
    - -
    - SDKが正しく機能するためには、次のプロパティを`strings.xml`で設定しなければなりません: - - - `com_auth0_domain`:Auth0テナントのドメインです。通常、Auth0 Dashboardにあるアプリケーションの[Settings(設定)]の[Domain(ドメイン)]フィールドで確認できます。[カスタムドメイン](/docs/ja-jp/custom-domains)を使用している場合は、その値を代わりに設定してください。 - - `com_auth0_client_id`:このクイックスタートで前にセットアップしたAuth0アプリケーションのIDです。Auth0 Dashboardにあるアプリケーションの[Settings(設定)]の[Client ID(クライアントID)]フィールドで確認できます。 - - `AndroidManifest.xml`ファイルが`android.permissions.INTERNET`のアクセス許可を指定していることを確認します。 - - ```html - - ``` - - Android Studio内で**Sync Project with Gradle Files** を実行するか、コマンドラインから`./gradlew clean assembleDebug`を実行します。 - - - Gradleの使用に関する詳細は、[Gradleの公式のドキュメンテーション](https://gradle.org/getting-started-android-build/)を確認してください。 - -
    - -
    - アプリケーションに認証をセットアップするには、[ユニバーサルログイン](/docs/ja-jp/hosted-pages/login)が最も手軽な方法です。最良のエクスペリエンス、高い安全性、幅広い機能を活用するためにも、ユニバーサルログインの使用をお勧めします。 - - `onCreate`メソッドで、`Auth0`クラスの新しいインスタンスを作成し、ユーザー資格情報を保持します。 - - `loginWithBrowser`メソッドを作成し、`WebAuthProvider`クラスを使用して、[Auth0 Dashboard](https://manage.auth0.com/#/)のアプリケーションで有効にした接続で認証します。ここでは、初期設定の一部として`auth0Scheme`マニフェストのプレースホルダーで使用されたスキーム値を渡すことができます。 - - `WebAuthProvider#start`関数を呼び出した後、ブラウザーが起動し、ログインページが表示されます。ユーザーが認証を行うと、Callback URLが呼び出されます。Callback URLには、認証プロセスの最終結果が含まれています。 - - - ##### チェックポイント - loginWithBrowserを呼び出すアプリケーションにボタンを追加します。このボタンをクリックすると、AndroidアプリケーションによってAuth0ユニバーサルログインページにリダイレクトされ、ユーザー名とパスワードまたはソーシャルプロバイダーを使ってログインまたはサインアップできるようになったことを確認します。 - 完了したら、Auth0がアプリにリダイレクトで戻すことを確認します。 - -
    - -
    - `WebAuthProvider`を使用して、認証時にブラウザーで設定されたクッキーを削除すると、ユーザーは次回の認証試行時に、資格情報を再入力するよう求められます。 - - `logout`メソッドをアプリに追加してユーザーのセッションを削除し、アプリからログアウトします。ここでは、初期設定の一部として`auth0Scheme`マニフェストのプレースホルダーで使用されたスキーム値を渡すことができます。 - - `WebAuthProvider`クラスを使用して、ログアウトを実装します。この呼び出しによってブラウザーが開き、ユーザーはログアウトエンドポイントに移動されます。ユーザーがログアウトをキャンセルする場合は、ユーザーを前のURLにリダイレクトすることを検討してください。 - - - ##### チェックポイント - logoutを呼び出し、ユーザーをアプリケーションからログアウトするアプリにボタンを追加します。このボタンをクリックすると、Androidアプリがユーザーをログアウトページにリダイレクトしてからもう一度リダイレクトで戻すこと、そして、アプリケーションにログインしていないことを確認します。 - -
    - -
    - `AuthenticationAPIClient`クラスを使用して、[Auth0からユーザーのプロファイルを取得します](/docs/ja-jp/users/user-profiles#user-profile-management-api-access)。これには以下のものが必要です。 - - - ログインフェーズから返されるアクセストークン - - `WebAuthProvider.login`に`profile`スコープが含まれる必要がある - - ユーザーのメールアドレスを取得する必要がある場合は、`email`スコープを指定する必要があります。 - - - このクイックスタートで、上のログイン手順中にデフォルトで`openid profile email`スコープが設定されます。 - - - 以下に、ユーザーのプロファイルを取得して画面上に表示するために使用できる関数を示します。 - - - ##### チェックポイント - ログイン後にshowUserProfile関数を呼び出します。onSuccessコールバックがユーザーのプロファイル情報を返すことを確認します。 - -
    - - ## 次のステップ - - 成功です!ここまで来れば、アプリケーションにログイン、ログアウト、ユーザープロファイル情報が備わっているはずです。 - - これでクイックスタートチュートリアルは終了ですが、機能はまだまだたくさんあります。Auth0でできることについて詳しくは、以下をご覧ください。 - - * [Auth0 Dashboard](https://manage.auth0.com/#) - Auth0のテナントやアプリケーションを構成して管理する方法について説明します - * [Auth0.Android SDK](https://github.com/auth0/Auth0.Android) - このチュートリアルで使用されているSDKをより詳しく説明します - * [Auth0 Marketplace](https://marketplace.auth0.com/) - Auth0の機能性を拡張できる各種の統合を見つけられます -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    +--- +title: "Androidアプリケーションにログインを追加する" +permalink: "interactive" +'description': "このガイドでは、AndroidアプリケーションにAuth0 Android SDKを使ってAuth0を統合する方法を説明します。" +'og:title': "Androidアプリケーションにログインを追加する" +'og:description': "このガイドでは、AndroidアプリケーションにAuth0 Android SDKを使ってAuth0を統合する方法を説明します。" +'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/android.png" +'twitter:title': "Androidアプリケーションにログインを追加する" +'twitter:description': "このガイドでは、AndroidアプリケーションにAuth0 Android SDKを使ってAuth0を統合する方法を説明します。" +sidebarTitle: Android +--- + + +import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; +import { LoggedInForm } from "/snippets/Login.jsx"; +import Build from "/snippets/quickstart/native/android/build.gradle.mdx"; +import Build2 from "/snippets/quickstart/native/android/build.gradle2.mdx"; +import Strings from "/snippets/quickstart/native/android/strings.xml.mdx"; +import Mainactivity from "/snippets/quickstart/native/android/MainActivity.kt.mdx"; +import Mainactivity2 from "/snippets/quickstart/native/android/MainActivity.kt2.mdx"; +import Mainactivity3 from "/snippets/quickstart/native/android/MainActivity.kt3.mdx"; + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + +export const sections = [ + { id: "auth0を構成する", title: "Auth0を構成する" }, + { id: "auth0-android-sdkをインストールする", title: "Auth0 Android SDKをインストールする" }, + { id: "マニフェストのプレースホルダーを追加する", title: "マニフェストのプレースホルダーを追加する" }, + { id: "アプリケーションを構成する", title: "アプリケーションを構成する" }, + { id: "アプリケーションにログインを追加する", title: "アプリケーションにログインを追加する" }, + { id: "アプリケーションにログアウトを追加する", title: "アプリケーションにログアウトを追加する" }, + { id: "ユーザープロファイル情報を表示する", title: "ユーザープロファイル情報を表示する" } +] + + + +
    + Auth0のサービスを利用するには、Auth0 Dashboadに設定済みのアプリケーションがある必要があります。Auth0アプリケーションは、プロジェクトに認証を構成する場所です。 + + ### アプリケーションを構成する + + 対話型のセレクターを使ってAuth0アプリケーションを新規作成するか、統合したいプロジェクトを表す既存のアプリケーションを選択します。Auth0のすべてのアプリケーションには英数字からなる一意のクライアントIDが割り当てられており、アプリケーションのコードがSDKを通じてAuth0 APIを呼び出す際に使用されます。 + + このクイックスタートを使って構成されたすべての設定は、[Dashboard](https://manage.auth0.com/#/)のアプリケーションを自動更新します。今後、アプリケーションの管理もDashboardで行えます。 + + 代わりに完了済みの構成を見てみたい場合は、サンプルアプリケーションをご覧ください。 + + ### Callback URLを構成する + + Callback URLとは、Auth0によって認証後のユーザーをダイレクトするアプリケーションURLです。この値を設定していない場合、ユーザーはログイン後にアプリケーションに戻りません。 + + + サンプルプロジェクトに沿って進めている場合は、`demo://{yourDomain}/android/YOUR_APP_PACKAGE_NAME/callback`に設定してください。 + + + ### ログアウトURLを構成する + + ログアウトURLとは、Auth0によってログアウト後のユーザーをリダイレクトするアプリケーションURLです。この値を設定していない場合、ユーザーはアプリケーションからログアウトできず、エラーを受け取ります。 + + + サンプルプロジェクトに沿って進めている場合は、`demo://{yourDomain}/android/YOUR_APP_PACKAGE_NAME/callback`に設定してください。 + +
    + +
    + [Auth0 Android](https://github.com/auth0/Auth0.Android) SDKをプロジェクトに追加します。ライブラリーはAuth0のAuthentication APIとManagement APIに要求を行います。 + + アプリの`build.gradle`依存関係セクションで、以下を追加します。 + + ``` + implementation 'com.auth0.android:auth0:2. ' + ``` + + AndroidとKotlinのプラグインのそれぞれに対して、Java 8+バイトコードをターゲットにするようにします。 +
    + +
    + SDKにはマニフェストのプレースホルダーが必要です。Auth0は内部でプレースホルダーを使用して、認証のCallback URLを捉える`intent-filter`を定義します。Auth0テナントのドメインとCallback URLスキームを設定する必要があります。 + + アクティビティーに特別な`intent-filter`を宣言する必要はありません。これは、マニフェストのプレースホルダーをAuth0**ドメイン** と**スキーム** の値で定義したため、ライブラリーがリダイレクトを処理します。 + + + ここでは、`auth0Scheme`に`demo`の値を使用したため、カスタムURLスキームをログイン後にAuth0がリダイレクトするURLに使用することができます。[Androidアプリのリンク](/docs/ja-jp/applications/enable-android-app-links)を使用したい場合は、`https`を使用する方法もあります。この値の設定に関する詳細情報は、[Auth0.Android SDKのREADME](https://github.com/auth0/Auth0.Android#a-note-about-app-deep-linking)をお読みください。 + +
    + +
    + SDKが正しく機能するためには、次のプロパティを`strings.xml`で設定しなければなりません: + + - `com_auth0_domain`:Auth0テナントのドメインです。通常、Auth0 Dashboardにあるアプリケーションの[Settings(設定)]の[Domain(ドメイン)]フィールドで確認できます。[カスタムドメイン](/docs/ja-jp/custom-domains)を使用している場合は、その値を代わりに設定してください。 + - `com_auth0_client_id`:このクイックスタートで前にセットアップしたAuth0アプリケーションのIDです。Auth0 Dashboardにあるアプリケーションの[Settings(設定)]の[Client ID(クライアントID)]フィールドで確認できます。 + + `AndroidManifest.xml`ファイルが`android.permissions.INTERNET`のアクセス許可を指定していることを確認します。 + + ```html + + ``` + + Android Studio内で**Sync Project with Gradle Files** を実行するか、コマンドラインから`./gradlew clean assembleDebug`を実行します。 + + + Gradleの使用に関する詳細は、[Gradleの公式のドキュメンテーション](https://gradle.org/getting-started-android-build/)を確認してください。 + +
    + +
    + アプリケーションに認証をセットアップするには、[ユニバーサルログイン](/docs/ja-jp/hosted-pages/login)が最も手軽な方法です。最良のエクスペリエンス、高い安全性、幅広い機能を活用するためにも、ユニバーサルログインの使用をお勧めします。 + + `onCreate`メソッドで、`Auth0`クラスの新しいインスタンスを作成し、ユーザー資格情報を保持します。 + + `loginWithBrowser`メソッドを作成し、`WebAuthProvider`クラスを使用して、[Auth0 Dashboard](https://manage.auth0.com/#/)のアプリケーションで有効にした接続で認証します。ここでは、初期設定の一部として`auth0Scheme`マニフェストのプレースホルダーで使用されたスキーム値を渡すことができます。 + + `WebAuthProvider#start`関数を呼び出した後、ブラウザーが起動し、ログインページが表示されます。ユーザーが認証を行うと、Callback URLが呼び出されます。Callback URLには、認証プロセスの最終結果が含まれています。 + + + ##### チェックポイント + loginWithBrowserを呼び出すアプリケーションにボタンを追加します。このボタンをクリックすると、AndroidアプリケーションによってAuth0ユニバーサルログインページにリダイレクトされ、ユーザー名とパスワードまたはソーシャルプロバイダーを使ってログインまたはサインアップできるようになったことを確認します。 + 完了したら、Auth0がアプリにリダイレクトで戻すことを確認します。 + +
    + +
    + `WebAuthProvider`を使用して、認証時にブラウザーで設定されたクッキーを削除すると、ユーザーは次回の認証試行時に、資格情報を再入力するよう求められます。 + + `logout`メソッドをアプリに追加してユーザーのセッションを削除し、アプリからログアウトします。ここでは、初期設定の一部として`auth0Scheme`マニフェストのプレースホルダーで使用されたスキーム値を渡すことができます。 + + `WebAuthProvider`クラスを使用して、ログアウトを実装します。この呼び出しによってブラウザーが開き、ユーザーはログアウトエンドポイントに移動されます。ユーザーがログアウトをキャンセルする場合は、ユーザーを前のURLにリダイレクトすることを検討してください。 + + + ##### チェックポイント + logoutを呼び出し、ユーザーをアプリケーションからログアウトするアプリにボタンを追加します。このボタンをクリックすると、Androidアプリがユーザーをログアウトページにリダイレクトしてからもう一度リダイレクトで戻すこと、そして、アプリケーションにログインしていないことを確認します。 + +
    + +
    + `AuthenticationAPIClient`クラスを使用して、[Auth0からユーザーのプロファイルを取得します](/docs/ja-jp/users/user-profiles#user-profile-management-api-access)。これには以下のものが必要です。 + + - ログインフェーズから返されるアクセストークン + - `WebAuthProvider.login`に`profile`スコープが含まれる必要がある + + ユーザーのメールアドレスを取得する必要がある場合は、`email`スコープを指定する必要があります。 + + + このクイックスタートで、上のログイン手順中にデフォルトで`openid profile email`スコープが設定されます。 + + + 以下に、ユーザーのプロファイルを取得して画面上に表示するために使用できる関数を示します。 + + + ##### チェックポイント + ログイン後にshowUserProfile関数を呼び出します。onSuccessコールバックがユーザーのプロファイル情報を返すことを確認します。 + +
    + + ## 次のステップ + + 成功です!ここまで来れば、アプリケーションにログイン、ログアウト、ユーザープロファイル情報が備わっているはずです。 + + これでクイックスタートチュートリアルは終了ですが、機能はまだまだたくさんあります。Auth0でできることについて詳しくは、以下をご覧ください。 + + * [Auth0 Dashboard](https://manage.auth0.com/#) - Auth0のテナントやアプリケーションを構成して管理する方法について説明します + * [Auth0.Android SDK](https://github.com/auth0/Auth0.Android) - このチュートリアルで使用されているSDKをより詳しく説明します + * [Auth0 Marketplace](https://marketplace.auth0.com/) - Auth0の機能性を拡張できる各種の統合を見つけられます +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    diff --git a/main/docs/ja-jp/quickstart/native/device/interactive.mdx b/main/docs/ja-jp/quickstart/native/device/interactive.mdx index 1cf1b65ca..446d94d0b 100644 --- a/main/docs/ja-jp/quickstart/native/device/interactive.mdx +++ b/main/docs/ja-jp/quickstart/native/device/interactive.mdx @@ -1,495 +1,497 @@ ---- -title: "デバイス認可フロー" -permalink: "interactive" -'description': "このチュートリアルでは、デバイス認可フローを使用して、入力に制約のあるデバイスからAPIを呼び出す方法について説明します。" -'og:title': "デバイス認可フロー" -'og:description': "このチュートリアルでは、デバイス認可フローを使用して、入力に制約のあるデバイスからAPIを呼び出す方法について説明します。" -'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/device.svg" -'twitter:title': "デバイス認可フロー" -'twitter:description': "このチュートリアルでは、デバイス認可フローを使用して、入力に制約のあるデバイスからAPIを呼び出す方法について説明します。" ---- - -import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; -import { LoggedInForm } from "/snippets/Login.jsx"; - -export const sections = [ - { id: "前提条件", title: "前提条件" }, - { id: "デバイスコードを要求する", title: "デバイスコードを要求する" }, - { id: "デバイスコードを受け取る", title: "デバイスコードを受け取る" }, - { id: "デバイスのアクティベーションを要求する", title: "デバイスのアクティベーションを要求する" }, - { id: "トークンエンドポイントをポーリングする", title: "トークンエンドポイントをポーリングする" }, - { id: "ユーザーの認可", title: "ユーザーの認可" }, - { id: "トークンを受け取る", title: "トークンを受け取る" }, - { id: "apiを呼び出す", title: "APIを呼び出す" }, - { id: "リフレッシュトークン", title: "リフレッシュトークン" }, - { id: "トラブルシューティング", title: "トラブルシューティング" }, - { id: "実装例", title: "実装例" }, - { id: "制限事項", title: "制限事項" } -] - - - - このチュートリアルでは、デバイス認可フローを使用して、入力に制約のあるデバイスからAPIを呼び出す方法について説明します。 ログインして、アカウント用に構成された例を参考にこのクイックタートに従うことをお勧めします。対話型のエクスペリエンスには、Device Flow Playgroundを使用することができます。 - -
    - - ネイティブアプリケーションを登録する。 - - **OIDC準拠** のトグルが有効になっていることを確認する。詳細については、「OIDC準拠の認証」をお読みください。 - - アプリケーションの付与タイプに**デバイスコード** を追加する。詳細については、「付与タイプを更新する」をお読みください。 - - リフレッシュトークンを有効にしたい場合には、アプリケーションの付与タイプに**リフレッシュトークン** を追加する。 - - アプリケーションに少なくとも1つの接続を構成して有効化する。 - - APIをAuth0に登録する。 - - - リフレッシュトークンを使用している場合には、**[Allow Offline Access(オフラインアクセスの許可)]** を有効にする。詳細については、「APIの設定」をお読みください。 - - デバイスのユーザーコードの設定を構成して、ランダムに生成されたユーザーコードの文字セット、形式、長さを定義する。 -
    - -
    - ユーザーがデバイスアプリケーションを起動して、それを認可したい場合には、アプリケーションがAuth0 Authentication APIからのデバイスコードを要求して、ユーザーのセッションに関連付けなければなりません。 - - デバイスコードを取得するには、アプリケーションがAuthentication APIのデバイス認可フローで[認証エンドポイント](https://auth0.com/docs/api/authentication#-post-oauth-device-code-)を呼び出す必要があります: - - - ```bash cURL lines - curl --request post \ - --url 'https://dev-gja8kxz4ndtex3rq.us.auth0.com/oauth/device/code' \ - --header 'content-type: application/x-www-form-urlencoded' - ``` - ```csharp C# lines - var client = new RestClient("https://dev-gja8kxz4ndtex3rq.us.auth0.com/oauth/device/code"); - var request = new RestRequest(Method.POST); - request.AddHeader("content-type", "application/x-www-form-urlencoded"); - IRestResponse response = client.Execute(request); - ``` - - ```go Go lines - package main - import ( - "fmt" - "net/http" - "io/ioutil" - ) - func main() { - url := "https://dev-gja8kxz4ndtex3rq.us.auth0.com/oauth/device/code" - req, _ := http.NewRequest("post", url, nil) - req.Header.Add("content-type", "application/x-www-form-urlencoded") - res, _ := http.DefaultClient.Do(req) - defer res.Body.Close() - body, _ := ioutil.ReadAll(res.Body) - fmt.Println(res) - fmt.Println(string(body)) - } - ``` - ```java Java lines - HttpResponse response = Unirest.post("https://dev-gja8kxz4ndtex3rq.us.auth0.com/oauth/device/code") - .header("content-type", "application/x-www-form-urlencoded") - .asString(); - ``` - ```javascript Node.JS lines - var axios = require("axios").default; - var options = { - method: 'post', - url: 'https://dev-gja8kxz4ndtex3rq.us.auth0.com/oauth/device/code', - headers: {'content-type': 'application/x-www-form-urlencoded'} - }; - axios.request(options).then(function (response) { - console.log(response.data); - }).catch(function (error) { - console.error(error); - }); - ``` - ```obj-c Obj-C lines - #import - NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; - NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://dev-gja8kxz4ndtex3rq.us.auth0.com/oauth/device/code"] - cachePolicy:NSURLRequestUseProtocolCachePolicy - - timeoutInterval:10.0]; - - [request setHTTPMethod:@"post"]; - [request setAllHTTPHeaderFields:headers]; - NSURLSession *session = [NSURLSession sharedSession]; - NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request - completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { - - if (error) { - - NSLog(@"%@", error); - - } else { - - NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response; - - NSLog(@"%@", httpResponse); - - } - - }]; - - [dataTask resume]; - ``` - ```php PHP lines - $curl = curl_init(); - curl_setopt_array($curl, [ - CURLOPT_URL => "https://dev-gja8kxz4ndtex3rq.us.auth0.com/oauth/device/code", - CURLOPT_RETURNTRANSFER => true, - CURLOPT_ENCODING => "", - CURLOPT_MAXREDIRS => 10, - CURLOPT_TIMEOUT => 30, - CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, - CURLOPT_CUSTOMREQUEST => "post", - CURLOPT_HTTPHEADER => [ - "content-type: application/x-www-form-urlencoded" - - ], - ]); - $response = curl_exec($curl); - $err = curl_error($curl); - curl_close($curl); - if ($err) { - echo "cURL Error #:" . $err; - } else { - echo $response; - } - ``` - ```python Python lines - import http.client - conn = http.client.HTTPSConnection("") - headers = { 'content-type': "application/x-www-form-urlencoded" } - conn.request("post", "/dev-gja8kxz4ndtex3rq.us.auth0.com/oauth/device/code", headers=headers) - res = conn.getresponse() - data = res.read() - print(data.decode("utf-8")) - ``` - ```ruby Ruby lines - require 'uri' - require 'net/http' - require 'openssl' - url = URI("https://dev-gja8kxz4ndtex3rq.us.auth0.com/oauth/device/code") - http = Net::HTTP.new(url.host, url.port) - http.use_ssl = true - http.verify_mode = OpenSSL::SSL::VERIFY_NONE - request = Net::HTTP::Post.new(url) - request["content-type"] = 'application/x-www-form-urlencoded' - response = http.request(request) - puts response.read_body - ``` - ```swift Swift lines - import Foundation - let headers = ["content-type": "application/x-www-form-urlencoded"] - let request = NSMutableURLRequest(url: NSURL(string: "https://dev-gja8kxz4ndtex3rq.us.auth0.com/oauth/device/code")! as URL, - cachePolicy: .useProtocolCachePolicy, - - timeoutInterval: 10.0) - - request.httpMethod = "post" - request.allHTTPHeaderFields = headers - let session = URLSession.shared - let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in - if (error != nil) { - print(error) - - } else { - let httpResponse = response as? HTTPURLResponse - - print(httpResponse) - - } - }) - dataTask.resume() - ``` - - -
    - -
    - デバイスアプリケーションはHTTP 200応答と次のようなペイロードを受け取るはずです: - - ``` - { - "device_code": "GmRh...k9eS", - "user_code": "WDJB-MJHT", - "verification_uri": "https://my-tenant.auth0.com/device", - "verification_uri_complete": "https://my-tenant.auth0.com/device?user_code=WDJB-MJHT", - "expires_in": 900, - "interval": 5 - } - ``` -
    - -
    - デバイスアプリケーションは、`device_code`と`user_code`の受信後に、ユーザーに`verification_uri`で`user_code`を入力するよう指示する必要があります。 - - ![](/docs/images/ja-jp/cdy7uua7fh8z/3Q9q41wocl6SojRoiGefXT/a98582a3c86740aaeb3d957f2dc4afe6/request-device-activation.png) - - - `device_code`はユーザーに直接提供するものではないため、ユーザーが混乱しないように、処理中に表示するべきではありません。 - - - - CLIをビルドする際は、この手順をスキップし、`verification_uri_complete`を使って直接ブラウザーを開くことができます。 - -
    - -
    - ユーザーによるアクティベーションを待っている間、デバイスアプリケーションはAuthentication API [POST /oauth/tokenエンドポイント](https://auth0.com/docs/api/authentication#-post-oauth-token-)を断続的に呼び出して、応答を適切に処理する必要があります。 - - - デバイスアプリケーションが確実にその`interval`(秒単位)または成功応答の受信で長い方の時間を待機して、ネットワーク遅延の問題を回避するようにします。 - - - ``` - curl --request POST \ - --url 'https://{yourDomain}/oauth/token' \ - --header 'content-type: application/x-www-form-urlencoded' \ - --data grant_type=urn:ietf:params:oauth:grant-type:device_code \ - --data device_code=AUTH0_SCOPES \ - --data 'client_id={yourClientId}' - ``` -
    - -
    - ユーザーはQRコードをスキャンするか、アクティベーションページを開いてユーザーコードを入力します: - - ![](/docs/images/ja-jp/cdy7uua7fh8z/7IwrVX4s5a36CvfY95rKCo/1f0734161a6e1fb6acbefb674896bf74/Device_Activation_-_Japanese.png) - - 確認ページが表示され、ユーザーが正しいデバイスであることを確認します: - - ![](/docs/images/ja-jp/cdy7uua7fh8z/5dwhOyM1HRNwfV3Co4Da2o/41706a37843a99b6c21117d4aebcd881/Device_Confirmation_-_Japanese.png) - - ユーザーがサインインして、トランザクションが完了します。この手順には、以下の1つ以上のプロセスが含まれます。 - - - ユーザーを認証する - - 認証を行うために、ユーザーをIDプロバイダーへリダイレクトする - - アクティブなSSOセッションを確認する - - デバイスに関してユーザーの同意がまだ得られていない場合には、同意を得る - - ![](/docs/images/ja-jp/cdy7uua7fh8z/3GqqaNB7sjcAYTQiTnEEsn/26ff7d214f4f02f4a703941908045cd1/Login_screen_-_Japanese.png) - - 認証と同意が成功すると、確認のプロンプトが表示されます: - - ![](/docs/images/ja-jp/cdy7uua7fh8z/2TsQpMa8fzifiojuEXLvDo/2e19d86a58bb4af653307f3086911d87/Success_message_-_Japanese.png) - - この時点で、ユーザーの認証とデバイスの認可は完了しています。 -
    - -
    - ユーザーがデバイスアプリケーションを認可すると、HTTP 200応答と次のペイロードを受け取ります: - - ``` - { - "access_token": "eyJz93a...k4laUWw", - "refresh_token": "GEbRxBN...edjnXbL", - "id_token": "eyJ0XAi...4faeEoQ", - "token_type": "Bearer", - "expires_in": 86400 - } - ``` - - - トークンは検証してから保存します。方法については、「**アクセストークンを検証する** 」と「**IDトークンを検証する** 」をお読みください。 - - - アクセストークンは、Authentication APIの[ユーザー情報取得エンドポイント](https://auth0.com/docs/api/authentication#get-user-info)(デバイスアプリケーションが`openid`スコープを要求した場合)、または`audience`パラメーターが指定したAPIを呼び出すために使用されます。独自のAPIを呼び出す場合には、デバイスアプリケーションは使用する前にアクセストークンを検証しなければなりません。 - - IDトークンには、[デコードと抽出](/docs/ja-jp/tokens/id-tokens#id-token-payload)が必要なユーザー情報が含まれています。デバイスアプリケーションが`openid`スコープを要求した場合には、Authentication APIは`id_token`のみを返します。 - - リフレッシュトークンは、アクセストークンまたはIDトークンの期限が切れたときに、新しいトークンの取得に使用されます。`audience`パラメーターが指定するAPIに**[Allow Offline Access(オフラインアクセスの許可)]** 設定が有効化されていて、デバイスアプリケーションが`offline_access`スコープを要求した場合には、Authentication APIは`refresh_token`のみを返します。 -
    - -
    - APIを呼び出すには、デバイスアプリケーションはアクセストークンをベアラートークンとしてHTTP要求の`Authorization`ヘッダーで渡さなければなりません。 - - ``` - curl --request GET \ - --url https://myapi.com/api \ - --header 'authorization: Bearer AUTH0_API_ACCESS_TOKEN' \ - --header 'content-type: application/json' - ``` -
    - -
    - ユーザーに新しいアクセストークンを取得するために、デバイスアプリケーションは、`refresh_token`パラメーターを指定してAuthentication API [POST /oauth/tokenエンドポイント](https://auth0.com/docs/api/authentication#-post-oauth-token-)を呼び出すことができます。 - - ``` - curl --request POST \ - --url 'https://{yourDomain}/oauth/token' \ - --header 'content-type: application/x-www-form-urlencoded' \ - --data grant_type=refresh_token \ - --data 'client_id={yourClientId}' \ - --data 'client_secret={yourClientSecret}' \ - --data refresh_token=AUTH0_REFRESH_TOKEN - ``` - - 要求が成功すると、デバイスアプリケーションはHTTP 200応答で次のペイロードを受け取ります: - - ``` - { - "access_token": "eyJ...MoQ", - "expires_in": 86400, - "scope": "openid offline_access", - "id_token": "eyJ...0NE", - "token_type": "Bearer" - } - ``` - - リフレッシュトークンの詳細については、「[リフレッシュトークン](/docs/ja-jp/secure/tokens/refresh-tokens)」をお読みください。 -
    - -
    - テナントログは実行されるあらゆるやり取りを記録し、問題の解決に利用することができます。 - - | \*\*コード\*\* | \*\*名前\*\* | \*\*説明\*\* | - | --- | --- | --- | - | `fdeaz` | デバイス認可要求の失敗 | | - | `fdeac` | デバイスのアクティベーションに失敗 | | - | `fdecc` | ユーザーがデバイス確認をキャンセル | | - | `fede` | 交換の失敗 | アクセストークンのデバイスコード | - | `sede` | 交換の成功 | アクセストークンのデバイスコード | - - ### トークンの応答 - - ユーザーによるデバイスの認可を待っている間には、さまざまなHTTP 4xx応答を受け取ります。 - - #### 認可待ち - - このエラーは、ユーザーの操作を待っている間に表示されます。このチュートリアルの前の手順で推奨されている`interval`を使ってポーリングを継続してください。 - - ``` - `HTTP 403` - { - "error": "authorization_pending", - "error_description": "..." - } - ``` - - #### 減速 - - ポーリングが速すぎます。このチュートリアルの前の手順で推奨されている間隔を使ってポーリングしてください。ネットワーク遅延が原因でこのエラーを受け取ることを避けるには、ポーリング要求の応答を受け取ってから間隔をカウントし始めるようにします。 - - ``` - `HTTP 429` - { - "error": "slow_down", - "error_description": "..." - } - ``` - - #### 有効期限切れのトークン - - ユーザーによるデバイスの認可が遅かったため、`device_code`の期限が切れました。アプリケーションはユーザーにフローの失効を通知して、フローをもう一度始めるように促す必要があります。 - - - `expired_token`エラーは一度だけ返されます。それ以降は、エンドポイントが`invalid_grant`エラーを返します。 - - - ``` - `HTTP 403` - { - "error": "expired_token", - "error_description": "..." - } - ``` - - #### アクセス拒否 - - アクセスが拒否された場合には、次を受け取ります: - - ``` - `HTTP 403` - { - "error": "access_denied", - "error_description": "..." - } - ``` - - これは、以下を含むさまざまな原因で発生します。 - - - ユーザーがデバイスの認可を拒否した。 - - 認可サーバーがトランザクションを拒否した。 - - 構成済みのアクションがアクセスを拒否した。 -
    - -
    - 以下の例を参考に、このフローを実際のアプリケーションに実装する方法を確認してください。 - - - [Device Authorization Playground](https://auth0.github.io/device-flow-playground/) - - [AppleTV(Swift)](https://github.com/pushpabrol/auth0-device-flow-appletv):AppleTVからのデバイス認可フローにAuth0を使用する方法を示す簡素なアプリケーションです。 - - [CLI(Node.js)](https://gist.github.com/panva/652c61e7d847e0ed99926c324fa91b36):認可コードフローではなく、デバイス認可フローを使用するCLIの実装例です。大きな違いは、CLIがWebサーバーのホスティングやポートの待ち受けを必要としないことです。 -
    - -
    - デバイス認可フローを使用するには、デバイスアプリケーションに以下が必要です。 - - - Server Name Indication(SNI)に対応している - - ネイティブアプリケーション - - [認証方法](/docs/ja-jp/secure/application-credentials#application-authentication-methods)が**[None(なし)]** に設定されている - - [OIDCに準拠](/docs/ja-jp/dashboard/reference/settings-application#oauth) - - 動的クライアント登録(Dynamic Client Registration) - - また、デバイス認可フローには以下を使用できません: - - - Auth0の開発者キーを使用したソーシャル接続(新しいユニバーサルログインエクスペリエンス - - ホストされたログインページやアクションからクエリ文字列パラメーターへのアクセス -
    - - ## 次のステップ - 成功です!ここまで来れば、アプリケーションにログイン、ログアウト、ユーザープロファイル情報が備わっているはずです。 - - これでクイックスタートチュートリアルは終了ですが、機能はまだまだたくさんあります。Auth0でできることについて詳しくは、以下をご覧ください。 - - - [Auth0 Dashboard](https://manage.auth0.com/#) - Auth0のテナントやアプリケーションを構成して管理する方法について説明します - - - [Auth0 Marketplace](https://marketplace.auth0.com/) - Auth0の機能性を拡張できる各種の統合を見つけられます -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    +--- +title: "デバイス認可フロー" +permalink: "interactive" +'description': "このチュートリアルでは、デバイス認可フローを使用して、入力に制約のあるデバイスからAPIを呼び出す方法について説明します。" +'og:title': "デバイス認可フロー" +'og:description': "このチュートリアルでは、デバイス認可フローを使用して、入力に制約のあるデバイスからAPIを呼び出す方法について説明します。" +'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/device.svg" +'twitter:title': "デバイス認可フロー" +'twitter:description': "このチュートリアルでは、デバイス認可フローを使用して、入力に制約のあるデバイスからAPIを呼び出す方法について説明します。" +--- + +import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; +import { LoggedInForm } from "/snippets/Login.jsx"; + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + +export const sections = [ + { id: "前提条件", title: "前提条件" }, + { id: "デバイスコードを要求する", title: "デバイスコードを要求する" }, + { id: "デバイスコードを受け取る", title: "デバイスコードを受け取る" }, + { id: "デバイスのアクティベーションを要求する", title: "デバイスのアクティベーションを要求する" }, + { id: "トークンエンドポイントをポーリングする", title: "トークンエンドポイントをポーリングする" }, + { id: "ユーザーの認可", title: "ユーザーの認可" }, + { id: "トークンを受け取る", title: "トークンを受け取る" }, + { id: "apiを呼び出す", title: "APIを呼び出す" }, + { id: "リフレッシュトークン", title: "リフレッシュトークン" }, + { id: "トラブルシューティング", title: "トラブルシューティング" }, + { id: "実装例", title: "実装例" }, + { id: "制限事項", title: "制限事項" } +] + + + + このチュートリアルでは、デバイス認可フローを使用して、入力に制約のあるデバイスからAPIを呼び出す方法について説明します。 ログインして、アカウント用に構成された例を参考にこのクイックタートに従うことをお勧めします。対話型のエクスペリエンスには、Device Flow Playgroundを使用することができます。 + +
    + - ネイティブアプリケーションを登録する。 + - **OIDC準拠** のトグルが有効になっていることを確認する。詳細については、「OIDC準拠の認証」をお読みください。 + - アプリケーションの付与タイプに**デバイスコード** を追加する。詳細については、「付与タイプを更新する」をお読みください。 + - リフレッシュトークンを有効にしたい場合には、アプリケーションの付与タイプに**リフレッシュトークン** を追加する。 + - アプリケーションに少なくとも1つの接続を構成して有効化する。 + - APIをAuth0に登録する。 + + - リフレッシュトークンを使用している場合には、**[Allow Offline Access(オフラインアクセスの許可)]** を有効にする。詳細については、「APIの設定」をお読みください。 + - デバイスのユーザーコードの設定を構成して、ランダムに生成されたユーザーコードの文字セット、形式、長さを定義する。 +
    + +
    + ユーザーがデバイスアプリケーションを起動して、それを認可したい場合には、アプリケーションがAuth0 Authentication APIからのデバイスコードを要求して、ユーザーのセッションに関連付けなければなりません。 + + デバイスコードを取得するには、アプリケーションがAuthentication APIのデバイス認可フローで[認証エンドポイント](https://auth0.com/docs/api/authentication#-post-oauth-device-code-)を呼び出す必要があります: + + + ```bash cURL lines + curl --request post \ + --url 'https://dev-gja8kxz4ndtex3rq.us.auth0.com/oauth/device/code' \ + --header 'content-type: application/x-www-form-urlencoded' + ``` + ```csharp C# lines + var client = new RestClient("https://dev-gja8kxz4ndtex3rq.us.auth0.com/oauth/device/code"); + var request = new RestRequest(Method.POST); + request.AddHeader("content-type", "application/x-www-form-urlencoded"); + IRestResponse response = client.Execute(request); + ``` + + ```go Go lines + package main + import ( + "fmt" + "net/http" + "io/ioutil" + ) + func main() { + url := "https://dev-gja8kxz4ndtex3rq.us.auth0.com/oauth/device/code" + req, _ := http.NewRequest("post", url, nil) + req.Header.Add("content-type", "application/x-www-form-urlencoded") + res, _ := http.DefaultClient.Do(req) + defer res.Body.Close() + body, _ := ioutil.ReadAll(res.Body) + fmt.Println(res) + fmt.Println(string(body)) + } + ``` + ```java Java lines + HttpResponse response = Unirest.post("https://dev-gja8kxz4ndtex3rq.us.auth0.com/oauth/device/code") + .header("content-type", "application/x-www-form-urlencoded") + .asString(); + ``` + ```javascript Node.JS lines + var axios = require("axios").default; + var options = { + method: 'post', + url: 'https://dev-gja8kxz4ndtex3rq.us.auth0.com/oauth/device/code', + headers: {'content-type': 'application/x-www-form-urlencoded'} + }; + axios.request(options).then(function (response) { + console.log(response.data); + }).catch(function (error) { + console.error(error); + }); + ``` + ```obj-c Obj-C lines + #import + NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; + NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://dev-gja8kxz4ndtex3rq.us.auth0.com/oauth/device/code"] + cachePolicy:NSURLRequestUseProtocolCachePolicy + + timeoutInterval:10.0]; + + [request setHTTPMethod:@"post"]; + [request setAllHTTPHeaderFields:headers]; + NSURLSession *session = [NSURLSession sharedSession]; + NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request + completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { + + if (error) { + + NSLog(@"%@", error); + + } else { + + NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response; + + NSLog(@"%@", httpResponse); + + } + + }]; + + [dataTask resume]; + ``` + ```php PHP lines + $curl = curl_init(); + curl_setopt_array($curl, [ + CURLOPT_URL => "https://dev-gja8kxz4ndtex3rq.us.auth0.com/oauth/device/code", + CURLOPT_RETURNTRANSFER => true, + CURLOPT_ENCODING => "", + CURLOPT_MAXREDIRS => 10, + CURLOPT_TIMEOUT => 30, + CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, + CURLOPT_CUSTOMREQUEST => "post", + CURLOPT_HTTPHEADER => [ + "content-type: application/x-www-form-urlencoded" + + ], + ]); + $response = curl_exec($curl); + $err = curl_error($curl); + curl_close($curl); + if ($err) { + echo "cURL Error #:" . $err; + } else { + echo $response; + } + ``` + ```python Python lines + import http.client + conn = http.client.HTTPSConnection("") + headers = { 'content-type': "application/x-www-form-urlencoded" } + conn.request("post", "/dev-gja8kxz4ndtex3rq.us.auth0.com/oauth/device/code", headers=headers) + res = conn.getresponse() + data = res.read() + print(data.decode("utf-8")) + ``` + ```ruby Ruby lines + require 'uri' + require 'net/http' + require 'openssl' + url = URI("https://dev-gja8kxz4ndtex3rq.us.auth0.com/oauth/device/code") + http = Net::HTTP.new(url.host, url.port) + http.use_ssl = true + http.verify_mode = OpenSSL::SSL::VERIFY_NONE + request = Net::HTTP::Post.new(url) + request["content-type"] = 'application/x-www-form-urlencoded' + response = http.request(request) + puts response.read_body + ``` + ```swift Swift lines + import Foundation + let headers = ["content-type": "application/x-www-form-urlencoded"] + let request = NSMutableURLRequest(url: NSURL(string: "https://dev-gja8kxz4ndtex3rq.us.auth0.com/oauth/device/code")! as URL, + cachePolicy: .useProtocolCachePolicy, + + timeoutInterval: 10.0) + + request.httpMethod = "post" + request.allHTTPHeaderFields = headers + let session = URLSession.shared + let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in + if (error != nil) { + print(error) + + } else { + let httpResponse = response as? HTTPURLResponse + + print(httpResponse) + + } + }) + dataTask.resume() + ``` + + +
    + +
    + デバイスアプリケーションはHTTP 200応答と次のようなペイロードを受け取るはずです: + + ``` + { + "device_code": "GmRh...k9eS", + "user_code": "WDJB-MJHT", + "verification_uri": "https://my-tenant.auth0.com/device", + "verification_uri_complete": "https://my-tenant.auth0.com/device?user_code=WDJB-MJHT", + "expires_in": 900, + "interval": 5 + } + ``` +
    + +
    + デバイスアプリケーションは、`device_code`と`user_code`の受信後に、ユーザーに`verification_uri`で`user_code`を入力するよう指示する必要があります。 + + ![](/docs/images/ja-jp/cdy7uua7fh8z/3Q9q41wocl6SojRoiGefXT/a98582a3c86740aaeb3d957f2dc4afe6/request-device-activation.png) + + + `device_code`はユーザーに直接提供するものではないため、ユーザーが混乱しないように、処理中に表示するべきではありません。 + + + + CLIをビルドする際は、この手順をスキップし、`verification_uri_complete`を使って直接ブラウザーを開くことができます。 + +
    + +
    + ユーザーによるアクティベーションを待っている間、デバイスアプリケーションはAuthentication API [POST /oauth/tokenエンドポイント](https://auth0.com/docs/api/authentication#-post-oauth-token-)を断続的に呼び出して、応答を適切に処理する必要があります。 + + + デバイスアプリケーションが確実にその`interval`(秒単位)または成功応答の受信で長い方の時間を待機して、ネットワーク遅延の問題を回避するようにします。 + + + ``` + curl --request POST \ + --url 'https://{yourDomain}/oauth/token' \ + --header 'content-type: application/x-www-form-urlencoded' \ + --data grant_type=urn:ietf:params:oauth:grant-type:device_code \ + --data device_code=AUTH0_SCOPES \ + --data 'client_id={yourClientId}' + ``` +
    + +
    + ユーザーはQRコードをスキャンするか、アクティベーションページを開いてユーザーコードを入力します: + + ![](/docs/images/ja-jp/cdy7uua7fh8z/7IwrVX4s5a36CvfY95rKCo/1f0734161a6e1fb6acbefb674896bf74/Device_Activation_-_Japanese.png) + + 確認ページが表示され、ユーザーが正しいデバイスであることを確認します: + + ![](/docs/images/ja-jp/cdy7uua7fh8z/5dwhOyM1HRNwfV3Co4Da2o/41706a37843a99b6c21117d4aebcd881/Device_Confirmation_-_Japanese.png) + + ユーザーがサインインして、トランザクションが完了します。この手順には、以下の1つ以上のプロセスが含まれます。 + + - ユーザーを認証する + - 認証を行うために、ユーザーをIDプロバイダーへリダイレクトする + - アクティブなSSOセッションを確認する + - デバイスに関してユーザーの同意がまだ得られていない場合には、同意を得る + + ![](/docs/images/ja-jp/cdy7uua7fh8z/3GqqaNB7sjcAYTQiTnEEsn/26ff7d214f4f02f4a703941908045cd1/Login_screen_-_Japanese.png) + + 認証と同意が成功すると、確認のプロンプトが表示されます: + + ![](/docs/images/ja-jp/cdy7uua7fh8z/2TsQpMa8fzifiojuEXLvDo/2e19d86a58bb4af653307f3086911d87/Success_message_-_Japanese.png) + + この時点で、ユーザーの認証とデバイスの認可は完了しています。 +
    + +
    + ユーザーがデバイスアプリケーションを認可すると、HTTP 200応答と次のペイロードを受け取ります: + + ``` + { + "access_token": "eyJz93a...k4laUWw", + "refresh_token": "GEbRxBN...edjnXbL", + "id_token": "eyJ0XAi...4faeEoQ", + "token_type": "Bearer", + "expires_in": 86400 + } + ``` + + + トークンは検証してから保存します。方法については、「**アクセストークンを検証する** 」と「**IDトークンを検証する** 」をお読みください。 + + + アクセストークンは、Authentication APIの[ユーザー情報取得エンドポイント](https://auth0.com/docs/api/authentication#get-user-info)(デバイスアプリケーションが`openid`スコープを要求した場合)、または`audience`パラメーターが指定したAPIを呼び出すために使用されます。独自のAPIを呼び出す場合には、デバイスアプリケーションは使用する前にアクセストークンを検証しなければなりません。 + + IDトークンには、[デコードと抽出](/docs/ja-jp/tokens/id-tokens#id-token-payload)が必要なユーザー情報が含まれています。デバイスアプリケーションが`openid`スコープを要求した場合には、Authentication APIは`id_token`のみを返します。 + + リフレッシュトークンは、アクセストークンまたはIDトークンの期限が切れたときに、新しいトークンの取得に使用されます。`audience`パラメーターが指定するAPIに**[Allow Offline Access(オフラインアクセスの許可)]** 設定が有効化されていて、デバイスアプリケーションが`offline_access`スコープを要求した場合には、Authentication APIは`refresh_token`のみを返します。 +
    + +
    + APIを呼び出すには、デバイスアプリケーションはアクセストークンをベアラートークンとしてHTTP要求の`Authorization`ヘッダーで渡さなければなりません。 + + ``` + curl --request GET \ + --url https://myapi.com/api \ + --header 'authorization: Bearer AUTH0_API_ACCESS_TOKEN' \ + --header 'content-type: application/json' + ``` +
    + +
    + ユーザーに新しいアクセストークンを取得するために、デバイスアプリケーションは、`refresh_token`パラメーターを指定してAuthentication API [POST /oauth/tokenエンドポイント](https://auth0.com/docs/api/authentication#-post-oauth-token-)を呼び出すことができます。 + + ``` + curl --request POST \ + --url 'https://{yourDomain}/oauth/token' \ + --header 'content-type: application/x-www-form-urlencoded' \ + --data grant_type=refresh_token \ + --data 'client_id={yourClientId}' \ + --data 'client_secret={yourClientSecret}' \ + --data refresh_token=AUTH0_REFRESH_TOKEN + ``` + + 要求が成功すると、デバイスアプリケーションはHTTP 200応答で次のペイロードを受け取ります: + + ``` + { + "access_token": "eyJ...MoQ", + "expires_in": 86400, + "scope": "openid offline_access", + "id_token": "eyJ...0NE", + "token_type": "Bearer" + } + ``` + + リフレッシュトークンの詳細については、「[リフレッシュトークン](/docs/ja-jp/secure/tokens/refresh-tokens)」をお読みください。 +
    + +
    + テナントログは実行されるあらゆるやり取りを記録し、問題の解決に利用することができます。 + + | \*\*コード\*\* | \*\*名前\*\* | \*\*説明\*\* | + | --- | --- | --- | + | `fdeaz` | デバイス認可要求の失敗 | | + | `fdeac` | デバイスのアクティベーションに失敗 | | + | `fdecc` | ユーザーがデバイス確認をキャンセル | | + | `fede` | 交換の失敗 | アクセストークンのデバイスコード | + | `sede` | 交換の成功 | アクセストークンのデバイスコード | + + ### トークンの応答 + + ユーザーによるデバイスの認可を待っている間には、さまざまなHTTP 4xx応答を受け取ります。 + + #### 認可待ち + + このエラーは、ユーザーの操作を待っている間に表示されます。このチュートリアルの前の手順で推奨されている`interval`を使ってポーリングを継続してください。 + + ``` + `HTTP 403` + { + "error": "authorization_pending", + "error_description": "..." + } + ``` + + #### 減速 + + ポーリングが速すぎます。このチュートリアルの前の手順で推奨されている間隔を使ってポーリングしてください。ネットワーク遅延が原因でこのエラーを受け取ることを避けるには、ポーリング要求の応答を受け取ってから間隔をカウントし始めるようにします。 + + ``` + `HTTP 429` + { + "error": "slow_down", + "error_description": "..." + } + ``` + + #### 有効期限切れのトークン + + ユーザーによるデバイスの認可が遅かったため、`device_code`の期限が切れました。アプリケーションはユーザーにフローの失効を通知して、フローをもう一度始めるように促す必要があります。 + + + `expired_token`エラーは一度だけ返されます。それ以降は、エンドポイントが`invalid_grant`エラーを返します。 + + + ``` + `HTTP 403` + { + "error": "expired_token", + "error_description": "..." + } + ``` + + #### アクセス拒否 + + アクセスが拒否された場合には、次を受け取ります: + + ``` + `HTTP 403` + { + "error": "access_denied", + "error_description": "..." + } + ``` + + これは、以下を含むさまざまな原因で発生します。 + + - ユーザーがデバイスの認可を拒否した。 + - 認可サーバーがトランザクションを拒否した。 + - 構成済みのアクションがアクセスを拒否した。 +
    + +
    + 以下の例を参考に、このフローを実際のアプリケーションに実装する方法を確認してください。 + + - [Device Authorization Playground](https://auth0.github.io/device-flow-playground/) + - [AppleTV(Swift)](https://github.com/pushpabrol/auth0-device-flow-appletv):AppleTVからのデバイス認可フローにAuth0を使用する方法を示す簡素なアプリケーションです。 + - [CLI(Node.js)](https://gist.github.com/panva/652c61e7d847e0ed99926c324fa91b36):認可コードフローではなく、デバイス認可フローを使用するCLIの実装例です。大きな違いは、CLIがWebサーバーのホスティングやポートの待ち受けを必要としないことです。 +
    + +
    + デバイス認可フローを使用するには、デバイスアプリケーションに以下が必要です。 + + - Server Name Indication(SNI)に対応している + - ネイティブアプリケーション + - [認証方法](/docs/ja-jp/secure/application-credentials#application-authentication-methods)が**[None(なし)]** に設定されている + - [OIDCに準拠](/docs/ja-jp/dashboard/reference/settings-application#oauth) + - 動的クライアント登録(Dynamic Client Registration) + + また、デバイス認可フローには以下を使用できません: + + - Auth0の開発者キーを使用したソーシャル接続(新しいユニバーサルログインエクスペリエンス + - ホストされたログインページやアクションからクエリ文字列パラメーターへのアクセス +
    + + ## 次のステップ + 成功です!ここまで来れば、アプリケーションにログイン、ログアウト、ユーザープロファイル情報が備わっているはずです。 + + これでクイックスタートチュートリアルは終了ですが、機能はまだまだたくさんあります。Auth0でできることについて詳しくは、以下をご覧ください。 + + - [Auth0 Dashboard](https://manage.auth0.com/#) - Auth0のテナントやアプリケーションを構成して管理する方法について説明します + + - [Auth0 Marketplace](https://marketplace.auth0.com/) - Auth0の機能性を拡張できる各種の統合を見つけられます +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    diff --git a/main/docs/ja-jp/quickstart/native/flutter/interactive.mdx b/main/docs/ja-jp/quickstart/native/flutter/interactive.mdx index 4345ad98b..b79ef8067 100644 --- a/main/docs/ja-jp/quickstart/native/flutter/interactive.mdx +++ b/main/docs/ja-jp/quickstart/native/flutter/interactive.mdx @@ -1,242 +1,244 @@ ---- -title: "Flutterアプリケーションにログインを追加する" -permalink: "interactive" -'description': "このガイドでは、FlutterアプリにAuth0 Flutter SDKを使ってAuth0を統合する方法を説明します。" -'og:title': "Flutterアプリケーションにログインを追加する" -'og:description': "このガイドでは、FlutterアプリにAuth0 Flutter SDKを使ってAuth0を統合する方法を説明します。" -'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/flutter.jpeg" -'twitter:title': "Flutterアプリケーションにログインを追加する" -'twitter:description': "このガイドでは、FlutterアプリにAuth0 Flutter SDKを使ってAuth0を統合する方法を説明します。" -sidebarTitle: Flutter ---- - -import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; -import { LoggedInForm } from "/snippets/Login.jsx"; -import Build from "/snippets/quickstart/native/flutter/build.gradle.mdx"; -import MainView from "/snippets/quickstart/native/flutter/main_view.dart.mdx"; -import MainView2 from "/snippets/quickstart/native/flutter/main_view.dart2.mdx"; -import ProfileView from "/snippets/quickstart/native/flutter/profile_view.dart.mdx"; - -export const sections = [ - { id: "auth0を構成する", title: "Auth0を構成する" }, - { id: "auth0-flutter-sdkをインストールする", title: "Auth0 Flutter SDKをインストールする" }, - { id: "androidを構成する", title: "Androidを構成する" }, - { id: "ios-macosを構成する", title: "iOS/macOSを構成する" }, - { id: "アプリケーションにログインを追加する", title: "アプリケーションにログインを追加する" }, - { id: "アプリケーションにログアウトを追加する", title: "アプリケーションにログアウトを追加する" }, - { id: "ユーザープロファイル情報を表示する", title: "ユーザープロファイル情報を表示する" } -] - - - - # Flutterアプリケーションにログインを追加する - - Auth0を使用すると、アプリケーションに手軽に認証を追加して、ユーザープロファイル情報にアクセスできます。このガイドでは、Flutterアプリに[Auth0 Flutter SDK](https://github.com/auth0/auth0-flutter)を使ってAuth0を統合する方法を説明します。 - - - Flutter SDKは現在、Android、iOS、macOS版のFlutterアプリのみに対応しています。 - - - このクイックスタートでは、すでに[Flutter](https://flutter.dev/)アプリが問題なく作動しているものとします。そうでない場合は、[Flutter「入門」ガイド](https://docs.flutter.dev/get-started/install)をチェックして、シンプルなアプリの始め方をご確認ください。 - - [Flutterコマンドラインツール](https://docs.flutter.dev/reference/flutter-cli)の知識も必要になります。 - -
    - Auth0のサービスを利用するには、Auth0 Dashboadに設定済みのアプリケーションがある必要があります。Auth0アプリケーションは、プロジェクトに対してどのように認証が動作して欲しいかを構成する場所です。 - - ### Auth0アプリケーションを構成する - - 対話型のセレクターを使ってAuth0アプリケーションを新規作成するか、既存の**ネイティブ** のAuth0アプリケーションを選択します。Auth0のすべてのアプリケーションには英数字からなる一意のクライアントIDが割り当てられており、アプリケーションのコードがSDKを通じてAuth0 APIを呼び出す際に使用されます。 - - このクイックスタートを使って構成されたすべての設定は、[Dashboard](https://manage.auth0.com/dashboard/us/auth0-dsepaid/)のアプリケーションを自動更新します。今後、アプリケーションの管理もDashboardで行えます。 - - 完了済みの構成を見てみたい場合は、サンプルアプリをご覧ください。 - - ### Callback URLとログアウトURLを構成する - - Callback URLとログアウトURLは、ユーザーをアプリにリダイレクトで戻すために、Auth0が呼び出すURLです。 Auth0は、ユーザーを認証した後にCallback URLを呼び出し、セッションのクッキーを削除した後にログアウトURLを呼び出します。Callback URLとログアウトURLを設定しないと、ユーザーはアプリにログインやログアウトが行えなくなり、エラーが発生します。 - - プラットフォームに合わせて、Callback URLとログアウトURLに以下の値を設定します。 - - - Androidでは、`SCHEME`プレースホルダーの値は`https`や他のカスタムスキームでも構いません。`https`スキームでは、[Androidアプリリンク](/docs/ja-jp/get-started/applications/enable-android-app-links-support)を有効にする必要があります。 - - iOS 17.4以降とmacOS 14.4以降では、ユニバーサルリンク(`https`スキーム)をCallback URLとログアウトURLに使うことができます。有効にすると、SDKは、iOS/macOSの古いバージョンではカスタムURLスキームにフォールバックして、アプリの[バンドル識別子](https://developer.apple.com/documentation/appstoreconnectapi/bundle_ids)を使用します。**この機能にはXcode 15.3以降と有料のApple Developerアカウントが必要です** 。 - - - #### Android - - `SCHEME://{yourDomain}/android/YOUR_PACKAGE_NAME/callback` - - #### iOS - - `https://{yourDomain}/ios/YOUR_BUNDLE_IDENTIFIER/callback,` - - `YOUR_BUNDLE_IDENTIFIER://{yourDomain}/ios/YOUR_BUNDLE_IDENTIFIER/callback` - - #### macOS - - `https://{yourDomain}/macos/YOUR_BUNDLE_IDENTIFIER/callback,` - - `YOUR_BUNDLE_IDENTIFIER://{yourDomain}/macos/YOUR_BUNDLE_IDENTIFIER/callback` - - たとえば、iOSのバンドル識別子が`com.example.MyApp`でAuth0ドメインが`example.us.auth0.com`の場合には、次の値になります: - - `https://example.us.auth0.com/ios/com.example.MyApp/callback,` - - `com.example.MyApp://example.us.auth0.com/ios/com.example.MyApp/callback` -
    - -
    - Auth0 Flutter SDKをプロジェクトに追加します: - - `flutter pub add auth0_flutter` -
    - -
    - Androidプラットフォームが開発対象でない場合には、この手順をスキップしてください。 - - SDKにはマニフェストのプレースホルダーが必要です。Auth0は内部でプレースホルダーを使用して、認証のCallback URLを捉える`intent-filter`を定義します。Auth0テナントのドメインとCallback URLスキームを設定する必要があります。 - - [サンプル](https://github.com/auth0-samples/auth0-flutter-samples/tree/main/sample/android)では、次のプレースホルダーを使用します: - - - `auth0Domain`:Auth0テナントのドメインです。通常、Auth0 Dashboardにある**アプリケーションの設定** の**[Domain(ドメイン)]** フィールドで確認できます。カスタムドメインを使用している場合には、この値をカスタムドメインの値に設定してください。 - - `auth0Scheme`:使用するスキームです。カスタムスキーム、または、[Androidアプリリンク](/docs/ja-jp/applications/enable-android-app-links)を利用したい場合はhttpsになります。この値の設定に関する詳細情報は、[Auth0.Android SDK README](https://github.com/auth0/Auth0.Android#a-note-about-app-deep-linking)をお読みください。 - - - アクティビティーに特別な`intent-filter`を宣言する必要はありません。これは、マニフェストのプレースホルダーをAuth0**ドメイン** と**スキーム** の値で定義したからです。リダイレクトはライブラリーによって処理されます。 - - - Android Studio内で**Sync Project with Gradle Files** を実行し、変更内容を適用します。 -
    - -
    - iOSまたはmacOSプラットフォームが開発対象でない場合には、この手順をスキップしてください。 - - - この手順では、有料のApple Developerアカウントが必要です。Callback URLおよびログアウトURLとしてユニバーサルリンクを使用する必要があります。代わりにカスタムのURLスキームを使用する場合はこの手順をスキップしてください。 - - - ### チームIDとバンドル識別子を構成する - - Auth0アプリケーションの[設定ページ](https://manage.auth0.com/#/applications/%7ByourClientId%7D/settings)に移動して最後までスクロールし、 **[Advanced Settings(詳細設定)]>[Device Settings(デバイス設定)]** を開きます。**[iOS]** セクションで**[Team ID(チームID)]** に[Apple Team ID](https://developer.apple.com/help/account/manage-your-team/locate-your-team-id/)を、**[App ID(アプリID)]** にアプリのバンドル識別子を設定します。 - - ![null](/docs/images/ja-jp/cdy7uua7fh8z/7wetuICumueyqt6dbB32ro/34a7981c2cee8a14cdcd01e75df1e50c/IOS_Settings_-_Japanese.png) - - これで、アプリがAuth0テナントの`apple-app-site-association`ファイルに追加されます。 - - ### 関連ドメインの機能を追加する - - `open ios/Runner.xcworkspace`(macOSの場合には`open macos/Runner.xcworkspace`)を実行し、Xcodeでアプリを開きます。**Runner** ターゲット設定の**[Signing & Capabilities(署名と機能)]** [タブ](https://developer.apple.com/documentation/xcode/adding-capabilities-to-your-app#Add-a-capability)に移動し、**[+ Capability(+機能)]** ボタンを押します。それから**[Associated Domains(関連ドメイン)]** を選択します。 - - ![null](/docs/images/ja-jp/cdy7uua7fh8z/3GO76kXynaieKs5CSj3UTp/1cc577b56d00bc3bad877e31b848c1ec/ios-xcode-capabilities.png) - - 次に、以下の[エントリー](https://developer.apple.com/documentation/xcode/configuring-an-associated-domain#Define-a-service-and-its-associated-domain)を**[Associated Domains(関連ドメイン)]** の下に追加します。 - - `webcredentials:{yourDomain}` - - カスタムドメインがある場合は、Auth0ドメインの代わりに、設定ページにあるカスタムドメインを使用してください。 - - - 関連ドメインが動作するためには、**iOSシミュレーター用に構築されている場合でも** 、アプリが自分のチーム証明書で署名されている必要があります。Apple Teamには必ず、Auth0アプリケーションの設定ページで構成されたチームIDのものを使用してください。 - -
    - -
    - アプリに認証をセットアップするには、ユニバーサルログインが最も手軽な方法です。最良のエクスペリエンス、高い安全性、幅広い機能を活用するためにも、ユニバーサルログインの使用をお勧めします。 - - `Auth0`クラスを使用して、Auth0のユニバーサルログインをFlutterアプリに統合します。`webAuthentication().login()`を使用して、ユーザーをAuth0のユニバーサルログインページにリダイレクトします。これは`Future`であるため、ユーザートークンの取得を待ち合わせる必要があります。 - - **Android** :カスタムスキームを使用している場合には、このスキームをログインメソッドに渡して、SDKが適切にログインページへ誘導してから戻せるようにします: - - `await auth0.webAuthentication(scheme: 'YOUR CUSTOM SCHEME').login();` - - ユーザーがログインすると、アプリへリダイレクトされます。その後、このユーザーのIDとアクセストークンにアクセスできるようになります。 - - - ##### チェックポイント - webAuthentication().login()を呼び出してアプリにユーザーをログインするボタンをアプリに追加します。認証のためにAuth0へリダイレクトされてから、アプリケーションに戻されることを確認します。 - loginを呼び出した結果、トークンにアクセスできることを確認します - -
    - -
    - ユーザーをログアウトさせるには、Auth0 Flutter SDKの`webAuthentication().logout()`を呼び出してログインセッションをクリアし、ユーザーをAuth0のログアウトエンドポイントにリダイレクトします。Auth0からのログアウトについて詳しい情報をお読みください。 - - **Android** :カスタムスキームを使用している場合には、このスキームをログアウトメソッドに渡して、SDKがアプリを適切に戻せるようにします: - - `await auth0.webAuthentication(scheme: 'YOUR CUSTOM SCHEME').logout();` - - - ##### チェックポイント - アプリにwebAuthentication().logout()を呼び出して、ユーザーをアプリからログアウトさせるボタンを追加します。ボタンを選択し、Flutterアプリからログアウトエンドポイントにリダイレクトされ、再び戻されることを確認してください。アプリケーションにはログインされていないはずです。 - -
    - -
    - `webAuthentication().login()`を呼び出すと、ユーザープロファイルが自動的にユーザープロファイルプロパティを取得します。ログイン手順から返されたオブジェクトには、すべてのユーザープロファイルプロパティのある`user`プロパティが含まれ、これらはIDトークンをデコードすることで入力されます。 - - - ##### チェックポイント - ログインして、結果のuserプロパティを調査します。emailやnameなど、現在のユーザーのプロファイル情報を確認します。 - -
    - - ## 次のステップ - - 成功です!ここまで来れば、アプリケーションにログイン、ログアウト、ユーザープロファイル情報が備わっているはずです。 - - これでクイックスタートチュートリアルは終了ですが、機能はまだまだたくさんあります。Auth0でできることについて詳しくは、以下をご覧ください。 - - * [Auth0 Dashboard](https://manage.auth0.com/#) - Auth0のテナントやアプリケーションを構成して管理する方法について説明します - * [auth0-flutter SDK](https://www.github.com/auth0/auth0-flutter/) - このチュートリアルで使用されているSDKをより詳しく説明します - * [Auth0 Marketplace](https://marketplace.auth0.com/) - Auth0の機能性を拡張できる各種の統合を見つけられます - * [Configure other identity providers](/docs/ja-jp/identityproviders) - * [Enable multifactor authentication](/docs/ja-jp/multifactor-authentication) - * [Learn about attack protection](/docs/ja-jp/attack-protection) - * [Learn about Actions](/docs/ja-jp/customize/actions) -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    +--- +title: "Flutterアプリケーションにログインを追加する" +permalink: "interactive" +'description': "このガイドでは、FlutterアプリにAuth0 Flutter SDKを使ってAuth0を統合する方法を説明します。" +'og:title': "Flutterアプリケーションにログインを追加する" +'og:description': "このガイドでは、FlutterアプリにAuth0 Flutter SDKを使ってAuth0を統合する方法を説明します。" +'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/flutter.jpeg" +'twitter:title': "Flutterアプリケーションにログインを追加する" +'twitter:description': "このガイドでは、FlutterアプリにAuth0 Flutter SDKを使ってAuth0を統合する方法を説明します。" +sidebarTitle: Flutter +--- + +import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; +import { LoggedInForm } from "/snippets/Login.jsx"; +import Build from "/snippets/quickstart/native/flutter/build.gradle.mdx"; +import MainView from "/snippets/quickstart/native/flutter/main_view.dart.mdx"; +import MainView2 from "/snippets/quickstart/native/flutter/main_view.dart2.mdx"; +import ProfileView from "/snippets/quickstart/native/flutter/profile_view.dart.mdx"; + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + +export const sections = [ + { id: "auth0を構成する", title: "Auth0を構成する" }, + { id: "auth0-flutter-sdkをインストールする", title: "Auth0 Flutter SDKをインストールする" }, + { id: "androidを構成する", title: "Androidを構成する" }, + { id: "ios-macosを構成する", title: "iOS/macOSを構成する" }, + { id: "アプリケーションにログインを追加する", title: "アプリケーションにログインを追加する" }, + { id: "アプリケーションにログアウトを追加する", title: "アプリケーションにログアウトを追加する" }, + { id: "ユーザープロファイル情報を表示する", title: "ユーザープロファイル情報を表示する" } +] + + + + # Flutterアプリケーションにログインを追加する + + Auth0を使用すると、アプリケーションに手軽に認証を追加して、ユーザープロファイル情報にアクセスできます。このガイドでは、Flutterアプリに[Auth0 Flutter SDK](https://github.com/auth0/auth0-flutter)を使ってAuth0を統合する方法を説明します。 + + + Flutter SDKは現在、Android、iOS、macOS版のFlutterアプリのみに対応しています。 + + + このクイックスタートでは、すでに[Flutter](https://flutter.dev/)アプリが問題なく作動しているものとします。そうでない場合は、[Flutter「入門」ガイド](https://docs.flutter.dev/get-started/install)をチェックして、シンプルなアプリの始め方をご確認ください。 + + [Flutterコマンドラインツール](https://docs.flutter.dev/reference/flutter-cli)の知識も必要になります。 + +
    + Auth0のサービスを利用するには、Auth0 Dashboadに設定済みのアプリケーションがある必要があります。Auth0アプリケーションは、プロジェクトに対してどのように認証が動作して欲しいかを構成する場所です。 + + ### Auth0アプリケーションを構成する + + 対話型のセレクターを使ってAuth0アプリケーションを新規作成するか、既存の**ネイティブ** のAuth0アプリケーションを選択します。Auth0のすべてのアプリケーションには英数字からなる一意のクライアントIDが割り当てられており、アプリケーションのコードがSDKを通じてAuth0 APIを呼び出す際に使用されます。 + + このクイックスタートを使って構成されたすべての設定は、[Dashboard](https://manage.auth0.com/dashboard/us/auth0-dsepaid/)のアプリケーションを自動更新します。今後、アプリケーションの管理もDashboardで行えます。 + + 完了済みの構成を見てみたい場合は、サンプルアプリをご覧ください。 + + ### Callback URLとログアウトURLを構成する + + Callback URLとログアウトURLは、ユーザーをアプリにリダイレクトで戻すために、Auth0が呼び出すURLです。 Auth0は、ユーザーを認証した後にCallback URLを呼び出し、セッションのクッキーを削除した後にログアウトURLを呼び出します。Callback URLとログアウトURLを設定しないと、ユーザーはアプリにログインやログアウトが行えなくなり、エラーが発生します。 + + プラットフォームに合わせて、Callback URLとログアウトURLに以下の値を設定します。 + + + Androidでは、`SCHEME`プレースホルダーの値は`https`や他のカスタムスキームでも構いません。`https`スキームでは、[Androidアプリリンク](/docs/ja-jp/get-started/applications/enable-android-app-links-support)を有効にする必要があります。 + + iOS 17.4以降とmacOS 14.4以降では、ユニバーサルリンク(`https`スキーム)をCallback URLとログアウトURLに使うことができます。有効にすると、SDKは、iOS/macOSの古いバージョンではカスタムURLスキームにフォールバックして、アプリの[バンドル識別子](https://developer.apple.com/documentation/appstoreconnectapi/bundle_ids)を使用します。**この機能にはXcode 15.3以降と有料のApple Developerアカウントが必要です** 。 + + + #### Android + + `SCHEME://{yourDomain}/android/YOUR_PACKAGE_NAME/callback` + + #### iOS + + `https://{yourDomain}/ios/YOUR_BUNDLE_IDENTIFIER/callback,` + + `YOUR_BUNDLE_IDENTIFIER://{yourDomain}/ios/YOUR_BUNDLE_IDENTIFIER/callback` + + #### macOS + + `https://{yourDomain}/macos/YOUR_BUNDLE_IDENTIFIER/callback,` + + `YOUR_BUNDLE_IDENTIFIER://{yourDomain}/macos/YOUR_BUNDLE_IDENTIFIER/callback` + + たとえば、iOSのバンドル識別子が`com.example.MyApp`でAuth0ドメインが`example.us.auth0.com`の場合には、次の値になります: + + `https://example.us.auth0.com/ios/com.example.MyApp/callback,` + + `com.example.MyApp://example.us.auth0.com/ios/com.example.MyApp/callback` +
    + +
    + Auth0 Flutter SDKをプロジェクトに追加します: + + `flutter pub add auth0_flutter` +
    + +
    + Androidプラットフォームが開発対象でない場合には、この手順をスキップしてください。 + + SDKにはマニフェストのプレースホルダーが必要です。Auth0は内部でプレースホルダーを使用して、認証のCallback URLを捉える`intent-filter`を定義します。Auth0テナントのドメインとCallback URLスキームを設定する必要があります。 + + [サンプル](https://github.com/auth0-samples/auth0-flutter-samples/tree/main/sample/android)では、次のプレースホルダーを使用します: + + - `auth0Domain`:Auth0テナントのドメインです。通常、Auth0 Dashboardにある**アプリケーションの設定** の**[Domain(ドメイン)]** フィールドで確認できます。カスタムドメインを使用している場合には、この値をカスタムドメインの値に設定してください。 + - `auth0Scheme`:使用するスキームです。カスタムスキーム、または、[Androidアプリリンク](/docs/ja-jp/applications/enable-android-app-links)を利用したい場合はhttpsになります。この値の設定に関する詳細情報は、[Auth0.Android SDK README](https://github.com/auth0/Auth0.Android#a-note-about-app-deep-linking)をお読みください。 + + + アクティビティーに特別な`intent-filter`を宣言する必要はありません。これは、マニフェストのプレースホルダーをAuth0**ドメイン** と**スキーム** の値で定義したからです。リダイレクトはライブラリーによって処理されます。 + + + Android Studio内で**Sync Project with Gradle Files** を実行し、変更内容を適用します。 +
    + +
    + iOSまたはmacOSプラットフォームが開発対象でない場合には、この手順をスキップしてください。 + + + この手順では、有料のApple Developerアカウントが必要です。Callback URLおよびログアウトURLとしてユニバーサルリンクを使用する必要があります。代わりにカスタムのURLスキームを使用する場合はこの手順をスキップしてください。 + + + ### チームIDとバンドル識別子を構成する + + Auth0アプリケーションの[設定ページ](https://manage.auth0.com/#/applications/%7ByourClientId%7D/settings)に移動して最後までスクロールし、 **[Advanced Settings(詳細設定)]>[Device Settings(デバイス設定)]** を開きます。**[iOS]** セクションで**[Team ID(チームID)]** に[Apple Team ID](https://developer.apple.com/help/account/manage-your-team/locate-your-team-id/)を、**[App ID(アプリID)]** にアプリのバンドル識別子を設定します。 + + ![null](/docs/images/ja-jp/cdy7uua7fh8z/7wetuICumueyqt6dbB32ro/34a7981c2cee8a14cdcd01e75df1e50c/IOS_Settings_-_Japanese.png) + + これで、アプリがAuth0テナントの`apple-app-site-association`ファイルに追加されます。 + + ### 関連ドメインの機能を追加する + + `open ios/Runner.xcworkspace`(macOSの場合には`open macos/Runner.xcworkspace`)を実行し、Xcodeでアプリを開きます。**Runner** ターゲット設定の**[Signing & Capabilities(署名と機能)]** [タブ](https://developer.apple.com/documentation/xcode/adding-capabilities-to-your-app#Add-a-capability)に移動し、**[+ Capability(+機能)]** ボタンを押します。それから**[Associated Domains(関連ドメイン)]** を選択します。 + + ![null](/docs/images/ja-jp/cdy7uua7fh8z/3GO76kXynaieKs5CSj3UTp/1cc577b56d00bc3bad877e31b848c1ec/ios-xcode-capabilities.png) + + 次に、以下の[エントリー](https://developer.apple.com/documentation/xcode/configuring-an-associated-domain#Define-a-service-and-its-associated-domain)を**[Associated Domains(関連ドメイン)]** の下に追加します。 + + `webcredentials:{yourDomain}` + + カスタムドメインがある場合は、Auth0ドメインの代わりに、設定ページにあるカスタムドメインを使用してください。 + + + 関連ドメインが動作するためには、**iOSシミュレーター用に構築されている場合でも** 、アプリが自分のチーム証明書で署名されている必要があります。Apple Teamには必ず、Auth0アプリケーションの設定ページで構成されたチームIDのものを使用してください。 + +
    + +
    + アプリに認証をセットアップするには、ユニバーサルログインが最も手軽な方法です。最良のエクスペリエンス、高い安全性、幅広い機能を活用するためにも、ユニバーサルログインの使用をお勧めします。 + + `Auth0`クラスを使用して、Auth0のユニバーサルログインをFlutterアプリに統合します。`webAuthentication().login()`を使用して、ユーザーをAuth0のユニバーサルログインページにリダイレクトします。これは`Future`であるため、ユーザートークンの取得を待ち合わせる必要があります。 + + **Android** :カスタムスキームを使用している場合には、このスキームをログインメソッドに渡して、SDKが適切にログインページへ誘導してから戻せるようにします: + + `await auth0.webAuthentication(scheme: 'YOUR CUSTOM SCHEME').login();` + + ユーザーがログインすると、アプリへリダイレクトされます。その後、このユーザーのIDとアクセストークンにアクセスできるようになります。 + + + ##### チェックポイント + webAuthentication().login()を呼び出してアプリにユーザーをログインするボタンをアプリに追加します。認証のためにAuth0へリダイレクトされてから、アプリケーションに戻されることを確認します。 + loginを呼び出した結果、トークンにアクセスできることを確認します + +
    + +
    + ユーザーをログアウトさせるには、Auth0 Flutter SDKの`webAuthentication().logout()`を呼び出してログインセッションをクリアし、ユーザーをAuth0のログアウトエンドポイントにリダイレクトします。Auth0からのログアウトについて詳しい情報をお読みください。 + + **Android** :カスタムスキームを使用している場合には、このスキームをログアウトメソッドに渡して、SDKがアプリを適切に戻せるようにします: + + `await auth0.webAuthentication(scheme: 'YOUR CUSTOM SCHEME').logout();` + + + ##### チェックポイント + アプリにwebAuthentication().logout()を呼び出して、ユーザーをアプリからログアウトさせるボタンを追加します。ボタンを選択し、Flutterアプリからログアウトエンドポイントにリダイレクトされ、再び戻されることを確認してください。アプリケーションにはログインされていないはずです。 + +
    + +
    + `webAuthentication().login()`を呼び出すと、ユーザープロファイルが自動的にユーザープロファイルプロパティを取得します。ログイン手順から返されたオブジェクトには、すべてのユーザープロファイルプロパティのある`user`プロパティが含まれ、これらはIDトークンをデコードすることで入力されます。 + + + ##### チェックポイント + ログインして、結果のuserプロパティを調査します。emailやnameなど、現在のユーザーのプロファイル情報を確認します。 + +
    + + ## 次のステップ + + 成功です!ここまで来れば、アプリケーションにログイン、ログアウト、ユーザープロファイル情報が備わっているはずです。 + + これでクイックスタートチュートリアルは終了ですが、機能はまだまだたくさんあります。Auth0でできることについて詳しくは、以下をご覧ください。 + + * [Auth0 Dashboard](https://manage.auth0.com/#) - Auth0のテナントやアプリケーションを構成して管理する方法について説明します + * [auth0-flutter SDK](https://www.github.com/auth0/auth0-flutter/) - このチュートリアルで使用されているSDKをより詳しく説明します + * [Auth0 Marketplace](https://marketplace.auth0.com/) - Auth0の機能性を拡張できる各種の統合を見つけられます + * [Configure other identity providers](/docs/ja-jp/identityproviders) + * [Enable multifactor authentication](/docs/ja-jp/multifactor-authentication) + * [Learn about attack protection](/docs/ja-jp/attack-protection) + * [Learn about Actions](/docs/ja-jp/customize/actions) +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    diff --git a/main/docs/ja-jp/quickstart/native/ionic-angular/interactive.mdx b/main/docs/ja-jp/quickstart/native/ionic-angular/interactive.mdx index c13900e1b..78aeb9674 100644 --- a/main/docs/ja-jp/quickstart/native/ionic-angular/interactive.mdx +++ b/main/docs/ja-jp/quickstart/native/ionic-angular/interactive.mdx @@ -1,268 +1,270 @@ ---- -title: "Capacitorを用いたIonic Angularアプリケーションにログインを追加する" -permalink: "interactive" -'description': "このガイドは、Ionic(Angular)とCapacitorのアプリケーションにAuth0 Angular SDKを使ってAuth0を統合する方法を説明します。" -'og:title': "Capacitorを用いたIonic Angularアプリケーションにログインを追加する" -'og:description': "このガイドは、Ionic(Angular)とCapacitorのアプリケーションにAuth0 Angular SDKを使ってAuth0を統合する方法を説明します。" -'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/ionic.jpeg" -'twitter:title': "Capacitorを用いたIonic Angularアプリケーションにログインを追加する" -'twitter:description': "このガイドは、Ionic(Angular)とCapacitorのアプリケーションにAuth0 Angular SDKを使ってAuth0を統合する方法を説明します。" -sidebarTitle: Ionic & Capacitor (Angular) ---- - -import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; -import { LoggedInForm } from "/snippets/Login.jsx"; -import AppModule from "/snippets/quickstart/native/ionic-angular/app.module.ts.mdx"; -import AppComponent from "/snippets/quickstart/native/ionic-angular/app.component.ts.mdx"; -import Loginbutton from "/snippets/quickstart/native/ionic-angular/login-button.ts.mdx"; -import Logoutbutton from "/snippets/quickstart/native/ionic-angular/logout-button.ts.mdx"; -import Userprofile from "/snippets/quickstart/native/ionic-angular/user-profile.ts.mdx"; - -export const sections = [ - { id: "使用を開始する", title: "使用を開始する" }, - { id: "auth0を構成する", title: "Auth0を構成する" }, - { id: "auth0-angular-sdkをインストールする", title: "Auth0 Angular SDKをインストールする" }, - { id: "認証モジュールを登録して構成する", title: "認証モジュールを登録して構成する" }, - { id: "アプリケーションにログインを追加する", title: "アプリケーションにログインを追加する" }, - { id: "ログインコールバックを処理する", title: "ログインコールバックを処理する" }, - { id: "アプリケーションにログアウトを追加する", title: "アプリケーションにログアウトを追加する" }, - { id: "ユーザープロファイルを表示する", title: "ユーザープロファイルを表示する" } -] - - - - Auth0を使用すると、アプリケーションに手軽に認証を追加して、ユーザープロファイル情報にアクセスすることができます。このガイドは、Ionic(Angular)とCapacitorのアプリケーションに[Auth0 Angular SDK](https://github.com/auth0/auth0-angular)を使ってAuth0を統合する方法を説明します。 - -
    - このクイックスタートは、[Ionic](https://ionicframework.com/)アプリケーションが[Capacitor](https://capacitorjs.com/)を使ってすでに実行されていることを前提としています。そうでない場合には、[IonicフレームワークでCapacitorを使用する](https://capacitorjs.com/docs/getting-started/with-ionic)ガイドを参照しながら簡単なアプリから始めるか、[サンプリアプリ](https://github.com/auth0-samples/auth0-ionic-samples)を複製してください。 - - また、[Capacitorの開発ワークフロー](https://capacitorjs.com/docs/basics/workflow)を理解しておく必要もあります。 -
    - -
    - Auth0のサービスを利用するには、Auth0 Dashboadに設定済みのアプリケーションがある必要があります。Auth0アプリケーションは、プロジェクトに対してどのように認証が動作して欲しいかを構成する場所です。 - - - 以下の説明では、「`YOUR_PACKAGE_ID`」を実際のアプリケーションのパッケージIDに置き換えてください。これは、`capacitor.config.ts`ファイルの`appId`フィールドで見つけて構成することができます。詳細については、[Capacitorの構成スキーマ](https://capacitorjs.com/docs/config#schema)を参照してください。 - - - ### アプリケーションを構成する - - 対話型のセレクターを使ってAuth0アプリケーションを新規作成するか、統合したいプロジェクトを表す既存のアプリケーションを選択します。Auth0のすべてのアプリケーションには英数字からなる一意のクライアントIDが割り当てられており、アプリケーションのコードがSDKを通じてAuth0 APIを呼び出す際に使用されます。 - - このクイックスタートを使って構成されたすべての設定は、[Dashboard](https://manage.auth0.com/#/)のアプリケーションを自動更新します。今後、アプリケーションの管理もDashboardで行えます。 - - 完了済みの構成を見てみたい場合は、サンプルアプリケーションをご覧ください。 - - ### Callback URLを構成する - - Callback URLとは、Auth0がユーザーを認証後にリダイレクトするアプリケーション内URLです。設定されていない場合、ユーザーはログイン後にアプリケーションに戻りません。 - - - サンプルプロジェクトに沿って進めている場合には、次の値に設定します: - - `YOUR_PACKAGE_ID://{yourDomain}/capacitor/YOUR_PACKAGE_ID/callback` - - - ### ログアウトURLを構成する - - ログアウトURLとは、Auth0がユーザーをログアウト後にリダイレクトするアプリケーション内URLです。設定されていない場合、ユーザーはアプリケーションからログアウトできず、エラーを受け取ります。 - - - サンプルプロジェクトに沿って進めている場合には、次の値に設定します: - - `YOUR_PACKAGE_ID://{yourDomain}/capacitor/YOUR_PACKAGE_ID/callback` - - - ### 許可されているオリジンを構成する - - ネイティブアプリケーションからAuth0へ要求を送信できるようにするには、[アプリケーションの設定](https://manage.auth0.com/#/applications/%7ByourClientId%7D/settings)で次の**許可されているオリジン** を設定します。 - - - サンプルプロジェクトに沿って進めている場合、capacitorにiOSとAndroidでそれぞれ`capacitor://localhost, http://localhost`を設定します。 - - - 最後に、アプリケーションの**[Application Type(アプリケーションタイプ)]** が**[Native(ネイティブ)]** になっていることを[アプリケーションの設定](https://manage.auth0.com/#/applications/%7ByourClientId%7D/settings)で必ず確認してください。 -
    - -
    - プロジェクトディレクトリで次のコマンドを実行して、Auth0 Angular SDKをインストールします: - - `npm install @auth0/auth0-angular` - - SDKはモジュールや認証サービスなど、Auth0をAngularアプリケーションに慣用的に統合しやすくする種類をいくつか公開しています。 - - ### Capacitorプラグインをインストールする - - このクイックスタートとサンプルでは、Capacitorの公式プラグインをいくつか使用しています。次のコマンドを使用して、これらをアプリにインストールします: - - `npm install @capacitor/browser @capacitor/app` - - - [`@capacitor/browser`](https://capacitorjs.com/docs/apis/browser):デバイスのシステムブラウザーと対話できるようになり、Auth0の認可エンドポイントへのURLを開くために使用されます。 - - [`@capacitor/app`](https://capacitorjs.com/docs/apis/app):高レベルのアプリイベントを受け取れるようになるため、Auth0からのコールバックを扱うのに便利です。 - - - iOSのCapacitorのBrowserプラグインは[`SFSafariViewController`](https://developer.apple.com/documentation/safariservices/sfsafariviewcontroller)を使用し、iOS 11以降ではデバイス上のSafariとクッキーを共有しません。つまり、これらのデバイスではSSOが機能しません。SSOが必要な場合には、[ASWebAuthenticationSession](https://developer.apple.com/documentation/authenticationservices/aswebauthenticationsession)を使用する互換のプラグインを使用してください。 - -
    - -
    - SDKは、SDKが機能するために必要なすべてのサービスを含んだ`AuthModule`をエクスポートします。このモジュールをアプリケーションに登録し、Auth0のドメインとクライアントIDで構成する必要があります。 - - `AuthModule.forRoot`関数は以下の構成を使用します。 - - - `domain`:Auth0 Dashboardで作成したアプリケーションの**設定** にある`domain`値、またはAuth0のカスタムドメイン機能を使用する場合のカスタムドメインです。 - - `clientId`:Auth0 Dashboardで作成したアプリケーションの**設定** にあるクライアントID値です。 - - `useRefreshTokens`:AndroidまたはiOSでauth0-angularをIonicと使用するには、リフレッシュトークンを有効にする必要があります。 - - `useRefreshTokensFallback`:AndroidまたはiOSでauth0-angularをIonicと使用するには、iframeのフォールバックを無効にする必要があります。 - - `authorizationParams.redirect_uri`:Auth0で認証した後に、ユーザーをリダイレクトするURLです。 - - - アプリケーションの閉開後に認証を継続するには、SDKを構成する際に`cacheLocation`を`localstorage`に設定することをお勧めします。ただし、[localstorageにトークンを保管するリスク](/docs/ja-jp/libraries/auth0-single-page-app-sdk#change-storage-options)を理解してください。また、状況によってはlocalstorageのデータが思いがけず復元される可能性もあるため、Capacitorアプリ内では**一次的** なものとして扱ってください。[Capacitorドキュメントに記載のストレージに関するガイド](https://capacitorjs.com/docs/guides/storage#why-cant-i-just-use-localstorage-or-indexeddb)をお読みください。 - - さらに、より安全で永続的なストレージの仕組みが要件である場合、SDKを使用すると、[カスタムのキャッシュを実装](https://github.com/auth0/auth0-spa-js/blob/master/EXAMPLES.md#creating-a-custom-cache)してトークンを保管することができます。 - - **注意** :[CapacitorのStorageプラグイン](https://capacitorjs.com/docs/apis/storage)は、iOSでは[UserDefaults](https://developer.apple.com/documentation/foundation/userdefaults)、Androidでは[SharedPreferences](https://developer.android.com/reference/android/content/SharedPreferences)によってバックアップされるため、トークンの保管に使用**しない** ことをお勧めします。これらのAPIを使って保管されたデータは暗号化されません。セキュリティで保護されることもなく、クラウドと同期される可能性があります。 - - - - ##### チェックポイント - アプリがAuth0 Angular SDKで構成されました。今度は、アプリケーションを実行して、SDKがエラーなく初期化されること、そして、以前と同じように動作することを確認します。 - -
    - -
    - Capacitorアプリケーションでは、[CapacitorのBrowserプラグイン](https://capacitorjs.com/docs/apis/browser)によって、Auth0の[ユニバーサルログインページ](https://auth0.com/universal-login)にリダイレクトされます。`loginWithRedirect`関数の`openUrl`パラメーターに`Browser.open`の使用を設定し、デバイスのシステムブラウザーコンポーネント(iOSでは[SFSafariViewController](https://developer.apple.com/documentation/safariservices/sfsafariviewcontroller)、Androidでは[Chrome Custom Tabs](https://developer.chrome.com/docs/android/custom-tabs))でURLが開くようにします。 - - - SDKの`loginWithRedirect`メソッドは、デフォルトで`window.location.href`を使用して、ユーザーのデバイスにあるデフォルトのブラウザーアプリケーションでログインページを開きます。プラットフォームに適切なシステムブラウザーコンポーネントは使用しません。ユーザーが認証でアプリケーションを離れるため、ユーザーエクスペリエンスとしては最適ではありません。 - - - - ##### チェックポイント - loginWithRedirect関数は、SDKにログインフローを開始するように指示します。openUrlパラメーターにログインURLを設定して、Browser.open関数を呼し出し、プラットフォームのシステムブラウザーコンポーネントでログインURLを開きます。これは、ユーザーがアプリケーションにログインする方法を提供します。ユーザーはAuth0のログインページにリダイレクトされ、エラーは一切受け取りません。 - -
    - -
    - ユーザーがユニバーサルログインページでログインすると、カスタムURLスキームを使ったURLでアプリにリダイレクトされます。`appUrlOpen`イベントがアプリ内で処理されなければなりません。Auth0 SDKの`handleRedirectCallback`メソッドを呼び出すと、認証状態を初期化することができます。 - - このメソッドは、Auth0からのリダイレクトでのみ使用することができます。正常に機能していることを確認するには、URL内の`code`と`state`パラメーターを確認します。 - - このイベントが発生した際に、`Browser.close()`メソッドがブラウザーを閉じるようにします。 - - `appUrlOpen`イベントのコールバックが`ngZone.run`でラップされていることに注意してください。`handleRedirectCallback`の実行時に発生するオブザーバブルへの変更は、Angularアプリが受け取ります。詳細については、「[AngularをCapacitorと使用する](https://capacitorjs.com/docs/guides/angular)」をお読みください。それ以外の場合では、画面がログイン後の認証状態で更新されません。 - - - 以下の説明では、カスタムURLスキームを使用して、アプリケーション内でコールバックを処理することを前提にしています。このためには、`YOUR_PACKAGE_ID`を選択したプラットのURLスキームで置き換えて登録します。詳細については、iOSには「[カスタムURLスキームを定義する](https://developer.apple.com/documentation/xcode/defining-a-custom-url-scheme-for-your-app)」、Androidには「[アプリコンテンツ用のディープリンクを作成する](https://developer.android.com/training/app-links/deep-linking)」をお読みください。 - - - - ##### チェックポイント - アプリケーションのAppコンポーネントにappUrlOpenを追加して、ログインします。ユーザーが認証して、アプリにログインすると、ブラウザーのウィンドウが閉じます。 - -
    - -
    - ユーザーがログインできるようになりました。今度は、ログアウトする方法を構成する必要があります。ユーザーをAuth0のログアウトエンドポイントにリダイレクトし、ブラウザー内のセッションをクリアする必要があります。他の場合と同様に、ユーザーがアプリから離れることでユーザーエクスペリエンスが損なわれないように、CapacitorのBrowserプラグインがリダイレクトを処理するようにします。 - - Auth0 SDKを使用してIonicとCapacitorで実現するには、以下を行います。 - - - アプリについて、ログアウト後にAuth0のリダイレクト先となるURLを構築します。これは、登録済みのカスタムスキームとAuth0ドメインを使ったURLです。これを、Auth0 Dashboardの**[Allowed Logout URLs(許可されているログアウトURL)]** の構成に追加します。 - - `logout`を呼び出し、`logoutParams.returnTo`パラメーターにリダイレクト先のURLを渡して、SDKからログアウトします。 - - CapacitorのBrowserプラグインを使用して`Browser.open`でURLを開くコールバックに、`openUrl`パラメーターを設定します。 - - - ログインの手順と同様に、`logout`を呼び出す際に`openUrl`を設定しないと、SDKがユーザーをログアウトURLにリダイレクトするのに、デバイスのデフォルトのブラウザーアプリケーションが使用されるため、ユーザーエクスペリエンスとしては最適ではありません。 - - - - ##### チェックポイント - ユーザーがアプリケーションからログアウトする方法を提供します。Auth0にリダイレクトしてから、returnToパラメーターで指定したアドレスへ移動することを確認します。ユーザーがアプリケーションにログインしていないことを確認します。 - -
    - -
    - Auth0 SDKは必要な任意のコンポーネントについて、名前やプロフィール写真など、ログイン済みのユーザーに関連付けられたプロファイル情報を取得し、ユーザーインターフェイスをパーソナライズします。プロファイル情報は、`AuthService`が公開する`user$`プロパティを介して使用することができます。 - - - ##### チェックポイント - ユーザーがアプリ内でユーザープロファイルの詳細を表示できる手段を提供し、ログインした後に自分のプロファイル情報を取得して画面に表示できることを確認します。 - -
    - - ## 次のステップ - - 成功です!ここまで来れば、アプリケーションにログイン、ログアウト、ユーザープロファイル情報が備わっているはずです。 - - これでクイックスタートチュートリアルは終了ですが、機能はまだまだたくさんあります。Auth0でできることについて詳しくは、以下をご覧ください。 - - * [Auth0 Dashboard](https://manage.auth0.com/#) - Auth0のテナントやアプリケーションを構成して管理する方法について説明します - * [Auth0 Marketplace](https://marketplace.auth0.com/) - Auth0の機能性を拡張できる各種の統合を見つけられます -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    +--- +title: "Capacitorを用いたIonic Angularアプリケーションにログインを追加する" +permalink: "interactive" +'description': "このガイドは、Ionic(Angular)とCapacitorのアプリケーションにAuth0 Angular SDKを使ってAuth0を統合する方法を説明します。" +'og:title': "Capacitorを用いたIonic Angularアプリケーションにログインを追加する" +'og:description': "このガイドは、Ionic(Angular)とCapacitorのアプリケーションにAuth0 Angular SDKを使ってAuth0を統合する方法を説明します。" +'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/ionic.jpeg" +'twitter:title': "Capacitorを用いたIonic Angularアプリケーションにログインを追加する" +'twitter:description': "このガイドは、Ionic(Angular)とCapacitorのアプリケーションにAuth0 Angular SDKを使ってAuth0を統合する方法を説明します。" +sidebarTitle: Ionic & Capacitor (Angular) +--- + +import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; +import { LoggedInForm } from "/snippets/Login.jsx"; +import AppModule from "/snippets/quickstart/native/ionic-angular/app.module.ts.mdx"; +import AppComponent from "/snippets/quickstart/native/ionic-angular/app.component.ts.mdx"; +import Loginbutton from "/snippets/quickstart/native/ionic-angular/login-button.ts.mdx"; +import Logoutbutton from "/snippets/quickstart/native/ionic-angular/logout-button.ts.mdx"; +import Userprofile from "/snippets/quickstart/native/ionic-angular/user-profile.ts.mdx"; + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + +export const sections = [ + { id: "使用を開始する", title: "使用を開始する" }, + { id: "auth0を構成する", title: "Auth0を構成する" }, + { id: "auth0-angular-sdkをインストールする", title: "Auth0 Angular SDKをインストールする" }, + { id: "認証モジュールを登録して構成する", title: "認証モジュールを登録して構成する" }, + { id: "アプリケーションにログインを追加する", title: "アプリケーションにログインを追加する" }, + { id: "ログインコールバックを処理する", title: "ログインコールバックを処理する" }, + { id: "アプリケーションにログアウトを追加する", title: "アプリケーションにログアウトを追加する" }, + { id: "ユーザープロファイルを表示する", title: "ユーザープロファイルを表示する" } +] + + + + Auth0を使用すると、アプリケーションに手軽に認証を追加して、ユーザープロファイル情報にアクセスすることができます。このガイドは、Ionic(Angular)とCapacitorのアプリケーションに[Auth0 Angular SDK](https://github.com/auth0/auth0-angular)を使ってAuth0を統合する方法を説明します。 + +
    + このクイックスタートは、[Ionic](https://ionicframework.com/)アプリケーションが[Capacitor](https://capacitorjs.com/)を使ってすでに実行されていることを前提としています。そうでない場合には、[IonicフレームワークでCapacitorを使用する](https://capacitorjs.com/docs/getting-started/with-ionic)ガイドを参照しながら簡単なアプリから始めるか、[サンプリアプリ](https://github.com/auth0-samples/auth0-ionic-samples)を複製してください。 + + また、[Capacitorの開発ワークフロー](https://capacitorjs.com/docs/basics/workflow)を理解しておく必要もあります。 +
    + +
    + Auth0のサービスを利用するには、Auth0 Dashboadに設定済みのアプリケーションがある必要があります。Auth0アプリケーションは、プロジェクトに対してどのように認証が動作して欲しいかを構成する場所です。 + + + 以下の説明では、「`YOUR_PACKAGE_ID`」を実際のアプリケーションのパッケージIDに置き換えてください。これは、`capacitor.config.ts`ファイルの`appId`フィールドで見つけて構成することができます。詳細については、[Capacitorの構成スキーマ](https://capacitorjs.com/docs/config#schema)を参照してください。 + + + ### アプリケーションを構成する + + 対話型のセレクターを使ってAuth0アプリケーションを新規作成するか、統合したいプロジェクトを表す既存のアプリケーションを選択します。Auth0のすべてのアプリケーションには英数字からなる一意のクライアントIDが割り当てられており、アプリケーションのコードがSDKを通じてAuth0 APIを呼び出す際に使用されます。 + + このクイックスタートを使って構成されたすべての設定は、[Dashboard](https://manage.auth0.com/#/)のアプリケーションを自動更新します。今後、アプリケーションの管理もDashboardで行えます。 + + 完了済みの構成を見てみたい場合は、サンプルアプリケーションをご覧ください。 + + ### Callback URLを構成する + + Callback URLとは、Auth0がユーザーを認証後にリダイレクトするアプリケーション内URLです。設定されていない場合、ユーザーはログイン後にアプリケーションに戻りません。 + + + サンプルプロジェクトに沿って進めている場合には、次の値に設定します: + + `YOUR_PACKAGE_ID://{yourDomain}/capacitor/YOUR_PACKAGE_ID/callback` + + + ### ログアウトURLを構成する + + ログアウトURLとは、Auth0がユーザーをログアウト後にリダイレクトするアプリケーション内URLです。設定されていない場合、ユーザーはアプリケーションからログアウトできず、エラーを受け取ります。 + + + サンプルプロジェクトに沿って進めている場合には、次の値に設定します: + + `YOUR_PACKAGE_ID://{yourDomain}/capacitor/YOUR_PACKAGE_ID/callback` + + + ### 許可されているオリジンを構成する + + ネイティブアプリケーションからAuth0へ要求を送信できるようにするには、[アプリケーションの設定](https://manage.auth0.com/#/applications/%7ByourClientId%7D/settings)で次の**許可されているオリジン** を設定します。 + + + サンプルプロジェクトに沿って進めている場合、capacitorにiOSとAndroidでそれぞれ`capacitor://localhost, http://localhost`を設定します。 + + + 最後に、アプリケーションの**[Application Type(アプリケーションタイプ)]** が**[Native(ネイティブ)]** になっていることを[アプリケーションの設定](https://manage.auth0.com/#/applications/%7ByourClientId%7D/settings)で必ず確認してください。 +
    + +
    + プロジェクトディレクトリで次のコマンドを実行して、Auth0 Angular SDKをインストールします: + + `npm install @auth0/auth0-angular` + + SDKはモジュールや認証サービスなど、Auth0をAngularアプリケーションに慣用的に統合しやすくする種類をいくつか公開しています。 + + ### Capacitorプラグインをインストールする + + このクイックスタートとサンプルでは、Capacitorの公式プラグインをいくつか使用しています。次のコマンドを使用して、これらをアプリにインストールします: + + `npm install @capacitor/browser @capacitor/app` + + - [`@capacitor/browser`](https://capacitorjs.com/docs/apis/browser):デバイスのシステムブラウザーと対話できるようになり、Auth0の認可エンドポイントへのURLを開くために使用されます。 + - [`@capacitor/app`](https://capacitorjs.com/docs/apis/app):高レベルのアプリイベントを受け取れるようになるため、Auth0からのコールバックを扱うのに便利です。 + + + iOSのCapacitorのBrowserプラグインは[`SFSafariViewController`](https://developer.apple.com/documentation/safariservices/sfsafariviewcontroller)を使用し、iOS 11以降ではデバイス上のSafariとクッキーを共有しません。つまり、これらのデバイスではSSOが機能しません。SSOが必要な場合には、[ASWebAuthenticationSession](https://developer.apple.com/documentation/authenticationservices/aswebauthenticationsession)を使用する互換のプラグインを使用してください。 + +
    + +
    + SDKは、SDKが機能するために必要なすべてのサービスを含んだ`AuthModule`をエクスポートします。このモジュールをアプリケーションに登録し、Auth0のドメインとクライアントIDで構成する必要があります。 + + `AuthModule.forRoot`関数は以下の構成を使用します。 + + - `domain`:Auth0 Dashboardで作成したアプリケーションの**設定** にある`domain`値、またはAuth0のカスタムドメイン機能を使用する場合のカスタムドメインです。 + - `clientId`:Auth0 Dashboardで作成したアプリケーションの**設定** にあるクライアントID値です。 + - `useRefreshTokens`:AndroidまたはiOSでauth0-angularをIonicと使用するには、リフレッシュトークンを有効にする必要があります。 + - `useRefreshTokensFallback`:AndroidまたはiOSでauth0-angularをIonicと使用するには、iframeのフォールバックを無効にする必要があります。 + - `authorizationParams.redirect_uri`:Auth0で認証した後に、ユーザーをリダイレクトするURLです。 + + + アプリケーションの閉開後に認証を継続するには、SDKを構成する際に`cacheLocation`を`localstorage`に設定することをお勧めします。ただし、[localstorageにトークンを保管するリスク](/docs/ja-jp/libraries/auth0-single-page-app-sdk#change-storage-options)を理解してください。また、状況によってはlocalstorageのデータが思いがけず復元される可能性もあるため、Capacitorアプリ内では**一次的** なものとして扱ってください。[Capacitorドキュメントに記載のストレージに関するガイド](https://capacitorjs.com/docs/guides/storage#why-cant-i-just-use-localstorage-or-indexeddb)をお読みください。 + + さらに、より安全で永続的なストレージの仕組みが要件である場合、SDKを使用すると、[カスタムのキャッシュを実装](https://github.com/auth0/auth0-spa-js/blob/master/EXAMPLES.md#creating-a-custom-cache)してトークンを保管することができます。 + + **注意** :[CapacitorのStorageプラグイン](https://capacitorjs.com/docs/apis/storage)は、iOSでは[UserDefaults](https://developer.apple.com/documentation/foundation/userdefaults)、Androidでは[SharedPreferences](https://developer.android.com/reference/android/content/SharedPreferences)によってバックアップされるため、トークンの保管に使用**しない** ことをお勧めします。これらのAPIを使って保管されたデータは暗号化されません。セキュリティで保護されることもなく、クラウドと同期される可能性があります。 + + + + ##### チェックポイント + アプリがAuth0 Angular SDKで構成されました。今度は、アプリケーションを実行して、SDKがエラーなく初期化されること、そして、以前と同じように動作することを確認します。 + +
    + +
    + Capacitorアプリケーションでは、[CapacitorのBrowserプラグイン](https://capacitorjs.com/docs/apis/browser)によって、Auth0の[ユニバーサルログインページ](https://auth0.com/universal-login)にリダイレクトされます。`loginWithRedirect`関数の`openUrl`パラメーターに`Browser.open`の使用を設定し、デバイスのシステムブラウザーコンポーネント(iOSでは[SFSafariViewController](https://developer.apple.com/documentation/safariservices/sfsafariviewcontroller)、Androidでは[Chrome Custom Tabs](https://developer.chrome.com/docs/android/custom-tabs))でURLが開くようにします。 + + + SDKの`loginWithRedirect`メソッドは、デフォルトで`window.location.href`を使用して、ユーザーのデバイスにあるデフォルトのブラウザーアプリケーションでログインページを開きます。プラットフォームに適切なシステムブラウザーコンポーネントは使用しません。ユーザーが認証でアプリケーションを離れるため、ユーザーエクスペリエンスとしては最適ではありません。 + + + + ##### チェックポイント + loginWithRedirect関数は、SDKにログインフローを開始するように指示します。openUrlパラメーターにログインURLを設定して、Browser.open関数を呼し出し、プラットフォームのシステムブラウザーコンポーネントでログインURLを開きます。これは、ユーザーがアプリケーションにログインする方法を提供します。ユーザーはAuth0のログインページにリダイレクトされ、エラーは一切受け取りません。 + +
    + +
    + ユーザーがユニバーサルログインページでログインすると、カスタムURLスキームを使ったURLでアプリにリダイレクトされます。`appUrlOpen`イベントがアプリ内で処理されなければなりません。Auth0 SDKの`handleRedirectCallback`メソッドを呼び出すと、認証状態を初期化することができます。 + + このメソッドは、Auth0からのリダイレクトでのみ使用することができます。正常に機能していることを確認するには、URL内の`code`と`state`パラメーターを確認します。 + + このイベントが発生した際に、`Browser.close()`メソッドがブラウザーを閉じるようにします。 + + `appUrlOpen`イベントのコールバックが`ngZone.run`でラップされていることに注意してください。`handleRedirectCallback`の実行時に発生するオブザーバブルへの変更は、Angularアプリが受け取ります。詳細については、「[AngularをCapacitorと使用する](https://capacitorjs.com/docs/guides/angular)」をお読みください。それ以外の場合では、画面がログイン後の認証状態で更新されません。 + + + 以下の説明では、カスタムURLスキームを使用して、アプリケーション内でコールバックを処理することを前提にしています。このためには、`YOUR_PACKAGE_ID`を選択したプラットのURLスキームで置き換えて登録します。詳細については、iOSには「[カスタムURLスキームを定義する](https://developer.apple.com/documentation/xcode/defining-a-custom-url-scheme-for-your-app)」、Androidには「[アプリコンテンツ用のディープリンクを作成する](https://developer.android.com/training/app-links/deep-linking)」をお読みください。 + + + + ##### チェックポイント + アプリケーションのAppコンポーネントにappUrlOpenを追加して、ログインします。ユーザーが認証して、アプリにログインすると、ブラウザーのウィンドウが閉じます。 + +
    + +
    + ユーザーがログインできるようになりました。今度は、ログアウトする方法を構成する必要があります。ユーザーをAuth0のログアウトエンドポイントにリダイレクトし、ブラウザー内のセッションをクリアする必要があります。他の場合と同様に、ユーザーがアプリから離れることでユーザーエクスペリエンスが損なわれないように、CapacitorのBrowserプラグインがリダイレクトを処理するようにします。 + + Auth0 SDKを使用してIonicとCapacitorで実現するには、以下を行います。 + + - アプリについて、ログアウト後にAuth0のリダイレクト先となるURLを構築します。これは、登録済みのカスタムスキームとAuth0ドメインを使ったURLです。これを、Auth0 Dashboardの**[Allowed Logout URLs(許可されているログアウトURL)]** の構成に追加します。 + - `logout`を呼び出し、`logoutParams.returnTo`パラメーターにリダイレクト先のURLを渡して、SDKからログアウトします。 + - CapacitorのBrowserプラグインを使用して`Browser.open`でURLを開くコールバックに、`openUrl`パラメーターを設定します。 + + + ログインの手順と同様に、`logout`を呼び出す際に`openUrl`を設定しないと、SDKがユーザーをログアウトURLにリダイレクトするのに、デバイスのデフォルトのブラウザーアプリケーションが使用されるため、ユーザーエクスペリエンスとしては最適ではありません。 + + + + ##### チェックポイント + ユーザーがアプリケーションからログアウトする方法を提供します。Auth0にリダイレクトしてから、returnToパラメーターで指定したアドレスへ移動することを確認します。ユーザーがアプリケーションにログインしていないことを確認します。 + +
    + +
    + Auth0 SDKは必要な任意のコンポーネントについて、名前やプロフィール写真など、ログイン済みのユーザーに関連付けられたプロファイル情報を取得し、ユーザーインターフェイスをパーソナライズします。プロファイル情報は、`AuthService`が公開する`user$`プロパティを介して使用することができます。 + + + ##### チェックポイント + ユーザーがアプリ内でユーザープロファイルの詳細を表示できる手段を提供し、ログインした後に自分のプロファイル情報を取得して画面に表示できることを確認します。 + +
    + + ## 次のステップ + + 成功です!ここまで来れば、アプリケーションにログイン、ログアウト、ユーザープロファイル情報が備わっているはずです。 + + これでクイックスタートチュートリアルは終了ですが、機能はまだまだたくさんあります。Auth0でできることについて詳しくは、以下をご覧ください。 + + * [Auth0 Dashboard](https://manage.auth0.com/#) - Auth0のテナントやアプリケーションを構成して管理する方法について説明します + * [Auth0 Marketplace](https://marketplace.auth0.com/) - Auth0の機能性を拡張できる各種の統合を見つけられます +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    diff --git a/main/docs/ja-jp/quickstart/native/ionic-react/interactive.mdx b/main/docs/ja-jp/quickstart/native/ionic-react/interactive.mdx index 1fd69d602..16d180c35 100644 --- a/main/docs/ja-jp/quickstart/native/ionic-react/interactive.mdx +++ b/main/docs/ja-jp/quickstart/native/ionic-react/interactive.mdx @@ -1,268 +1,270 @@ ---- -title: "Capacitorを用いたIonic React アプリにログインを追加する" -permalink: "interactive" -'description': "このガイドは、Ionic(React)とCapacitorのアプリケーションにAuth0 React SDKを使ってAuth0を統合する方法を説明します。" -'og:title': "Capacitorを用いたIonic React アプリにログインを追加する" -'og:description': "このガイドは、Ionic(React)とCapacitorのアプリケーションにAuth0 React SDKを使ってAuth0を統合する方法を説明します。" -'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/ionic.jpeg" -'twitter:title': "Capacitorを用いたIonic React アプリにログインを追加する" -'twitter:description': "このガイドは、Ionic(React)とCapacitorのアプリケーションにAuth0 React SDKを使ってAuth0を統合する方法を説明します。" -sidebarTitle: Ionic & Capacitor (React) ---- - -import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; -import { LoggedInForm } from "/snippets/Login.jsx"; -import Index from "/snippets/quickstart/native/ionic-react/index.tsx.mdx"; -import Loginbutton from "/snippets/quickstart/native/ionic-react/login-button.tsx.mdx"; -import Logoutbutton from "/snippets/quickstart/native/ionic-react/logout-button.tsx.mdx"; -import App from "/snippets/quickstart/native/ionic-react/app.tsx.mdx"; -import Userprofile from "/snippets/quickstart/native/ionic-react/user-profile.tsx.mdx"; - -export const sections = [ - { id: "使用を開始する", title: "使用を開始する" }, - { id: "auth0を構成する", title: "Auth0を構成する" }, - { id: "auth0-react-sdkをインストールする", title: "Auth0 React SDKをインストールする" }, - { id: "auth0providerコンポーネントを構成する", title: "Auth0Providerコンポーネントを構成する" }, - { id: "アプリケーションにログインを追加する", title: "アプリケーションにログインを追加する" }, - { id: "ログインコールバックを処理する", title: "ログインコールバックを処理する" }, - { id: "アプリケーションにログアウトを追加する", title: "アプリケーションにログアウトを追加する" }, - { id: "ユーザープロファイルを表示する", title: "ユーザープロファイルを表示する" } -] - - - - Auth0を使用すると、アプリケーションに手軽に認証を追加して、ユーザープロファイル情報にアクセスすることができます。このガイドは、Ionic(React)とCapacitorのアプリケーションに[Auth0 React SDK](https://github.com/auth0/auth0-react)を使ってAuth0を統合する方法を説明します。 - -
    - このクイックスタートは、[Ionic](https://ionicframework.com/)アプリケーションが[Capacitor](https://capacitorjs.com/)を使ってすでに実行されていることを前提としています。そうでない場合には、[IonicフレームワークでCapacitorを使用する](https://capacitorjs.com/docs/getting-started/with-ionic)ガイドを参照しながら簡単なアプリから始めるか、[サンプリアプリ](https://github.com/auth0-samples/auth0-ionic-samples)を複製してください。 - - また、[Capacitorの開発ワークフロー](https://capacitorjs.com/docs/basics/workflow)を理解しておく必要もあります。 -
    - -
    - Auth0のサービスを利用するには、Auth0 Dashboadに設定済みのアプリケーションがある必要があります。Auth0アプリケーションは、プロジェクトに対してどのように認証が動作して欲しいかを構成する場所です。 - - - 以下の説明では、「`YOUR_PACKAGE_ID`」を実際のアプリケーションのパッケージIDに置き換えてください。これは、`capacitor.config.ts`ファイルの`appId`フィールドで見つけて構成することができます。詳細については、[Capacitorの構成スキーマ](https://capacitorjs.com/docs/config#schema)を参照してください。 - - - ### アプリケーションを構成する - - 対話型のセレクターを使ってAuth0アプリケーションを新規作成するか、統合したいプロジェクトを表す既存のアプリケーションを選択します。Auth0のすべてのアプリケーションには英数字からなる一意のクライアントIDが割り当てられており、アプリケーションのコードがSDKを通じてAuth0 APIを呼び出す際に使用されます。 - - このクイックスタートを使って構成されたすべての設定は、[Dashboard](https://manage.auth0.com/#/)のアプリケーションを自動更新します。今後、アプリケーションの管理もDashboardで行えます。 - - 完了済みの構成を見てみたい場合は、サンプルアプリケーションをご覧ください。 - - ### Callback URLを構成する - - Callback URLとは、Auth0がユーザーを認証後にリダイレクトするアプリケーション内URLです。設定されていない場合、ユーザーはログイン後にアプリケーションに戻りません。 - - - サンプルプロジェクトに沿って進めている場合には、次の値に設定します: - - `YOUR_PACKAGE_ID://{yourTenant}.auth0.com/capacitor/YOUR_PACKAGE_ID/callback` - - - ### ログアウトURLを構成する - - ログアウトURLとは、Auth0がユーザーをログアウト後にリダイレクトするアプリケーション内URLです。設定されていない場合、ユーザーはアプリケーションからログアウトできず、エラーを受け取ります。 - - - サンプルプロジェクトに沿って進めている場合には、次の値に設定します: - - `YOUR_PACKAGE_ID://{yourTenant}.auth0.com/capacitor/YOUR_PACKAGE_ID/callback` - - - ### 許可されているオリジンを構成する - - ネイティブアプリケーションからAuth0へ要求を送信できるようにするには、[アプリケーションの設定](https://manage.auth0.com/dashboard/#/applications/%7ByourClientId%7D/settings)で次の**許可されているオリジン** を設定します。 - - - サンプルプロジェクトに沿って進めている場合、capacitorにiOSとAndroidでそれぞれ`capacitor://localhost, http://localhost`を設定します。 - - - 最後に、アプリケーションの**[Application Type(アプリケーションタイプ)]** が**[Native(ネイティブ)]** になっていることを[アプリケーションの設定](https://manage.auth0.com/dashboard/#/applications/%7ByourClientId%7D/settings)で必ず確認してください。 -
    - -
    - プロジェクトディレクトリで次のコマンドを実行して、Auth0 React SDKをインストールします: - - `npm install @auth0/auth0-react` - - SDKは、慣用的に[React Hooks](https://reactjs.org/docs/hooks-overview.html)や[高階コンポーネント(HOC)](https://reactjs.org/docs/higher-order-components.html)を使用して、Auth0をReactアプリケーションに統合しやすくするメソッドや変数を公開しています。 - - ### Capacitorプラグインをインストールする - - このクイックスタートとサンプルでは、Capacitorの公式プラグインをいくつか使用しています。次のコマンドを使用して、これらをアプリにインストールします: - - `npm install @capacitor/browser @capacitor/app` - - - [`@capacitor/browser`](https://capacitorjs.com/docs/apis/browser):デバイスのシステムブラウザーと対話できるようになり、Auth0の認可エンドポイントへのURLを開くために使用されます。 - - [`@capacitor/app`](https://capacitorjs.com/docs/apis/app):高レベルのアプリイベントを受け取れるようになるため、Auth0からのコールバックを扱うのに便利です。 - - - iOSのCapacitorのBrowserプラグインは[`SFSafariViewController`](https://developer.apple.com/documentation/safariservices/sfsafariviewcontroller)を使用し、iOS 11以降ではデバイス上のSafariとクッキーを共有しません。つまり、これらのデバイスではSSOが機能しません。SSOが必要な場合には、[ASWebAuthenticationSession](https://developer.apple.com/documentation/authenticationservices/aswebauthenticationsession)を使用する互換のプラグインを使用してください。 - -
    - -
    - 内部では、Auth0 React SDKは[React Context](https://reactjs.org/docs/context.html)を使用して、ユーザーの認証状態を管理します。Auth0をReactアプリに統合する1つの方法として、SDKからインポート可能な`Auth0Provider`でルートコンポーネントをラップすることができます。 - - `Auth0Provider`コンポーネントは以下のプロパティを使用します。 - - - `domain`:Auth0 Dashboardで作成したアプリケーションの**設定** にある`domain`値、またはAuth0のカスタムドメイン機能を使用する場合のカスタムドメインです。 - - `clientId`:Auth0 Dashboardで作成したアプリケーションの**設定** にあるクライアントID値です。 - - `useRefreshTokens`:AndroidまたはiOSでauth0-reactをIonicと使用するには、リフレッシュトークンを有効にする必要があります。 - - `useRefreshTokensFallback`:AndroidまたはiOSでauth0-reactをIonicと使用するには、iframeのフォールバックを無効にする必要があります。 - - `authorizationParams.redirect_uri`:Auth0で認証した後に、ユーザーをリダイレクトするURLです。 - - - アプリケーションの閉開後に認証を継続するには、SDKを構成する際に`cacheLocation`を`localstorage`に設定することをお勧めします。ただし、[localstorageにトークンを保管するリスク](/docs/ja-jp/libraries/auth0-single-page-app-sdk#change-storage-options)を理解してください。また、状況によってはlocalstorageのデータが思いがけず復元される可能性もあるため、Capacitorアプリ内では**一次的** なものとして扱ってください。[Capacitorドキュメントに記載のストレージに関するガイド](https://capacitorjs.com/docs/guides/storage#why-cant-i-just-use-localstorage-or-indexeddb)をお読みください。 - - さらに、より安全で永続的なストレージの仕組みが要件である場合、SDKを使用すると、[カスタムのキャッシュを実装](https://github.com/auth0/auth0-spa-js/blob/master/EXAMPLES.md#creating-a-custom-cache)してトークンを保管することができます。 - - **注意** :[CapacitorのStorageプラグイン](https://capacitorjs.com/docs/apis/storage)は、iOSでは[UserDefaults](https://developer.apple.com/documentation/foundation/userdefaults)、Androidでは[SharedPreferences](https://developer.android.com/reference/android/content/SharedPreferences)によってバックアップされるため、トークンの保管に使用**しない** ことをお勧めします。これらのAPIを使って保管されたデータは暗号化されません。セキュリティで保護されることもなく、クラウドと同期される可能性があります。 - - - - ##### チェックポイント - Auth0ProviderコンポーネントがAppコンポーネントをラップするようにして追加してから、アプリケーションを実行し、SDKが正しく初期化されていること、そして、アプリケーションがAuth0に関連したエラーを投入していないことを確認します。 - -
    - -
    - Capacitorアプリケーションでは、[CapacitorのBrowserプラグイン](https://capacitorjs.com/docs/apis/browser)によって、Auth0の[ユニバーサルログインページ](https://auth0.com/universal-login)にリダイレクトされます。`loginWithRedirect`関数の`openUrl`パラメーターに`Browser.open`の使用を設定し、デバイスのシステムブラウザーコンポーネント(iOSでは[SFSafariViewController](https://developer.apple.com/documentation/safariservices/sfsafariviewcontroller)、Androidでは[Chrome Custom Tabs](https://developer.chrome.com/docs/android/custom-tabs))でURLが開くようにします。 - - - SDKの`loginWithRedirect`メソッドは、デフォルトで`window.location.href`を使用して、ユーザーのデバイスにあるデフォルトのブラウザーアプリケーションでログインページを開きます。プラットフォームに適切なシステムブラウザーコンポーネントは使用しません。ユーザーが認証でアプリケーションを離れるため、ユーザーエクスペリエンスとしては最適ではありません。 - - - - ##### チェックポイント - loginWithRedirect関数は、SDKにログインフローを開始するように指示します。openUrlパラメーターにログインURLを設定して、Browser.open関数を呼び出し、プラットフォームのシステムブラウザーコンポーネントでログインURLを開きます。これは、ユーザーがアプリケーションにログインする方法を提供します。ユーザーはAuth0のログインページにリダイレクトされ、エラーは一切受け取りません。 - -
    - -
    - ユーザーがユニバーサルログインページでログインすると、カスタムURLスキームを使ったURLでアプリにリダイレクトされます。`appUrlOpen`イベントがアプリ内で処理されなければなりません。Auth0 SDKの`handleRedirectCallback`メソッドを呼び出すと、認証状態を初期化することができます。 - - このメソッドは、Auth0からのリダイレクトでのみ使用することができます。正常に機能していることを確認するには、URL内の`code`と`state`パラメーターを確認します。 - - このイベントが発生した際に、`Browser.close()`メソッドがブラウザーを閉じるようにします。 - - - 以下の説明では、カスタムURLスキームを使用して、アプリケーション内でコールバックを処理することを前提にしています。このためには、`YOUR_PACKAGE_ID`を選択したプラットのURLスキームで置き換えて登録します。詳細については、iOSには「[カスタムURLスキームを定義する](https://developer.apple.com/documentation/xcode/defining-a-custom-url-scheme-for-your-app)」、Androidには「[アプリコンテンツ用のディープリンクを作成する](https://developer.android.com/training/app-links/deep-linking)」をお読みください。 - - - - ##### チェックポイント - アプリケーションのAppコンポーネントにappUrlOpenを追加して、ログインします。ユーザーが認証して、アプリにログインすると、ブラウザーのウィンドウが閉じます。 - -
    - -
    - ユーザーがログインできるようになりました。今度は、[ログアウトする方法](/docs/ja-jp/logout/guides/logout-auth0)を構成する必要があります。ユーザーをAuth0のログアウトエンドポイントにリダイレクトし、ブラウザー内のセッションをクリアする必要があります。他の場合と同様に、ユーザーがアプリから離れることでユーザーエクスペリエンスが損なわれないように、CapacitorのBrowserプラグインがリダイレクトを処理するようにします。 - - Auth0 SDKを使用してIonicとCapacitorで実現するには、以下を行います。 - - - アプリについて、ログアウト後にAuth0のリダイレクト先となるURLを構築します。これは、登録済みのカスタムスキームとAuth0ドメインを使ったURLです。これを、Auth0 Dashboardの**[Allowed Logout URLs(許可されているログアウトURL)]** の構成に追加します。 - - `logout`を呼び出し、`logoutParams.returnTo`パラメーターにリダイレクト先のURLを渡して、SDKからログアウトします。 - - CapacitorのBrowserプラグインを使用して`Browser.open`でURLを開くコールバックに、`openUrl`パラメーターを設定します。 - - - ログインの手順と同様に、`logout`を呼び出す際に`openUrl`を設定しないと、SDKがユーザーをログアウトURLにリダイレクトするのに、デバイスのデフォルトのブラウザーアプリケーションが使用されるため、ユーザーエクスペリエンスとしては最適ではありません。 - - - - ##### チェックポイント - ユーザーがアプリケーションからログアウトする方法を提供します。Auth0にリダイレクトしてから、returnToパラメーターで指定したアドレスへ移動することを確認します。アプリケーションにログインしていないことを確認します。 - -
    - -
    - Auth0 React SDKは必要な任意のコンポーネントについて、名前やプロフィール写真など、ログイン済みのユーザーに関連付けられたユーザープロファイルを取得し、ユーザーインターフェイスをパーソナライズします。プロファイル情報は、`useAuth0()`フックが公開する`user`プロパティを介して使用することができます。 - - SDKの初期化は非同期に行われます。`isLoading`と`user`プロパティを確認して、ユーザープロファイルを保護する必要があります。`isLoading`が`false`になり、`user`が値を持つと、ユーザープロファイルを利用することができます。 - - - ##### チェックポイント - ユーザーがアプリ内でユーザープロファイルの詳細を表示できる手段を提供し、ログインした後に自分のプロファイル情報を取得して画面に表示できることを確認します。 - -
    - - ## 次のステップ - - 成功です!ここまで来れば、アプリケーションにログイン、ログアウト、ユーザープロファイル情報が備わっているはずです。 - - これでクイックスタートチュートリアルは終了ですが、機能はまだまだたくさんあります。Auth0でできることについて詳しくは、以下をご覧ください。 - - * [Auth0 Dashboard](https://manage.auth0.com/#) - Auth0のテナントやアプリケーションを構成して管理する方法について説明します - * [Auth0 Marketplace](https://marketplace.auth0.com/) - Auth0の機能性を拡張できる各種の統合を見つけられます -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    +--- +title: "Capacitorを用いたIonic React アプリにログインを追加する" +permalink: "interactive" +'description': "このガイドは、Ionic(React)とCapacitorのアプリケーションにAuth0 React SDKを使ってAuth0を統合する方法を説明します。" +'og:title': "Capacitorを用いたIonic React アプリにログインを追加する" +'og:description': "このガイドは、Ionic(React)とCapacitorのアプリケーションにAuth0 React SDKを使ってAuth0を統合する方法を説明します。" +'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/ionic.jpeg" +'twitter:title': "Capacitorを用いたIonic React アプリにログインを追加する" +'twitter:description': "このガイドは、Ionic(React)とCapacitorのアプリケーションにAuth0 React SDKを使ってAuth0を統合する方法を説明します。" +sidebarTitle: Ionic & Capacitor (React) +--- + +import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; +import { LoggedInForm } from "/snippets/Login.jsx"; +import Index from "/snippets/quickstart/native/ionic-react/index.tsx.mdx"; +import Loginbutton from "/snippets/quickstart/native/ionic-react/login-button.tsx.mdx"; +import Logoutbutton from "/snippets/quickstart/native/ionic-react/logout-button.tsx.mdx"; +import App from "/snippets/quickstart/native/ionic-react/app.tsx.mdx"; +import Userprofile from "/snippets/quickstart/native/ionic-react/user-profile.tsx.mdx"; + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + +export const sections = [ + { id: "使用を開始する", title: "使用を開始する" }, + { id: "auth0を構成する", title: "Auth0を構成する" }, + { id: "auth0-react-sdkをインストールする", title: "Auth0 React SDKをインストールする" }, + { id: "auth0providerコンポーネントを構成する", title: "Auth0Providerコンポーネントを構成する" }, + { id: "アプリケーションにログインを追加する", title: "アプリケーションにログインを追加する" }, + { id: "ログインコールバックを処理する", title: "ログインコールバックを処理する" }, + { id: "アプリケーションにログアウトを追加する", title: "アプリケーションにログアウトを追加する" }, + { id: "ユーザープロファイルを表示する", title: "ユーザープロファイルを表示する" } +] + + + + Auth0を使用すると、アプリケーションに手軽に認証を追加して、ユーザープロファイル情報にアクセスすることができます。このガイドは、Ionic(React)とCapacitorのアプリケーションに[Auth0 React SDK](https://github.com/auth0/auth0-react)を使ってAuth0を統合する方法を説明します。 + +
    + このクイックスタートは、[Ionic](https://ionicframework.com/)アプリケーションが[Capacitor](https://capacitorjs.com/)を使ってすでに実行されていることを前提としています。そうでない場合には、[IonicフレームワークでCapacitorを使用する](https://capacitorjs.com/docs/getting-started/with-ionic)ガイドを参照しながら簡単なアプリから始めるか、[サンプリアプリ](https://github.com/auth0-samples/auth0-ionic-samples)を複製してください。 + + また、[Capacitorの開発ワークフロー](https://capacitorjs.com/docs/basics/workflow)を理解しておく必要もあります。 +
    + +
    + Auth0のサービスを利用するには、Auth0 Dashboadに設定済みのアプリケーションがある必要があります。Auth0アプリケーションは、プロジェクトに対してどのように認証が動作して欲しいかを構成する場所です。 + + + 以下の説明では、「`YOUR_PACKAGE_ID`」を実際のアプリケーションのパッケージIDに置き換えてください。これは、`capacitor.config.ts`ファイルの`appId`フィールドで見つけて構成することができます。詳細については、[Capacitorの構成スキーマ](https://capacitorjs.com/docs/config#schema)を参照してください。 + + + ### アプリケーションを構成する + + 対話型のセレクターを使ってAuth0アプリケーションを新規作成するか、統合したいプロジェクトを表す既存のアプリケーションを選択します。Auth0のすべてのアプリケーションには英数字からなる一意のクライアントIDが割り当てられており、アプリケーションのコードがSDKを通じてAuth0 APIを呼び出す際に使用されます。 + + このクイックスタートを使って構成されたすべての設定は、[Dashboard](https://manage.auth0.com/#/)のアプリケーションを自動更新します。今後、アプリケーションの管理もDashboardで行えます。 + + 完了済みの構成を見てみたい場合は、サンプルアプリケーションをご覧ください。 + + ### Callback URLを構成する + + Callback URLとは、Auth0がユーザーを認証後にリダイレクトするアプリケーション内URLです。設定されていない場合、ユーザーはログイン後にアプリケーションに戻りません。 + + + サンプルプロジェクトに沿って進めている場合には、次の値に設定します: + + `YOUR_PACKAGE_ID://{yourTenant}.auth0.com/capacitor/YOUR_PACKAGE_ID/callback` + + + ### ログアウトURLを構成する + + ログアウトURLとは、Auth0がユーザーをログアウト後にリダイレクトするアプリケーション内URLです。設定されていない場合、ユーザーはアプリケーションからログアウトできず、エラーを受け取ります。 + + + サンプルプロジェクトに沿って進めている場合には、次の値に設定します: + + `YOUR_PACKAGE_ID://{yourTenant}.auth0.com/capacitor/YOUR_PACKAGE_ID/callback` + + + ### 許可されているオリジンを構成する + + ネイティブアプリケーションからAuth0へ要求を送信できるようにするには、[アプリケーションの設定](https://manage.auth0.com/dashboard/#/applications/%7ByourClientId%7D/settings)で次の**許可されているオリジン** を設定します。 + + + サンプルプロジェクトに沿って進めている場合、capacitorにiOSとAndroidでそれぞれ`capacitor://localhost, http://localhost`を設定します。 + + + 最後に、アプリケーションの**[Application Type(アプリケーションタイプ)]** が**[Native(ネイティブ)]** になっていることを[アプリケーションの設定](https://manage.auth0.com/dashboard/#/applications/%7ByourClientId%7D/settings)で必ず確認してください。 +
    + +
    + プロジェクトディレクトリで次のコマンドを実行して、Auth0 React SDKをインストールします: + + `npm install @auth0/auth0-react` + + SDKは、慣用的に[React Hooks](https://reactjs.org/docs/hooks-overview.html)や[高階コンポーネント(HOC)](https://reactjs.org/docs/higher-order-components.html)を使用して、Auth0をReactアプリケーションに統合しやすくするメソッドや変数を公開しています。 + + ### Capacitorプラグインをインストールする + + このクイックスタートとサンプルでは、Capacitorの公式プラグインをいくつか使用しています。次のコマンドを使用して、これらをアプリにインストールします: + + `npm install @capacitor/browser @capacitor/app` + + - [`@capacitor/browser`](https://capacitorjs.com/docs/apis/browser):デバイスのシステムブラウザーと対話できるようになり、Auth0の認可エンドポイントへのURLを開くために使用されます。 + - [`@capacitor/app`](https://capacitorjs.com/docs/apis/app):高レベルのアプリイベントを受け取れるようになるため、Auth0からのコールバックを扱うのに便利です。 + + + iOSのCapacitorのBrowserプラグインは[`SFSafariViewController`](https://developer.apple.com/documentation/safariservices/sfsafariviewcontroller)を使用し、iOS 11以降ではデバイス上のSafariとクッキーを共有しません。つまり、これらのデバイスではSSOが機能しません。SSOが必要な場合には、[ASWebAuthenticationSession](https://developer.apple.com/documentation/authenticationservices/aswebauthenticationsession)を使用する互換のプラグインを使用してください。 + +
    + +
    + 内部では、Auth0 React SDKは[React Context](https://reactjs.org/docs/context.html)を使用して、ユーザーの認証状態を管理します。Auth0をReactアプリに統合する1つの方法として、SDKからインポート可能な`Auth0Provider`でルートコンポーネントをラップすることができます。 + + `Auth0Provider`コンポーネントは以下のプロパティを使用します。 + + - `domain`:Auth0 Dashboardで作成したアプリケーションの**設定** にある`domain`値、またはAuth0のカスタムドメイン機能を使用する場合のカスタムドメインです。 + - `clientId`:Auth0 Dashboardで作成したアプリケーションの**設定** にあるクライアントID値です。 + - `useRefreshTokens`:AndroidまたはiOSでauth0-reactをIonicと使用するには、リフレッシュトークンを有効にする必要があります。 + - `useRefreshTokensFallback`:AndroidまたはiOSでauth0-reactをIonicと使用するには、iframeのフォールバックを無効にする必要があります。 + - `authorizationParams.redirect_uri`:Auth0で認証した後に、ユーザーをリダイレクトするURLです。 + + + アプリケーションの閉開後に認証を継続するには、SDKを構成する際に`cacheLocation`を`localstorage`に設定することをお勧めします。ただし、[localstorageにトークンを保管するリスク](/docs/ja-jp/libraries/auth0-single-page-app-sdk#change-storage-options)を理解してください。また、状況によってはlocalstorageのデータが思いがけず復元される可能性もあるため、Capacitorアプリ内では**一次的** なものとして扱ってください。[Capacitorドキュメントに記載のストレージに関するガイド](https://capacitorjs.com/docs/guides/storage#why-cant-i-just-use-localstorage-or-indexeddb)をお読みください。 + + さらに、より安全で永続的なストレージの仕組みが要件である場合、SDKを使用すると、[カスタムのキャッシュを実装](https://github.com/auth0/auth0-spa-js/blob/master/EXAMPLES.md#creating-a-custom-cache)してトークンを保管することができます。 + + **注意** :[CapacitorのStorageプラグイン](https://capacitorjs.com/docs/apis/storage)は、iOSでは[UserDefaults](https://developer.apple.com/documentation/foundation/userdefaults)、Androidでは[SharedPreferences](https://developer.android.com/reference/android/content/SharedPreferences)によってバックアップされるため、トークンの保管に使用**しない** ことをお勧めします。これらのAPIを使って保管されたデータは暗号化されません。セキュリティで保護されることもなく、クラウドと同期される可能性があります。 + + + + ##### チェックポイント + Auth0ProviderコンポーネントがAppコンポーネントをラップするようにして追加してから、アプリケーションを実行し、SDKが正しく初期化されていること、そして、アプリケーションがAuth0に関連したエラーを投入していないことを確認します。 + +
    + +
    + Capacitorアプリケーションでは、[CapacitorのBrowserプラグイン](https://capacitorjs.com/docs/apis/browser)によって、Auth0の[ユニバーサルログインページ](https://auth0.com/universal-login)にリダイレクトされます。`loginWithRedirect`関数の`openUrl`パラメーターに`Browser.open`の使用を設定し、デバイスのシステムブラウザーコンポーネント(iOSでは[SFSafariViewController](https://developer.apple.com/documentation/safariservices/sfsafariviewcontroller)、Androidでは[Chrome Custom Tabs](https://developer.chrome.com/docs/android/custom-tabs))でURLが開くようにします。 + + + SDKの`loginWithRedirect`メソッドは、デフォルトで`window.location.href`を使用して、ユーザーのデバイスにあるデフォルトのブラウザーアプリケーションでログインページを開きます。プラットフォームに適切なシステムブラウザーコンポーネントは使用しません。ユーザーが認証でアプリケーションを離れるため、ユーザーエクスペリエンスとしては最適ではありません。 + + + + ##### チェックポイント + loginWithRedirect関数は、SDKにログインフローを開始するように指示します。openUrlパラメーターにログインURLを設定して、Browser.open関数を呼び出し、プラットフォームのシステムブラウザーコンポーネントでログインURLを開きます。これは、ユーザーがアプリケーションにログインする方法を提供します。ユーザーはAuth0のログインページにリダイレクトされ、エラーは一切受け取りません。 + +
    + +
    + ユーザーがユニバーサルログインページでログインすると、カスタムURLスキームを使ったURLでアプリにリダイレクトされます。`appUrlOpen`イベントがアプリ内で処理されなければなりません。Auth0 SDKの`handleRedirectCallback`メソッドを呼び出すと、認証状態を初期化することができます。 + + このメソッドは、Auth0からのリダイレクトでのみ使用することができます。正常に機能していることを確認するには、URL内の`code`と`state`パラメーターを確認します。 + + このイベントが発生した際に、`Browser.close()`メソッドがブラウザーを閉じるようにします。 + + + 以下の説明では、カスタムURLスキームを使用して、アプリケーション内でコールバックを処理することを前提にしています。このためには、`YOUR_PACKAGE_ID`を選択したプラットのURLスキームで置き換えて登録します。詳細については、iOSには「[カスタムURLスキームを定義する](https://developer.apple.com/documentation/xcode/defining-a-custom-url-scheme-for-your-app)」、Androidには「[アプリコンテンツ用のディープリンクを作成する](https://developer.android.com/training/app-links/deep-linking)」をお読みください。 + + + + ##### チェックポイント + アプリケーションのAppコンポーネントにappUrlOpenを追加して、ログインします。ユーザーが認証して、アプリにログインすると、ブラウザーのウィンドウが閉じます。 + +
    + +
    + ユーザーがログインできるようになりました。今度は、[ログアウトする方法](/docs/ja-jp/logout/guides/logout-auth0)を構成する必要があります。ユーザーをAuth0のログアウトエンドポイントにリダイレクトし、ブラウザー内のセッションをクリアする必要があります。他の場合と同様に、ユーザーがアプリから離れることでユーザーエクスペリエンスが損なわれないように、CapacitorのBrowserプラグインがリダイレクトを処理するようにします。 + + Auth0 SDKを使用してIonicとCapacitorで実現するには、以下を行います。 + + - アプリについて、ログアウト後にAuth0のリダイレクト先となるURLを構築します。これは、登録済みのカスタムスキームとAuth0ドメインを使ったURLです。これを、Auth0 Dashboardの**[Allowed Logout URLs(許可されているログアウトURL)]** の構成に追加します。 + - `logout`を呼び出し、`logoutParams.returnTo`パラメーターにリダイレクト先のURLを渡して、SDKからログアウトします。 + - CapacitorのBrowserプラグインを使用して`Browser.open`でURLを開くコールバックに、`openUrl`パラメーターを設定します。 + + + ログインの手順と同様に、`logout`を呼び出す際に`openUrl`を設定しないと、SDKがユーザーをログアウトURLにリダイレクトするのに、デバイスのデフォルトのブラウザーアプリケーションが使用されるため、ユーザーエクスペリエンスとしては最適ではありません。 + + + + ##### チェックポイント + ユーザーがアプリケーションからログアウトする方法を提供します。Auth0にリダイレクトしてから、returnToパラメーターで指定したアドレスへ移動することを確認します。アプリケーションにログインしていないことを確認します。 + +
    + +
    + Auth0 React SDKは必要な任意のコンポーネントについて、名前やプロフィール写真など、ログイン済みのユーザーに関連付けられたユーザープロファイルを取得し、ユーザーインターフェイスをパーソナライズします。プロファイル情報は、`useAuth0()`フックが公開する`user`プロパティを介して使用することができます。 + + SDKの初期化は非同期に行われます。`isLoading`と`user`プロパティを確認して、ユーザープロファイルを保護する必要があります。`isLoading`が`false`になり、`user`が値を持つと、ユーザープロファイルを利用することができます。 + + + ##### チェックポイント + ユーザーがアプリ内でユーザープロファイルの詳細を表示できる手段を提供し、ログインした後に自分のプロファイル情報を取得して画面に表示できることを確認します。 + +
    + + ## 次のステップ + + 成功です!ここまで来れば、アプリケーションにログイン、ログアウト、ユーザープロファイル情報が備わっているはずです。 + + これでクイックスタートチュートリアルは終了ですが、機能はまだまだたくさんあります。Auth0でできることについて詳しくは、以下をご覧ください。 + + * [Auth0 Dashboard](https://manage.auth0.com/#) - Auth0のテナントやアプリケーションを構成して管理する方法について説明します + * [Auth0 Marketplace](https://marketplace.auth0.com/) - Auth0の機能性を拡張できる各種の統合を見つけられます +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    diff --git a/main/docs/ja-jp/quickstart/native/ionic-vue/interactive.mdx b/main/docs/ja-jp/quickstart/native/ionic-vue/interactive.mdx index b5933a071..671363067 100644 --- a/main/docs/ja-jp/quickstart/native/ionic-vue/interactive.mdx +++ b/main/docs/ja-jp/quickstart/native/ionic-vue/interactive.mdx @@ -1,258 +1,260 @@ ---- -title: "CapacitorアプリでIonic Vueにログインを追加する" -permalink: "interactive" -'description': "このガイドは、Ionic(Vue)とCapacitrorのアプリケーションにAuth0 Vue SDKを使ってAuth0を統合する方法を説明します。" -'og:title': "CapacitorアプリでIonic Vueにログインを追加する" -'og:description': "このガイドは、Ionic(Vue)とCapacitrorのアプリケーションにAuth0 Vue SDKを使ってAuth0を統合する方法を説明します。" -'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/ionic.jpeg" -'twitter:title': "CapacitorアプリでIonic Vueにログインを追加する" -'twitter:description': "このガイドは、Ionic(Vue)とCapacitrorのアプリケーションにAuth0 Vue SDKを使ってAuth0を統合する方法を説明します。" -sidebarTitle: Ionic & Capacitor (Vue) ---- - -import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; -import { LoggedInForm } from "/snippets/Login.jsx"; -import Main from "/snippets/quickstart/native/ionic-vue/main.ts.mdx"; -import Loginbutton from "/snippets/quickstart/native/ionic-vue/LoginButton.vue.mdx"; -import Logoutbutton from "/snippets/quickstart/native/ionic-vue/LogoutButton.vue.mdx"; -import Userprofile from "/snippets/quickstart/native/ionic-vue/UserProfile.vue.mdx"; - -export const sections = [ - { id: "使用を開始する", title: "使用を開始する" }, - { id: "auth0を構成する", title: "Auth0を構成する" }, - { id: "auth0-vue-sdkをインストールする", title: "Auth0 Vue SDKをインストールする" }, - { id: "createauht0プラグインを構成する", title: "CreateAuht0プラグインを構成する" }, - { id: "アプリケーションにログインを追加する", title: "アプリケーションにログインを追加する" }, - { id: "ログインコールバックを処理する", title: "ログインコールバックを処理する" }, - { id: "アプリケーションにログアウトを追加する", title: "アプリケーションにログアウトを追加する" }, - { id: "ユーザープロファイルを表示する", title: "ユーザープロファイルを表示する" } -] - - - - Auth0を使用すると、アプリケーションに手軽に認証を追加して、ユーザープロファイル情報にアクセスすることができます。このガイドは、Ionic(Vue)とCapacitrorのアプリケーションに[Auth0 Vue SDK](https://github.com/auth0/auth0-vue)を使ってAuth0を統合する方法を説明します。 - -
    - このクイックスタートは、[Ionic](https://ionicframework.com/)アプリケーションが[Capacitor](https://capacitorjs.com/)を使ってすでに実行されていることを前提としています。そうでない場合には、[IonicフレームワークでCapacitorを使用する](https://capacitorjs.com/docs/getting-started/with-ionic)ガイドを参照しながら簡単なアプリから始めるか、[サンプルアプリ](https://github.com/auth0-samples/auth0-ionic-samples)を複製してください。 - - また、[Capacitorの開発ワークフロー](https://capacitorjs.com/docs/basics/workflow)を理解しておく必要もあります。 -
    - -
    - Auth0のサービスを利用するには、Auth0 Dashboadに設定済みのアプリケーションがある必要があります。Auth0アプリケーションは、プロジェクトに対してどのように認証が動作して欲しいかを構成する場所です。 - - - 以下の説明では、`YOUR_PACKAGE_ID`を実際のアプリケーションのパッケージIDに置き換えてください。これは、`capacitor.config.ts`ファイルの`appId`フィールドで見つけて構成することができます。詳細については、[Capacitorの構成スキーマ](https://capacitorjs.com/docs/config#schema)を参照してください。 - - - ### アプリケーションを構成する - - 対話型のセレクターを使ってAuth0アプリケーションを新規作成するか、統合したいプロジェクトを表す既存のアプリケーションを選択します。Auth0のすべてのアプリケーションには英数字からなる一意のクライアントIDが割り当てられており、アプリケーションのコードがSDKを通じてAuth0 APIを呼び出す際に使用されます。 - - このクイックスタートを使って構成されたすべての設定は、[Dashboard](https://manage.auth0.com/#/)のアプリケーションを自動更新します。今後、アプリケーションの管理もDashboardで行えます。 - - 代わりに完了済みの構成を見てみたい場合は、サンプルアプリケーションをご覧ください。 - - ### Callback URLを構成する - - Callback URLとは、Auth0がユーザーを認証後にリダイレクトするアプリケーション内URLです。設定されていない場合、ユーザーはログイン後にアプリケーションに戻りません。 - - - サンプルプロジェクトに沿って進めている場合は、`YOUR_PACKAGE_ID://{yourDomain}/capacitor/YOUR_PACKAGE_ID/callback`に設定してください。 - - - ### ログアウトURLを構成する - - ログアウトURLとは、Auth0がユーザーをログアウト後にリダイレクトするアプリケーション内URLです。設定されていない場合、ユーザーはアプリケーションからログアウトできず、エラーを受け取ります。 - - - サンプルプロジェクトに沿って進めている場合は、`YOUR_PACKAGE_ID://{yourDomain}/capacitor/YOUR_PACKAGE_ID/callback`に設定してください。 - - - ### 許可されているオリジンを構成する - - ネイティブアプリケーションからAuth0へ要求を送信できるようにするには、[アプリケーションの設定](https://manage.auth0.com/#/applications/%7ByourClientId%7D/settings)で次の**許可されているオリジン** を設定します。 - - - サンプルプロジェクトに沿って進めている場合、iOSとAndroidでそれぞれ`capacitor://localhost, http://localhost`を設定します。 - - - 最後に、アプリケーションの**[Application Type(アプリケーションタイプ)]** が**[Native(ネイティブ)]** になっていることを[アプリケーションの設定](https://manage.auth0.com/#/applications/%7ByourClientId%7D/settings)で必ず確認してください。 -
    - -
    - プロジェクトディレクトリで次のコマンドを実行して、Auth0 Vue SDKをインストールします: - - `npm install @auth0/auth0-vue` - - SDKはモジュールや認証サービスなど、Auth0をVueアプリケーションに慣用的に統合しやすくする種類をいくつか公開しています。 - - ### Capacitorプラグインをインストールする - - このクイックスタートとサンプルでは、Capacitorの公式プラグインをいくつか使用しています。次のコマンドを使用して、これらをアプリにインストールします: - - npm install @capacitor/browser @capacitor/app - - - [`@capacitor/browser`](https://capacitorjs.com/docs/apis/browser):デバイスのシステムブラウザーと対話できるようになり、Auth0の認可エンドポイントへのURLを開くために使用されます - - [`@capacitor/app`](https://capacitorjs.com/docs/apis/app):高レベルのアプリイベントを受け取れるようになるため、Auth0からのコールバックを扱うのに便利です - - - iOSのCapacitorのBrowserプラグインは[`SFSafariViewController`](https://developer.apple.com/documentation/safariservices/sfsafariviewcontroller)を使用し、iOS 11以降ではデバイス上のSafariとクッキーを共有しません。つまり、これらのデバイスでは[SSO](/docs/ja-jp/sso)が機能しません。SSOが必要な場合には、[ASWebAuthenticationSession](https://developer.apple.com/documentation/authenticationservices/aswebauthenticationsession)を使用する互換性のあるプラグインを使用してください。 - -
    - -
    - SDKは、SDKが機能するために必要なすべてのサービスを含んだコンポーザブル、`createAuth0`をエクスポートします。このコンポーザブルをアプリケーションに登録し、Auth0のドメインとクライアントIDで構成する必要があります。 - - `createAuth0`コンポーザブルは以下の構成を取ります。 - - - `domain`:Auth0 Dashboardで作成したアプリケーションの**[Settings(設定)]** にある`domain`値、またはAuth0の[カスタムドメイン機能](http://localhost:3000/docs/custom-domains)を使用する場合のカスタムドメインです。 - - `clientId`:Auth0 Dashboardで作成したアプリケーションの**[Settings(設定)]** にあるクライアントID値です。 - - `useRefreshTokens`:AndroidまたはiOSでauth0-vueをIonicと使用するには、リフレッシュトークンを有効にする必要があります。 - - `useRefreshTokensFallback`:AndroidまたはiOSでauth0-vueをIonicと使用するには、iframeのフォールバックを無効にする必要があります。 - - `authorizationParams.redirect_uri`:Auth0で認証した後に、ユーザーをリダイレクトするURLです。 - - - アプリケーションの閉開後に認証を継続するには、SDKを構成する際に`cacheLocation`を`localstorage`に設定することをお勧めします。ただし、[localstorageにトークンを保管するリスク](/docs/ja-jp/libraries/auth0-single-page-app-sdk#change-storage-options)を理解してください。また、状況によってはlocalstorageのデータが思いがけず復元される可能性もあるため、Capacitorアプリ内では**一次的** なものとして扱ってください。[Capacitorドキュメントに記載のストレージに関するガイド](https://capacitorjs.com/docs/guides/storage#why-cant-i-just-use-localstorage-or-indexeddb)をお読みください。 - - さらに、より安全で永続的なストレージの仕組みが要件である場合、SDKを使用すると、[カスタムのキャッシュを実装](https://github.com/auth0/auth0-spa-js/blob/master/EXAMPLES.md#creating-a-custom-cache)してトークンを保管することができます。 - - **注意** :[CapacitorのStorageプラグイン](https://capacitorjs.com/docs/apis/storage)は、iOSでは[UserDefaults](https://developer.apple.com/documentation/foundation/userdefaults)、Androidでは[SharedPreferences](https://developer.android.com/reference/android/content/SharedPreferences)によってバックアップされるため、トークンの保管に使用**しない** ことをお勧めします。これらのAPIを使って保管されたデータは暗号化されません。セキュリティで保護されることもなく、クラウドと同期される可能性があります。 - - - - ##### チェックポイント - アプリがAuth0 Vue SDKで構成されました。今度は、アプリケーションを実行して、SDKがエラーなく初期化されること、そして、以前と同じように動作することを確認します。 - -
    - -
    - Capacitorアプリケーションでは、[CapacitorのBrowserプラグイン](https://capacitorjs.com/docs/apis/browser)によって、Auth0の[ユニバーサルログインページ](https://auth0.com/universal-login)にリダイレクトされます。`loginWithRedirect`関数の`openUrl`パラメーターに`Browser.open`の使用を設定し、デバイスのシステムブラウザーコンポーネント(iOSでは[SFSafariViewController](https://developer.apple.com/documentation/safariservices/sfsafariviewcontroller)、Androidでは[Chrome Custom Tabs](https://developer.chrome.com/docs/android/custom-tabs))でURLが開くようにします。 - - - SDKの`loginWithRedirect`メソッドは、デフォルトで`window.location.href`を使用して、ユーザーのデバイスにあるデフォルトのブラウザーアプリケーションでログインページを開きます。プラットフォームに適切なシステムブラウザーコンポーネントは使用しません。ユーザーが認証でアプリケーションを離れるため、ユーザーエクスペリエンスとしては最適ではありません。 - - - - ##### チェックポイント - loginWithRedirect関数は、SDKにログインフローを開始するように指示します。openUrlパラメーターを設定して、Browser.open関数を呼び出し、プラットフォームのシステムブラウザーコンポーネントでログインURLを開きます。これは、ユーザーがアプリケーションにログインする方法を提供します。ユーザーはAuth0のログインページにリダイレクトされ、エラーは一切受け取りません。 - -
    - -
    - ユーザーがユニバーサルログインページでログインすると、カスタムURLスキームを使ったURLでアプリにリダイレクトされます。`appUrlOpen`イベントがアプリ内で処理されなければなりません。Auth0 SDKの`handleRedirectCallback`メソッドを呼び出すと、認証状態を初期化することができます。 - - このメソッドは、Auth0からのリダイレクトでのみ使用することができます。正常に機能していることを確認するには、URL内の`code`と`state`パラメーターを確認します。 - - このイベントが発生した際に、`Browser.close()`メソッドがブラウザーを閉じるようにします。 - - - 以下の説明では、カスタムURLスキームを使用して、アプリケーション内でコールバックを処理することを前提にしています。このためには、`YOUR_PACKAGE_ID`を選択したプラットフォームのURLスキームで置き換えて登録します。詳細については、iOSには「[カスタムURLスキームを定義する](https://developer.apple.com/documentation/xcode/defining-a-custom-url-scheme-for-your-app)」、Androidには「[アプリコンテンツ用のディープリンクを作成する](https://developer.android.com/training/app-links/deep-linking)」をお読みください。 - - - - ##### チェックポイント - アプリケーションのAppコンポーネントセットアップにappUrlOpenを追加して、ログインします。ユーザーが認証して、アプリにログインすると、ブラウザーのウィンドウが閉じます。 - -
    - -
    - ユーザーがログインできるようになりました。今度は、[ログアウトする方法](/docs/ja-jp/logout/guides/logout-auth0)を構成する必要があります。ユーザーをAuth0のログアウトエンドポイントにリダイレクトし、ブラウザー内のセッションをクリアする必要があります。他の場合と同様に、ユーザーがアプリから離れることでユーザーエクスペリエンスが損なわれないように、CapacitorのBrowserプラグインがリダイレクトを処理するようにします。 - - Auth0 SDKを使用してIonicとCapacitorで実現するには、以下を行います。 - - - アプリについて、ログアウト後にAuth0のリダイレクト先となるURLを構築します。これは、登録済みのカスタムスキームとAuth0ドメインを使ったURLです。これを、Auth0 Dashboardの**[Allowed Logout URLs(許可されているログアウトURL)]** の構成に追加します。 - - `logout`を呼び出し、`logoutParams.returnTo`パラメーターにリダイレクト先のURLを渡して、SDKからログアウトします。 - - CapacitorのBrowserプラグインを使用して`Browser.open`でURLを開くコールバックに、`openUrl`パラメーターを設定します。 - - - ログインの手順と同様に、`logout`を呼び出す際に`openUrl`を設定しないと、SDKがユーザーをログアウトURLにリダイレクトするのに、デバイスのデフォルトのブラウザーアプリケーションが使用されるため、ユーザーエクスペリエンスとしては最適ではありません。 - - - - ##### チェックポイント - ユーザーがアプリケーションからログアウトする方法を提供します。Auth0にリダイレクトしてから、returnToパラメーターで指定したアドレスへ移動することを確認します。アプリケーションにログインしていないことを確認します。 - -
    - -
    - Auth0 Vue SDKは必要な任意のコンポーネントについて、名前やプロフィール写真など、ログイン済みのユーザーに関連付けられた[ユーザープロファイル](/docs/ja-jp/users/concepts/overview-user-profile)を取得し、ユーザーインターフェイスをパーソナライズします。プロファイル情報は、`useAuth0()`コンポーザブルが公開する`user`プロパティを介して使用することができます。 - - SDKの初期化は非同期に行われます。`isLoading`と`user`プロパティを確認して、ユーザープロファイルを保護する必要があります。`isLoading`が`false`になり、`user`が値を持つと、ユーザープロファイルを利用することができます。 - - - ##### チェックポイント - ユーザーがアプリ内でユーザープロファイルの詳細を表示できる手段を提供し、ログインした後に自分のプロファイル情報を取得して画面に表示できることを確認します。 - -
    - - ## 次のステップ - - 成功です!ここまで来れば、アプリケーションにログイン、ログアウト、ユーザープロファイル情報が備わっているはずです。 - - これでクイックスタートチュートリアルは終了ですが、機能はまだまだたくさんあります。Auth0でできることについて詳しくは、以下をご覧ください。 - - * [Auth0 Dashboard](https://manage.auth0.com/#) - Auth0のテナントやアプリケーションを構成して管理する方法について説明します - * [Auth0 Marketplace](https://marketplace.auth0.com/) - Auth0の機能性を拡張できる各種の統合を見つけられます -
    - - - - - - - - - - - - - - - - -
    - - - - - - - - - -
    - - - - - - - -
    - - - - - - - - - -
    - - - - - - - - -
    - - - - - - - +--- +title: "CapacitorアプリでIonic Vueにログインを追加する" +permalink: "interactive" +'description': "このガイドは、Ionic(Vue)とCapacitrorのアプリケーションにAuth0 Vue SDKを使ってAuth0を統合する方法を説明します。" +'og:title': "CapacitorアプリでIonic Vueにログインを追加する" +'og:description': "このガイドは、Ionic(Vue)とCapacitrorのアプリケーションにAuth0 Vue SDKを使ってAuth0を統合する方法を説明します。" +'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/ionic.jpeg" +'twitter:title': "CapacitorアプリでIonic Vueにログインを追加する" +'twitter:description': "このガイドは、Ionic(Vue)とCapacitrorのアプリケーションにAuth0 Vue SDKを使ってAuth0を統合する方法を説明します。" +sidebarTitle: Ionic & Capacitor (Vue) +--- + +import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; +import { LoggedInForm } from "/snippets/Login.jsx"; +import Main from "/snippets/quickstart/native/ionic-vue/main.ts.mdx"; +import Loginbutton from "/snippets/quickstart/native/ionic-vue/LoginButton.vue.mdx"; +import Logoutbutton from "/snippets/quickstart/native/ionic-vue/LogoutButton.vue.mdx"; +import Userprofile from "/snippets/quickstart/native/ionic-vue/UserProfile.vue.mdx"; + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + +export const sections = [ + { id: "使用を開始する", title: "使用を開始する" }, + { id: "auth0を構成する", title: "Auth0を構成する" }, + { id: "auth0-vue-sdkをインストールする", title: "Auth0 Vue SDKをインストールする" }, + { id: "createauht0プラグインを構成する", title: "CreateAuht0プラグインを構成する" }, + { id: "アプリケーションにログインを追加する", title: "アプリケーションにログインを追加する" }, + { id: "ログインコールバックを処理する", title: "ログインコールバックを処理する" }, + { id: "アプリケーションにログアウトを追加する", title: "アプリケーションにログアウトを追加する" }, + { id: "ユーザープロファイルを表示する", title: "ユーザープロファイルを表示する" } +] + + + + Auth0を使用すると、アプリケーションに手軽に認証を追加して、ユーザープロファイル情報にアクセスすることができます。このガイドは、Ionic(Vue)とCapacitrorのアプリケーションに[Auth0 Vue SDK](https://github.com/auth0/auth0-vue)を使ってAuth0を統合する方法を説明します。 + +
    + このクイックスタートは、[Ionic](https://ionicframework.com/)アプリケーションが[Capacitor](https://capacitorjs.com/)を使ってすでに実行されていることを前提としています。そうでない場合には、[IonicフレームワークでCapacitorを使用する](https://capacitorjs.com/docs/getting-started/with-ionic)ガイドを参照しながら簡単なアプリから始めるか、[サンプルアプリ](https://github.com/auth0-samples/auth0-ionic-samples)を複製してください。 + + また、[Capacitorの開発ワークフロー](https://capacitorjs.com/docs/basics/workflow)を理解しておく必要もあります。 +
    + +
    + Auth0のサービスを利用するには、Auth0 Dashboadに設定済みのアプリケーションがある必要があります。Auth0アプリケーションは、プロジェクトに対してどのように認証が動作して欲しいかを構成する場所です。 + + + 以下の説明では、`YOUR_PACKAGE_ID`を実際のアプリケーションのパッケージIDに置き換えてください。これは、`capacitor.config.ts`ファイルの`appId`フィールドで見つけて構成することができます。詳細については、[Capacitorの構成スキーマ](https://capacitorjs.com/docs/config#schema)を参照してください。 + + + ### アプリケーションを構成する + + 対話型のセレクターを使ってAuth0アプリケーションを新規作成するか、統合したいプロジェクトを表す既存のアプリケーションを選択します。Auth0のすべてのアプリケーションには英数字からなる一意のクライアントIDが割り当てられており、アプリケーションのコードがSDKを通じてAuth0 APIを呼び出す際に使用されます。 + + このクイックスタートを使って構成されたすべての設定は、[Dashboard](https://manage.auth0.com/#/)のアプリケーションを自動更新します。今後、アプリケーションの管理もDashboardで行えます。 + + 代わりに完了済みの構成を見てみたい場合は、サンプルアプリケーションをご覧ください。 + + ### Callback URLを構成する + + Callback URLとは、Auth0がユーザーを認証後にリダイレクトするアプリケーション内URLです。設定されていない場合、ユーザーはログイン後にアプリケーションに戻りません。 + + + サンプルプロジェクトに沿って進めている場合は、`YOUR_PACKAGE_ID://{yourDomain}/capacitor/YOUR_PACKAGE_ID/callback`に設定してください。 + + + ### ログアウトURLを構成する + + ログアウトURLとは、Auth0がユーザーをログアウト後にリダイレクトするアプリケーション内URLです。設定されていない場合、ユーザーはアプリケーションからログアウトできず、エラーを受け取ります。 + + + サンプルプロジェクトに沿って進めている場合は、`YOUR_PACKAGE_ID://{yourDomain}/capacitor/YOUR_PACKAGE_ID/callback`に設定してください。 + + + ### 許可されているオリジンを構成する + + ネイティブアプリケーションからAuth0へ要求を送信できるようにするには、[アプリケーションの設定](https://manage.auth0.com/#/applications/%7ByourClientId%7D/settings)で次の**許可されているオリジン** を設定します。 + + + サンプルプロジェクトに沿って進めている場合、iOSとAndroidでそれぞれ`capacitor://localhost, http://localhost`を設定します。 + + + 最後に、アプリケーションの**[Application Type(アプリケーションタイプ)]** が**[Native(ネイティブ)]** になっていることを[アプリケーションの設定](https://manage.auth0.com/#/applications/%7ByourClientId%7D/settings)で必ず確認してください。 +
    + +
    + プロジェクトディレクトリで次のコマンドを実行して、Auth0 Vue SDKをインストールします: + + `npm install @auth0/auth0-vue` + + SDKはモジュールや認証サービスなど、Auth0をVueアプリケーションに慣用的に統合しやすくする種類をいくつか公開しています。 + + ### Capacitorプラグインをインストールする + + このクイックスタートとサンプルでは、Capacitorの公式プラグインをいくつか使用しています。次のコマンドを使用して、これらをアプリにインストールします: + + npm install @capacitor/browser @capacitor/app + + - [`@capacitor/browser`](https://capacitorjs.com/docs/apis/browser):デバイスのシステムブラウザーと対話できるようになり、Auth0の認可エンドポイントへのURLを開くために使用されます + - [`@capacitor/app`](https://capacitorjs.com/docs/apis/app):高レベルのアプリイベントを受け取れるようになるため、Auth0からのコールバックを扱うのに便利です + + + iOSのCapacitorのBrowserプラグインは[`SFSafariViewController`](https://developer.apple.com/documentation/safariservices/sfsafariviewcontroller)を使用し、iOS 11以降ではデバイス上のSafariとクッキーを共有しません。つまり、これらのデバイスでは[SSO](/docs/ja-jp/sso)が機能しません。SSOが必要な場合には、[ASWebAuthenticationSession](https://developer.apple.com/documentation/authenticationservices/aswebauthenticationsession)を使用する互換性のあるプラグインを使用してください。 + +
    + +
    + SDKは、SDKが機能するために必要なすべてのサービスを含んだコンポーザブル、`createAuth0`をエクスポートします。このコンポーザブルをアプリケーションに登録し、Auth0のドメインとクライアントIDで構成する必要があります。 + + `createAuth0`コンポーザブルは以下の構成を取ります。 + + - `domain`:Auth0 Dashboardで作成したアプリケーションの**[Settings(設定)]** にある`domain`値、またはAuth0の[カスタムドメイン機能](http://localhost:3000/docs/custom-domains)を使用する場合のカスタムドメインです。 + - `clientId`:Auth0 Dashboardで作成したアプリケーションの**[Settings(設定)]** にあるクライアントID値です。 + - `useRefreshTokens`:AndroidまたはiOSでauth0-vueをIonicと使用するには、リフレッシュトークンを有効にする必要があります。 + - `useRefreshTokensFallback`:AndroidまたはiOSでauth0-vueをIonicと使用するには、iframeのフォールバックを無効にする必要があります。 + - `authorizationParams.redirect_uri`:Auth0で認証した後に、ユーザーをリダイレクトするURLです。 + + + アプリケーションの閉開後に認証を継続するには、SDKを構成する際に`cacheLocation`を`localstorage`に設定することをお勧めします。ただし、[localstorageにトークンを保管するリスク](/docs/ja-jp/libraries/auth0-single-page-app-sdk#change-storage-options)を理解してください。また、状況によってはlocalstorageのデータが思いがけず復元される可能性もあるため、Capacitorアプリ内では**一次的** なものとして扱ってください。[Capacitorドキュメントに記載のストレージに関するガイド](https://capacitorjs.com/docs/guides/storage#why-cant-i-just-use-localstorage-or-indexeddb)をお読みください。 + + さらに、より安全で永続的なストレージの仕組みが要件である場合、SDKを使用すると、[カスタムのキャッシュを実装](https://github.com/auth0/auth0-spa-js/blob/master/EXAMPLES.md#creating-a-custom-cache)してトークンを保管することができます。 + + **注意** :[CapacitorのStorageプラグイン](https://capacitorjs.com/docs/apis/storage)は、iOSでは[UserDefaults](https://developer.apple.com/documentation/foundation/userdefaults)、Androidでは[SharedPreferences](https://developer.android.com/reference/android/content/SharedPreferences)によってバックアップされるため、トークンの保管に使用**しない** ことをお勧めします。これらのAPIを使って保管されたデータは暗号化されません。セキュリティで保護されることもなく、クラウドと同期される可能性があります。 + + + + ##### チェックポイント + アプリがAuth0 Vue SDKで構成されました。今度は、アプリケーションを実行して、SDKがエラーなく初期化されること、そして、以前と同じように動作することを確認します。 + +
    + +
    + Capacitorアプリケーションでは、[CapacitorのBrowserプラグイン](https://capacitorjs.com/docs/apis/browser)によって、Auth0の[ユニバーサルログインページ](https://auth0.com/universal-login)にリダイレクトされます。`loginWithRedirect`関数の`openUrl`パラメーターに`Browser.open`の使用を設定し、デバイスのシステムブラウザーコンポーネント(iOSでは[SFSafariViewController](https://developer.apple.com/documentation/safariservices/sfsafariviewcontroller)、Androidでは[Chrome Custom Tabs](https://developer.chrome.com/docs/android/custom-tabs))でURLが開くようにします。 + + + SDKの`loginWithRedirect`メソッドは、デフォルトで`window.location.href`を使用して、ユーザーのデバイスにあるデフォルトのブラウザーアプリケーションでログインページを開きます。プラットフォームに適切なシステムブラウザーコンポーネントは使用しません。ユーザーが認証でアプリケーションを離れるため、ユーザーエクスペリエンスとしては最適ではありません。 + + + + ##### チェックポイント + loginWithRedirect関数は、SDKにログインフローを開始するように指示します。openUrlパラメーターを設定して、Browser.open関数を呼び出し、プラットフォームのシステムブラウザーコンポーネントでログインURLを開きます。これは、ユーザーがアプリケーションにログインする方法を提供します。ユーザーはAuth0のログインページにリダイレクトされ、エラーは一切受け取りません。 + +
    + +
    + ユーザーがユニバーサルログインページでログインすると、カスタムURLスキームを使ったURLでアプリにリダイレクトされます。`appUrlOpen`イベントがアプリ内で処理されなければなりません。Auth0 SDKの`handleRedirectCallback`メソッドを呼び出すと、認証状態を初期化することができます。 + + このメソッドは、Auth0からのリダイレクトでのみ使用することができます。正常に機能していることを確認するには、URL内の`code`と`state`パラメーターを確認します。 + + このイベントが発生した際に、`Browser.close()`メソッドがブラウザーを閉じるようにします。 + + + 以下の説明では、カスタムURLスキームを使用して、アプリケーション内でコールバックを処理することを前提にしています。このためには、`YOUR_PACKAGE_ID`を選択したプラットフォームのURLスキームで置き換えて登録します。詳細については、iOSには「[カスタムURLスキームを定義する](https://developer.apple.com/documentation/xcode/defining-a-custom-url-scheme-for-your-app)」、Androidには「[アプリコンテンツ用のディープリンクを作成する](https://developer.android.com/training/app-links/deep-linking)」をお読みください。 + + + + ##### チェックポイント + アプリケーションのAppコンポーネントセットアップにappUrlOpenを追加して、ログインします。ユーザーが認証して、アプリにログインすると、ブラウザーのウィンドウが閉じます。 + +
    + +
    + ユーザーがログインできるようになりました。今度は、[ログアウトする方法](/docs/ja-jp/logout/guides/logout-auth0)を構成する必要があります。ユーザーをAuth0のログアウトエンドポイントにリダイレクトし、ブラウザー内のセッションをクリアする必要があります。他の場合と同様に、ユーザーがアプリから離れることでユーザーエクスペリエンスが損なわれないように、CapacitorのBrowserプラグインがリダイレクトを処理するようにします。 + + Auth0 SDKを使用してIonicとCapacitorで実現するには、以下を行います。 + + - アプリについて、ログアウト後にAuth0のリダイレクト先となるURLを構築します。これは、登録済みのカスタムスキームとAuth0ドメインを使ったURLです。これを、Auth0 Dashboardの**[Allowed Logout URLs(許可されているログアウトURL)]** の構成に追加します。 + - `logout`を呼び出し、`logoutParams.returnTo`パラメーターにリダイレクト先のURLを渡して、SDKからログアウトします。 + - CapacitorのBrowserプラグインを使用して`Browser.open`でURLを開くコールバックに、`openUrl`パラメーターを設定します。 + + + ログインの手順と同様に、`logout`を呼び出す際に`openUrl`を設定しないと、SDKがユーザーをログアウトURLにリダイレクトするのに、デバイスのデフォルトのブラウザーアプリケーションが使用されるため、ユーザーエクスペリエンスとしては最適ではありません。 + + + + ##### チェックポイント + ユーザーがアプリケーションからログアウトする方法を提供します。Auth0にリダイレクトしてから、returnToパラメーターで指定したアドレスへ移動することを確認します。アプリケーションにログインしていないことを確認します。 + +
    + +
    + Auth0 Vue SDKは必要な任意のコンポーネントについて、名前やプロフィール写真など、ログイン済みのユーザーに関連付けられた[ユーザープロファイル](/docs/ja-jp/users/concepts/overview-user-profile)を取得し、ユーザーインターフェイスをパーソナライズします。プロファイル情報は、`useAuth0()`コンポーザブルが公開する`user`プロパティを介して使用することができます。 + + SDKの初期化は非同期に行われます。`isLoading`と`user`プロパティを確認して、ユーザープロファイルを保護する必要があります。`isLoading`が`false`になり、`user`が値を持つと、ユーザープロファイルを利用することができます。 + + + ##### チェックポイント + ユーザーがアプリ内でユーザープロファイルの詳細を表示できる手段を提供し、ログインした後に自分のプロファイル情報を取得して画面に表示できることを確認します。 + +
    + + ## 次のステップ + + 成功です!ここまで来れば、アプリケーションにログイン、ログアウト、ユーザープロファイル情報が備わっているはずです。 + + これでクイックスタートチュートリアルは終了ですが、機能はまだまだたくさんあります。Auth0でできることについて詳しくは、以下をご覧ください。 + + * [Auth0 Dashboard](https://manage.auth0.com/#) - Auth0のテナントやアプリケーションを構成して管理する方法について説明します + * [Auth0 Marketplace](https://marketplace.auth0.com/) - Auth0の機能性を拡張できる各種の統合を見つけられます +
    + + + + + + + + + + + + + + + + +
    + + + + + + + + + +
    + + + + + + + +
    + + + + + + + + + +
    + + + + + + + + +
    + + + + + + + diff --git a/main/docs/ja-jp/quickstart/native/ios-swift/interactive.mdx b/main/docs/ja-jp/quickstart/native/ios-swift/interactive.mdx index 1d49d1fcd..7efefe365 100644 --- a/main/docs/ja-jp/quickstart/native/ios-swift/interactive.mdx +++ b/main/docs/ja-jp/quickstart/native/ios-swift/interactive.mdx @@ -1,285 +1,287 @@ ---- -title: "iOSまたはmacOSアプリケーションにログインを追加する" -permalink: "interactive" -'description': "このガイドは、iOSやmacOSアプリにAuth0.swift SDKを使ってAuth0を統合する方法を説明します。" -'og:title': "iOSまたはmacOSアプリケーションにログインを追加する" -'og:description': "このガイドは、iOSやmacOSアプリにAuth0.swift SDKを使ってAuth0を統合する方法を説明します。" -'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/ios.png" -'twitter:title': "iOSまたはmacOSアプリケーションにログインを追加する" -'twitter:description': "このガイドは、iOSやmacOSアプリにAuth0.swift SDKを使ってAuth0を統合する方法を説明します。" -sidebarTitle: iOS / macOS ---- - -import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; -import { LoggedInForm } from "/snippets/Login.jsx"; -import Auth0 from "/snippets/quickstart/native/ios-swift/Auth0.plist.mdx"; -import Mainview from "/snippets/quickstart/native/ios-swift/MainView.swift.mdx"; -import Mainview2 from "/snippets/quickstart/native/ios-swift/MainView.swift2.mdx"; -import Profileview from "/snippets/quickstart/native/ios-swift/ProfileView.swift.mdx"; -import User from "/snippets/quickstart/native/ios-swift/User.swift.mdx"; - -export const sections = [ - { id: "auth0を構成する", title: "Auth0を構成する" }, - { id: "sdkをインストールする", title: "SDKをインストールする" }, - { id: "sdkを構成する", title: "SDKを構成する" }, - { id: "アプリケーションにログインを追加する", title: "アプリケーションにログインを追加する" }, - { id: "アプリケーションにログアウトを追加する", title: "アプリケーションにログアウトを追加する" }, - { id: "ユーザープロファイル情報にアクセスする", title: "ユーザープロファイル情報にアクセスする" } -] - - - - このガイドは、[Auth0.swift](https://github.com/auth0/Auth0.swift) SDKを使って、iOSやmacOSアプリで認証の追加とユーザプロファイル情報へのにアクセスを行う方法について説明します。 - - このクイックスタートを使用するには、以下の手順に従います: - - - Auth0の無料アカウントにサインアップするか、Auth0にログインします。 - - 統合したいiOSまたはmacOSのアプリを準備します。または、ログインした後に、サンプルアプリを表示してダウンロードすることもできます。 - -
    - Auth0のサービスを利用するには、Auth0 Dashboadに設定済みのアプリケーションが必要です。Auth0アプリケーションは、開発中のアプリに対してどのように認証が動作して欲しいかを構成する場所です。 - - ### Auth0アプリケーションを構成する - - 対話型のセレクターを使ってAuth0アプリケーションを新規作成するか、既存の**ネイティブ** のAuth0アプリケーションを選択します。Auth0のすべてのアプリケーションには英数字からなる一意のクライアントIDが割り当てられており、アプリがSDKを通じてAuth0 APIを呼び出す際に使用されます。 - - このクイックスタートを使って構成されたすべての設定は、[Dashboard](https://manage.auth0.com/#/)のAuth0アプリケーションを自動更新します。今後、アプリケーションの管理もDashboardで行えます。 - - 完了済みの構成を見てみたい場合は、サンプルアプリをご覧ください。 - - ### Callback URLとログアウトURLを構成する - - Auth0はリダイレクトでユーザーをアプリに戻すため、Callback URLとログアウトURLを呼び出します。Auth0は、ユーザーを認証した後にCallback URLを呼び出し、セッションのクッキーを削除した後にログアウトURLを呼び出します。Callback URLとログインURLを設定しないと、ユーザーはアプリにログインやログアウトが行えなくなり、アプリにエラーが発生します。 - - - iOS 17.4以降とmacOS 14.4以降では、ユニバーサルリンクをCallback URLおよびログアウトURLとして使用できます。有効になっている場合、古いバージョンのiOS/macOSでは、Auth0.swiftはフォールバックとしてカスタムURLスキームを使用します。 - - **この機能にはXcode 15.3以降と有料のApple Developerアカウントが必要です。** - - - アプリのプラットフォームに応じて、以下の**Callback URL** と**ログアウトURL** を追加してください。カスタムドメインがある場合は、Auth0テナントのドメインに代わってそちらを使用します。 - - #### iOS - - ``` - https://{yourDomain}/ios/YOUR_BUNDLE_IDENTIFIER/callback, - YOUR_BUNDLE_IDENTIFIER://{yourDomain}/ios/YOUR_BUNDLE_IDENTIFIER/callback - ``` - - #### macOS - - ``` - https://{yourDomain}/macos/YOUR_BUNDLE_IDENTIFIER/callback, - YOUR_BUNDLE_IDENTIFIER://{yourDomain}/macos/YOUR_BUNDLE_IDENTIFIER/callback - ``` - - たとえば、iOSのバンドル識別子が`com.example.MyApp`でAuth0ドメインが`example.us.auth0.com`の場合には、次の値になります: - - ``` - https://example.us.auth0.com/ios/com.example.MyApp/callback, - com.example.MyApp://example.us.auth0.com/ios/com.example.MyApp/callback - ``` - - ### 関連ドメインを構成する - - - この手順では有料のApple Developerアカウントが必要になります。Callback URLおよびログアウトURLとしてユニバーサルリンクを使用する必要があります。代わりにカスタムURLスキームを使用する場合はこの手順をスキップしてください。 - - - #### チームIDとバンドル識別子を構成する - - Auth0アプリケーションの[設定ページ](https://manage.auth0.com/dashboard/us/#/applications/)に移動して最後までスクロールし、 **[Advanced Settings(詳細設定)]>[Device Settings(デバイス設定)]** を開きます。**[iOS]** セクションで**[Team ID(チームID)]** に[Apple Team ID](https://developer.apple.com/help/account/manage-your-team/locate-your-team-id/)を、**[App ID(アプリID)]** にアプリのバンドルIDを設定します。 - - ![Auth0 Dashboard> [Applications(アプリケーション)] > [Applications(アプリケーション)] > [Native App(ネイティブアプリ)] > [Settings(設定)]タブ > [Advanced Settings(詳細設定)] > [Device Settings(デバイス設定)]タブ](/docs/images/ja-jp/cdy7uua7fh8z/62v9bB3bUVMw9XLND5lcMI/1b20d248b400f75e1bf1174a7d0d0ba0/IOS_Settings_-_Japanese.png) - - これで、アプリがAuth0テナントの`apple-app-site-association`ファイルに追加されます。 - - #### 関連ドメインの機能を追加する - - Xcodeで、アプリのターゲット設定の**[Signing & Capabilities(署名と機能)]** [タブ](https://developer.apple.com/documentation/xcode/adding-capabilities-to-your-app#Add-a-capability)に移動し、**[+ Capability(+機能)]** ボタンを押します。それから**[Associated Domains(関連ドメイン)]** を選択します。 - - ![[Xcode]> [Signing & Capabilities(署名と機能)]タブ > [Add New(新規追加)] > [Associated Domains(関連ドメイン)]](/docs/images/ja-jp/cdy7uua7fh8z/72eVE104zKB5Q4NPnx6MCa/66c81ee64f104583bd00b9916778f989/ios-xcode-capabilities.png) - - 次に、以下の [エントリー](https://developer.apple.com/documentation/xcode/configuring-an-associated-domain#Define-a-service-and-its-associated-domain)を**[Associated Domains(関連ドメイン)]** の下に追加します: - - ``` - webcredentials:labs-fundtraining.us.auth0.com - ``` - - カスタムドメインがある場合は、Auth0テナントのドメインではなくそちらを使用してください。 - - - 関連ドメインが動作するためには、**iOSシミュレーター用に構築されている場合でも** 、アプリが自分のチーム証明書で署名されている必要があります。Apple Teamには必ず、Auth0アプリケーションの設定ページで構成されたチームIDのものを使用してください。 - -
    - -
    - ### Swift Package Managerを使用する - - Xcodeで以下のメニュー項目を開きます: - - **[File(ファイル)] > [Add Package Dependencies...(パッケージの依存関係を追加する...)]** - - **[Search or Enter Package URL(パッケージURLを検索または入力)]** 検索ボックスに次のURLを入力します: - - ``` - https://github.com/auth0/Auth0.swift - ``` - - それから依存ルールを選択して**[Add Package(パッケージを追加)]** を押します。 - - - SPMの詳細については、[公式ドキュメント](https://developer.apple.com/documentation/xcode/adding-package-dependencies-to-your-app)を確認してください。 - - - ### CocoaPodsを使用する - - 以下のラインを`Podfile`に追加します: - - ``` - pod 'Auth0', '~> 2.0' - ``` - - それから`pod install`を実行します。 - - - CocoaPodsの詳細は、[公式ドキュメント](https://guides.cocoapods.org/using/getting-started.html)を確認してください。 - - - ### Carthageを使用する - - 以下のラインを`Cartfile`に追加します: - - ``` - github "auth0/Auth0.swift" ~> 2.0 - ``` - - それから`carthage bootstrap --use-xcframeworks`を実行します。 - - - Carthageの詳細については、[公式ドキュメント](https://github.com/Carthage/Carthage#getting-started)を確認してください。 - -
    - -
    - Auth0.swiftのSDKにはAuth0**domain** と**Client ID** が必要です。これらの値はAuth0アプリケーションの[設定ページ](https://manage.auth0.com/dashboard/us/#/applications/)で確認できます - - - **domain** :Auth0テナントのドメインです。カスタムドメインがある場合は、Auth0テナントのドメインではなくそちらを使用してください。 - - **クライアントID** :このクイックスタートで前にセットアップした、Auth0アプリケーションの英数字からなる一意のIDです。 - - Auth0ドメインとクライアントIDの値を含むアプリバンドルに`Auth0.plist`という名前の`plist`ファイルを作成します。 - - - SDKはプログラムコードによって構成することも可能です。詳細は[README](https://github.com/auth0/Auth0.swift#configure-client-id-and-domain-programmatically)をご覧ください。 - - - - ##### チェックポイント - Auth0.swift SDKの構成を完了しました。アプリを実行して、SDKに関連したエラーを出していないことを確認します。 - -
    - -
    - ログインページを提示したいファイルに`Auth0`モジュールをインポートします。それから**ログイン** ボタンのアクションでユニバーサルログインページを提示します。 - - - コールバックに基づいたAPIの代わりにasync/awaitまたはCombineを使用できます。詳細は[README](https://github.com/auth0/Auth0.swift#web-auth-login-ios--macos)をご覧ください。 - - - ![iOSアプリのユニバーサルログイン画面の例](/docs/images/ja-jp/cdy7uua7fh8z/3ZRDXpjlUXEcQpXq6Q00L1/4b6b596983b5f7d257975a5efcc1cafa/login-ios_japanese.png) - - - ##### チェックポイント - ログインボタンを押して次の点を確認します: - アラートボックスが表示され、同意を求める。 - [Continue(続行)]を選択するとSafariモーダルでユニバーサルログインページが開く。 - ユーザー名とパスワード、またはソーシャルプロバイダーを使って、ログインまたはサインアップできる。 - その後、Safariモーダルが自動的に閉じる。 - -
    - -
    - アプリにログインできるようになったら、[ログアウト](/docs/ja-jp/authenticate/login/logout)する方法が必要です。**ログアウト** ボタンのアクションで`clearSession()`メソッドを呼び出し、ユニバーサルログインセッションのクッキーを消去します。 - - - ##### チェックポイント - ログアウトボタンを押して次の点を確認します: - アラートボックスが表示され、同意を求める。 - [Continue(続行)]を選択するとSafariモーダルでページが開く。 - その直後にSafariモーダルが自動的に閉じる。 - -
    - -
    - ログイン後に得る`Credentials`インスタンスにはIDトークンが含まれます。IDトークンは、ログインしたユーザーに関連するプロファイル情報(メールアドレスやプロフィール写真など)を含みます。これらの詳細情報はアプリのユーザーインターフェイスをパーソナライズするために使用できます。 - - Auth0.swiftのSDKには、IDトークンのような[JWT](https://jwt.io/)をデコードするための[ユーティリティ](https://github.com/auth0/JWTDecode.swift)が含まれています。ユーザープロファイル情報にアクセスしたいファイルへ`JWTDecode`モジュールをインポートすることで開始します。それから、`decode(jwt:)`メソッドを使ってIDトークンをデコードし、そこに含まれるクレームにアクセスします。 - - - 最新のユーザー情報は`userInfo(withAccessToken:)`メソッドで取得できます。詳細は[EXAMPLES](https://github.com/auth0/Auth0.swift/blob/master/EXAMPLES.md#retrieve-user-information)をご覧ください。 - - - - ##### チェックポイント - ログイン後にemail、picture、その他すべてのクレームにアクセスできることを確認します。 - -
    - - ## 次のステップ - - 成功です!ここまで来れば、アプリケーションにログイン、ログアウト、ユーザープロファイル情報が備わっているはずです。 - - これでクイックスタートチュートリアルは終了ですが、機能はまだまだたくさんあります。Auth0でできることについて詳しくは、以下をご覧ください。 - - * [Auth0 Dashboard](https://manage.auth0.com/#) - Auth0のテナントやアプリケーションを構成して管理する方法について説明します - * [Auth0.swift SDK](https://github.com/auth0/Auth0.swift) - このチュートリアルで使用されているSDKをより詳しく説明します - * [Auth0 Marketplace](https://marketplace.auth0.com/) - Auth0の機能性を拡張できる各種の統合を見つけられます -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    +--- +title: "iOSまたはmacOSアプリケーションにログインを追加する" +permalink: "interactive" +'description': "このガイドは、iOSやmacOSアプリにAuth0.swift SDKを使ってAuth0を統合する方法を説明します。" +'og:title': "iOSまたはmacOSアプリケーションにログインを追加する" +'og:description': "このガイドは、iOSやmacOSアプリにAuth0.swift SDKを使ってAuth0を統合する方法を説明します。" +'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/ios.png" +'twitter:title': "iOSまたはmacOSアプリケーションにログインを追加する" +'twitter:description': "このガイドは、iOSやmacOSアプリにAuth0.swift SDKを使ってAuth0を統合する方法を説明します。" +sidebarTitle: iOS / macOS +--- + +import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; +import { LoggedInForm } from "/snippets/Login.jsx"; +import Auth0 from "/snippets/quickstart/native/ios-swift/Auth0.plist.mdx"; +import Mainview from "/snippets/quickstart/native/ios-swift/MainView.swift.mdx"; +import Mainview2 from "/snippets/quickstart/native/ios-swift/MainView.swift2.mdx"; +import Profileview from "/snippets/quickstart/native/ios-swift/ProfileView.swift.mdx"; +import User from "/snippets/quickstart/native/ios-swift/User.swift.mdx"; + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + +export const sections = [ + { id: "auth0を構成する", title: "Auth0を構成する" }, + { id: "sdkをインストールする", title: "SDKをインストールする" }, + { id: "sdkを構成する", title: "SDKを構成する" }, + { id: "アプリケーションにログインを追加する", title: "アプリケーションにログインを追加する" }, + { id: "アプリケーションにログアウトを追加する", title: "アプリケーションにログアウトを追加する" }, + { id: "ユーザープロファイル情報にアクセスする", title: "ユーザープロファイル情報にアクセスする" } +] + + + + このガイドは、[Auth0.swift](https://github.com/auth0/Auth0.swift) SDKを使って、iOSやmacOSアプリで認証の追加とユーザプロファイル情報へのにアクセスを行う方法について説明します。 + + このクイックスタートを使用するには、以下の手順に従います: + + - Auth0の無料アカウントにサインアップするか、Auth0にログインします。 + - 統合したいiOSまたはmacOSのアプリを準備します。または、ログインした後に、サンプルアプリを表示してダウンロードすることもできます。 + +
    + Auth0のサービスを利用するには、Auth0 Dashboadに設定済みのアプリケーションが必要です。Auth0アプリケーションは、開発中のアプリに対してどのように認証が動作して欲しいかを構成する場所です。 + + ### Auth0アプリケーションを構成する + + 対話型のセレクターを使ってAuth0アプリケーションを新規作成するか、既存の**ネイティブ** のAuth0アプリケーションを選択します。Auth0のすべてのアプリケーションには英数字からなる一意のクライアントIDが割り当てられており、アプリがSDKを通じてAuth0 APIを呼び出す際に使用されます。 + + このクイックスタートを使って構成されたすべての設定は、[Dashboard](https://manage.auth0.com/#/)のAuth0アプリケーションを自動更新します。今後、アプリケーションの管理もDashboardで行えます。 + + 完了済みの構成を見てみたい場合は、サンプルアプリをご覧ください。 + + ### Callback URLとログアウトURLを構成する + + Auth0はリダイレクトでユーザーをアプリに戻すため、Callback URLとログアウトURLを呼び出します。Auth0は、ユーザーを認証した後にCallback URLを呼び出し、セッションのクッキーを削除した後にログアウトURLを呼び出します。Callback URLとログインURLを設定しないと、ユーザーはアプリにログインやログアウトが行えなくなり、アプリにエラーが発生します。 + + + iOS 17.4以降とmacOS 14.4以降では、ユニバーサルリンクをCallback URLおよびログアウトURLとして使用できます。有効になっている場合、古いバージョンのiOS/macOSでは、Auth0.swiftはフォールバックとしてカスタムURLスキームを使用します。 + + **この機能にはXcode 15.3以降と有料のApple Developerアカウントが必要です。** + + + アプリのプラットフォームに応じて、以下の**Callback URL** と**ログアウトURL** を追加してください。カスタムドメインがある場合は、Auth0テナントのドメインに代わってそちらを使用します。 + + #### iOS + + ``` + https://{yourDomain}/ios/YOUR_BUNDLE_IDENTIFIER/callback, + YOUR_BUNDLE_IDENTIFIER://{yourDomain}/ios/YOUR_BUNDLE_IDENTIFIER/callback + ``` + + #### macOS + + ``` + https://{yourDomain}/macos/YOUR_BUNDLE_IDENTIFIER/callback, + YOUR_BUNDLE_IDENTIFIER://{yourDomain}/macos/YOUR_BUNDLE_IDENTIFIER/callback + ``` + + たとえば、iOSのバンドル識別子が`com.example.MyApp`でAuth0ドメインが`example.us.auth0.com`の場合には、次の値になります: + + ``` + https://example.us.auth0.com/ios/com.example.MyApp/callback, + com.example.MyApp://example.us.auth0.com/ios/com.example.MyApp/callback + ``` + + ### 関連ドメインを構成する + + + この手順では有料のApple Developerアカウントが必要になります。Callback URLおよびログアウトURLとしてユニバーサルリンクを使用する必要があります。代わりにカスタムURLスキームを使用する場合はこの手順をスキップしてください。 + + + #### チームIDとバンドル識別子を構成する + + Auth0アプリケーションの[設定ページ](https://manage.auth0.com/dashboard/us/#/applications/)に移動して最後までスクロールし、 **[Advanced Settings(詳細設定)]>[Device Settings(デバイス設定)]** を開きます。**[iOS]** セクションで**[Team ID(チームID)]** に[Apple Team ID](https://developer.apple.com/help/account/manage-your-team/locate-your-team-id/)を、**[App ID(アプリID)]** にアプリのバンドルIDを設定します。 + + ![Auth0 Dashboard> [Applications(アプリケーション)] > [Applications(アプリケーション)] > [Native App(ネイティブアプリ)] > [Settings(設定)]タブ > [Advanced Settings(詳細設定)] > [Device Settings(デバイス設定)]タブ](/docs/images/ja-jp/cdy7uua7fh8z/62v9bB3bUVMw9XLND5lcMI/1b20d248b400f75e1bf1174a7d0d0ba0/IOS_Settings_-_Japanese.png) + + これで、アプリがAuth0テナントの`apple-app-site-association`ファイルに追加されます。 + + #### 関連ドメインの機能を追加する + + Xcodeで、アプリのターゲット設定の**[Signing & Capabilities(署名と機能)]** [タブ](https://developer.apple.com/documentation/xcode/adding-capabilities-to-your-app#Add-a-capability)に移動し、**[+ Capability(+機能)]** ボタンを押します。それから**[Associated Domains(関連ドメイン)]** を選択します。 + + ![[Xcode]> [Signing & Capabilities(署名と機能)]タブ > [Add New(新規追加)] > [Associated Domains(関連ドメイン)]](/docs/images/ja-jp/cdy7uua7fh8z/72eVE104zKB5Q4NPnx6MCa/66c81ee64f104583bd00b9916778f989/ios-xcode-capabilities.png) + + 次に、以下の [エントリー](https://developer.apple.com/documentation/xcode/configuring-an-associated-domain#Define-a-service-and-its-associated-domain)を**[Associated Domains(関連ドメイン)]** の下に追加します: + + ``` + webcredentials:labs-fundtraining.us.auth0.com + ``` + + カスタムドメインがある場合は、Auth0テナントのドメインではなくそちらを使用してください。 + + + 関連ドメインが動作するためには、**iOSシミュレーター用に構築されている場合でも** 、アプリが自分のチーム証明書で署名されている必要があります。Apple Teamには必ず、Auth0アプリケーションの設定ページで構成されたチームIDのものを使用してください。 + +
    + +
    + ### Swift Package Managerを使用する + + Xcodeで以下のメニュー項目を開きます: + + **[File(ファイル)] > [Add Package Dependencies...(パッケージの依存関係を追加する...)]** + + **[Search or Enter Package URL(パッケージURLを検索または入力)]** 検索ボックスに次のURLを入力します: + + ``` + https://github.com/auth0/Auth0.swift + ``` + + それから依存ルールを選択して**[Add Package(パッケージを追加)]** を押します。 + + + SPMの詳細については、[公式ドキュメント](https://developer.apple.com/documentation/xcode/adding-package-dependencies-to-your-app)を確認してください。 + + + ### CocoaPodsを使用する + + 以下のラインを`Podfile`に追加します: + + ``` + pod 'Auth0', '~> 2.0' + ``` + + それから`pod install`を実行します。 + + + CocoaPodsの詳細は、[公式ドキュメント](https://guides.cocoapods.org/using/getting-started.html)を確認してください。 + + + ### Carthageを使用する + + 以下のラインを`Cartfile`に追加します: + + ``` + github "auth0/Auth0.swift" ~> 2.0 + ``` + + それから`carthage bootstrap --use-xcframeworks`を実行します。 + + + Carthageの詳細については、[公式ドキュメント](https://github.com/Carthage/Carthage#getting-started)を確認してください。 + +
    + +
    + Auth0.swiftのSDKにはAuth0**domain** と**Client ID** が必要です。これらの値はAuth0アプリケーションの[設定ページ](https://manage.auth0.com/dashboard/us/#/applications/)で確認できます + + - **domain** :Auth0テナントのドメインです。カスタムドメインがある場合は、Auth0テナントのドメインではなくそちらを使用してください。 + - **クライアントID** :このクイックスタートで前にセットアップした、Auth0アプリケーションの英数字からなる一意のIDです。 + + Auth0ドメインとクライアントIDの値を含むアプリバンドルに`Auth0.plist`という名前の`plist`ファイルを作成します。 + + + SDKはプログラムコードによって構成することも可能です。詳細は[README](https://github.com/auth0/Auth0.swift#configure-client-id-and-domain-programmatically)をご覧ください。 + + + + ##### チェックポイント + Auth0.swift SDKの構成を完了しました。アプリを実行して、SDKに関連したエラーを出していないことを確認します。 + +
    + +
    + ログインページを提示したいファイルに`Auth0`モジュールをインポートします。それから**ログイン** ボタンのアクションでユニバーサルログインページを提示します。 + + + コールバックに基づいたAPIの代わりにasync/awaitまたはCombineを使用できます。詳細は[README](https://github.com/auth0/Auth0.swift#web-auth-login-ios--macos)をご覧ください。 + + + ![iOSアプリのユニバーサルログイン画面の例](/docs/images/ja-jp/cdy7uua7fh8z/3ZRDXpjlUXEcQpXq6Q00L1/4b6b596983b5f7d257975a5efcc1cafa/login-ios_japanese.png) + + + ##### チェックポイント + ログインボタンを押して次の点を確認します: + アラートボックスが表示され、同意を求める。 + [Continue(続行)]を選択するとSafariモーダルでユニバーサルログインページが開く。 + ユーザー名とパスワード、またはソーシャルプロバイダーを使って、ログインまたはサインアップできる。 + その後、Safariモーダルが自動的に閉じる。 + +
    + +
    + アプリにログインできるようになったら、[ログアウト](/docs/ja-jp/authenticate/login/logout)する方法が必要です。**ログアウト** ボタンのアクションで`clearSession()`メソッドを呼び出し、ユニバーサルログインセッションのクッキーを消去します。 + + + ##### チェックポイント + ログアウトボタンを押して次の点を確認します: + アラートボックスが表示され、同意を求める。 + [Continue(続行)]を選択するとSafariモーダルでページが開く。 + その直後にSafariモーダルが自動的に閉じる。 + +
    + +
    + ログイン後に得る`Credentials`インスタンスにはIDトークンが含まれます。IDトークンは、ログインしたユーザーに関連するプロファイル情報(メールアドレスやプロフィール写真など)を含みます。これらの詳細情報はアプリのユーザーインターフェイスをパーソナライズするために使用できます。 + + Auth0.swiftのSDKには、IDトークンのような[JWT](https://jwt.io/)をデコードするための[ユーティリティ](https://github.com/auth0/JWTDecode.swift)が含まれています。ユーザープロファイル情報にアクセスしたいファイルへ`JWTDecode`モジュールをインポートすることで開始します。それから、`decode(jwt:)`メソッドを使ってIDトークンをデコードし、そこに含まれるクレームにアクセスします。 + + + 最新のユーザー情報は`userInfo(withAccessToken:)`メソッドで取得できます。詳細は[EXAMPLES](https://github.com/auth0/Auth0.swift/blob/master/EXAMPLES.md#retrieve-user-information)をご覧ください。 + + + + ##### チェックポイント + ログイン後にemail、picture、その他すべてのクレームにアクセスできることを確認します。 + +
    + + ## 次のステップ + + 成功です!ここまで来れば、アプリケーションにログイン、ログアウト、ユーザープロファイル情報が備わっているはずです。 + + これでクイックスタートチュートリアルは終了ですが、機能はまだまだたくさんあります。Auth0でできることについて詳しくは、以下をご覧ください。 + + * [Auth0 Dashboard](https://manage.auth0.com/#) - Auth0のテナントやアプリケーションを構成して管理する方法について説明します + * [Auth0.swift SDK](https://github.com/auth0/Auth0.swift) - このチュートリアルで使用されているSDKをより詳しく説明します + * [Auth0 Marketplace](https://marketplace.auth0.com/) - Auth0の機能性を拡張できる各種の統合を見つけられます +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    diff --git a/main/docs/ja-jp/quickstart/native/net-android-ios/interactive.mdx b/main/docs/ja-jp/quickstart/native/net-android-ios/interactive.mdx index 3b7e0885e..447e3251b 100644 --- a/main/docs/ja-jp/quickstart/native/net-android-ios/interactive.mdx +++ b/main/docs/ja-jp/quickstart/native/net-android-ios/interactive.mdx @@ -1,271 +1,273 @@ ---- -title: ".NET AndroidまたはiOSアプリケーションにログインを追加する" -permalink: "interactive" -'description': "このチュートリアルは、Auth0を使用して、.NET AndroidまたはiOSアプリケーションにユーザーログインを追加する方法について説明します。" -'og:title': ".NET AndroidまたはiOSアプリケーションにログインを追加する" -'og:description': "このチュートリアルは、Auth0を使用して、.NET AndroidまたはiOSアプリケーションにユーザーログインを追加する方法について説明します。" -'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/xamarin.png" -'twitter:title': ".NET AndroidまたはiOSアプリケーションにログインを追加する" -'twitter:description': "このチュートリアルは、Auth0を使用して、.NET AndroidまたはiOSアプリケーションにユーザーログインを追加する方法について説明します。" -sidebarTitle: .NET Android and iOS ---- - -import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; -import { LoggedInForm } from "/snippets/Login.jsx"; -import Mainactivity from "/snippets/quickstart/native/net-android-ios/MainActivity.cs.mdx"; -import Appdelegate from "/snippets/quickstart/native/net-android-ios/AppDelegate.cs.mdx"; -import Myviewcontroller from "/snippets/quickstart/native/net-android-ios/MyViewController.cs.mdx"; - -export const sections = [ - { id: "auth0を構成する", title: "Auth0を構成する" }, - { id: "auth0-sdkをインストールする", title: "Auth0 SDKをインストールする" }, - { id: "auth0clientをインスタンス化する", title: "Auth0Clientをインスタンス化する" }, - { id: "androidを構成する", title: "Androidを構成する" }, - { id: "iosを構成する", title: "iOSを構成する" }, - { id: "アプリケーションにログインを追加する", title: "アプリケーションにログインを追加する" }, - { id: "アプリケーションにログアウトを追加する", title: "アプリケーションにログアウトを追加する" }, - { id: "ユーザープロファイル情報を表示する", title: "ユーザープロファイル情報を表示する" } -] - - - - Auth0を使用すると、アプリケーションに手軽に認証を追加することができます。このガイドは、.NET AndroidまたはiOSアプリケーションに[Android](https://www.nuget.org/packages/Auth0.OidcClient.AndroidX/)や[iOS](https://www.nuget.org/packages/Auth0.OidcClient.iOS)用のAuth0 SDKを使ってAuth0を統合し、認証の追加とユーザープロファイル情報の表示を行う方法について説明します。 - - - このクイックスタートは、`Xamarin.Android`と`Xamarin.iOS`の次世代である.NET AndroidとiOSについて説明します。現在、`Xamarin.Android`や`Xamarin.iOS`を使用している場合は、統合が同一でSDKにも互換性があるため、このガイドに従ってください。 - - - このクイックスタートを使用するには、以下の手順に従います: - - - Auth0の無料アカウントにサインアップするか、Auth0にログインします。 - - 統合したいAndroidまたはiOSのプロジェクトで、.NET 6以降を使用したものを用意します。または、ログインした後に、サンプルアプリケーションを表示してダウンロードすることもできます。 - -
    - Auth0のサービスを利用するには、Auth0 Dashboadに設定済みのアプリケーションがある必要があります。Auth0アプリケーションは、プロジェクトに対してどのように認証が動作して欲しいかを構成する場所です。 - - ### アプリケーションを構成する - - 対話型のセレクターを使って「ネイティブアプリケーション」を新規作成するか、統合したいプロジェクトを表す既存のアプリケーションを選択します。Auth0のすべてのアプリケーションには英数字からなる一意のクライアントIDが割り当てられており、アプリケーションのコードがSDKを通じてAuth0 APIを呼び出す際に使用されます。 - - このクイックスタートを使って構成されたすべての設定は、[Dashboard](https://manage.auth0.com/#/)のアプリケーションを自動更新します。今後、アプリケーションの管理もDashboardで行えます。 - - 完了済みの構成を見てみたい場合は、サンプルアプリケーションをご覧ください。 - - ### Callback URLを構成する - - Callback URLとは、Auth0がユーザーを認証後にリダイレクトするアプリケーション内URLです。設定されていない場合、ユーザーはログイン後にアプリケーションに戻りません。 - - - サンプルプロジェクトに沿って進めている場合は、プラットフォームに応じて、これを次のURLの1つに設定します: - - - **Android** :`YOUR_PACKAGE_NAME://{yourDomain}/android/YOUR_PACKAGE_NAME/callback` - - **iOS** :`YOUR_BUNDLE_ID://{yourDomain}/ios/YOUR_BUNDLE_ID/callback` - - - ### ログアウトURLを構成する - - ログアウトURLとは、Auth0がユーザーをログアウト後にリダイレクトするアプリケーション内URLです。設定されていない場合、ユーザーはアプリケーションからログアウトできず、エラーを受け取ります。 - - - サンプルプロジェクトに沿って進めている場合は、プラットフォームに応じて、これを次のURLの1つに設定します: - - - **Android** :`YOUR_PACKAGE_NAME://{yourDomain}/android/YOUR_PACKAGE_NAME/callback` - - **iOS** :`YOUR_BUNDLE_ID://{yourDomain}/ios/YOUR_BUNDLE_ID/callback` - - - 最後に、アプリケーションの**[Application Type(アプリケーションタイプ)]** が**[Native(ネイティブ)]** になっていることを[アプリケーションの設定](https://manage.auth0.com/#/applications/)で必ず確認してください。 -
    - -
    - .NET AndroidとiOSアプリケーションで、Auth0認証が手軽に実装できるように、Auth0は[Android](https://www.nuget.org/packages/Auth0.OidcClient.AndroidX/)と[iOS](https://www.nuget.org/packages/Auth0.OidcClient.iOS)のSDKを提供しています。 - - NuGetパッケージマネージャ([Tools(ツール)] -> [Library Package Manager(ライブラリーパッケージマネージャー)] -> [Package Manager Console(パッケージマネージャーコンソール)])を使用して、AndroidまたはiOSアプリケーションのどちらをビルドするかに応じて、`Auth0.OidcClient.AndroidX`または`Auth0.OidcClient.iOS`パッケージをインストールします。 - - NuGetパッケージマネージャーコンソール(`Install-Package`)や`dotnet` CLI(`dotnet add`)を代わりに使用することもできます。 - - ``` - Install-Package Auth0.OidcClient.AndroidX - Install-Package Auth0.OidcClient.iOS - ``` - - ``` - dotnet add Auth0.OidcClient.AndroidX - dotnet add Auth0.OidcClient.iOS - ``` -
    - -
    - Auth0をアプリケーションに統合するには、Auth0のドメインとクライアントIDを含む`Auth0ClientOptions`のインスタンスを渡して、`Auth0Client`クラスをインスタンス化します。 - - ``` - using Auth0.OidcClient; - var client = new Auth0Client(new Auth0ClientOptions { - Domain = "{yourDomain}", - ClientId = "{yourClientId}" - }, this); - ``` - - SDKは初期設定で、AndroidにはChrome Custom Tabs、iOSにはASWebAuthenticationSessionを利用します。 - - - ##### チェックポイント - Auth0Clientが適切にインスタンス化されました。アプリケーションを実行して次の点を確認します: - Auth0ClientのインスタンスがActivity(Android)またはUIViewController(iOS)で正しく作成されている。 - アプリケーションがAuth0に関連したエラーを投入していない。 - -
    - -
    - ユーザーが認証に成功すると、このクイックスタートで前にセットアップしたCallback URLへリダイレクトされます。 - - Androidデバイスでコールバックを扱うには、Callback URLを扱うインテントを登録する必要があります。これを手軽に実現するには、認証フローをインスタンス化するためにLoginAsyncメソッドを呼び出したのと同じアクティビティーにインテントを登録します。 - - 必ず、サンプルコードにある`YOUR_ANDROID_PACKAGE_NAME`は実際のアプリケーションのパッケージ名(`com.mycompany.myapplication`など)で置き換えてください。また、`DataScheme`、`DataHost`、`DataPathPrefix`のテキストがすべて小文字であることを確認してください。アクティビティーには`LaunchMode = LaunchMode.SingleTask`を設定します。設定しないと、Callback URLが呼び出されるたびに、システムがアクティビティーの新しいインスタンスを作成します。 - - また、`Activity`クラスにある`OnNewIntent`イベントでインテントを扱う必要があります。`ActivityMediator`シングルトンの`Send`メソッドを呼び出して受け取ったURLを渡し、Auth0のOIDCクライアントに認証フローを終わらせるよう通知する必要があります。 - - ``` - protected override void OnNewIntent(Intent intent) - { - - base.OnNewIntent(intent); - - ActivityMediator.Instance.Send(intent.DataString); - - } - ``` -
    - -
    - ユーザーが認証に成功すると、このクイックスタートで前にセットアップしたCallback URLへリダイレクトされます。 - - iOSデバイスでコールバックを扱うには、以下を行います: - - 1. アプリケーションの`Info.plist`ファイルをVisual Studioで開いて、**[Advanced(詳細)]** タブに移動します。 - 2. **[URL Types(URLタイプ)]** にある**[Add URL Type(URLタイプの追加)]** ボタンをクリックします。 - 3. **識別子** をAuth0、**URLスキーマ** をアプリケーションの`バンドル識別子`、**ロール** を`[None(なし)]`に設定します。 - - これは、URLタイプを追加した後でXML表記された`info.plist`ファイルの例です: - - ```xml - CFBundleURLTypes - - - CFBundleTypeRole - None - CFBundleURLName - Auth0 - CFBundleURLSchemes - - YOUR_BUNDLE_IDENTIFIER - - - - ``` - - さらに、`AppDelegate`クラスにある`OpenUrl`イベントでCallback URLを扱う必要があります。`ActivityMediator`シングルトンの`Send`メソッドを呼び出して受け取ったURLを渡し、Auth0のOIDCクライアントに認証フローを終わらせるよう通知する必要があります。 -
    - -
    - Auth0アプリケーションとAuth0 SDKの構成が完了したら、プロジェクトのためにログインをセットアップする必要があります。これを実現するには、SDKの`LoginAsync()`メソッドを使用して、ユーザーをAuth0のユニバーサルログインページにリダイレクトするログインボタンを作成します。 - - ```js - var loginResult = await client.LoginAsync(); - ``` - - エラーがなければ、`LoginAsync()`が返す`LoginResult`で`User`、`IdentityToken`、`AccessToken`、`RefreshToken`にアクセスすることができます。 - - - ##### チェックポイント - ユーザー名とパスワードを使ってログインやサインアップができるようになりました。 - ログインボタンをクリックして次の点を確認します: - AndroidまたはiOSアプリケーションによってAuth0のユニバーサルログインページにリダイレクトされる。 - ログインまたはサインアップできる。 - Auth0によってアプリケーションにリダイレクトされる。 - -
    - -
    - プロジェクトにログインしたユーザーには、ログアウトする方法も必要です。SDKの`LogoutAsync()`メソッドを使用してログアウトボタンを作成します。ユーザーはログアウトすると、Auth0ログアウトエンドポイントにリダイレクトされてから、即座に、このクイックスタートで先ほどセットアップしたログアウトURLにリダイレクトで戻されます。 - - ``` - await client.LogoutAsync(); - ``` - - - ##### チェックポイント - アプリケーションを実行して、ログアウトボタンをクリックします。以下の点を確認します: - AndroidまたはiOSアプリケーションによって、アプリケーションの設定で[Allowed Logout URLs(許可されているログアウトURL)]の1つに指定されているアドレスへリダイレクトされる。 - アプリケーションにログインしていない。 - -
    - -
    - ユーザーがログインやログアウトできるようになったら、認証済のユーザーに関連付けられたプロファイル情報を取得できるようにしたいと考えるはずです。たとえば、ログインしたユーザーの名前やプロフィール写真をプロジェクトに表示したいかもしれません。 - - AndroidまたはiOS用のAuth0 SDKでは、`LoginResult.User`プロパティを通じてユーザー情報を提供します。 - - ``` - if loginResult.IsError == false { - var user = loginResult.User - var name = user.FindFirst(c => c.Type == "name")?.Value - var email = user.FindFirst(c => c.Type == "email")?.Value - var picture = user.FindFirst(c => c.Type == "picture")?.Value - } - ``` -
    - - ## 次のステップ - - 成功です!ここまで来れば、アプリケーションにログイン、ログアウト、ユーザープロファイル情報が備わっているはずです。 - - これでクイックスタートチュートリアルは終了ですが、機能はまだまだたくさんあります。Auth0でできることについて詳しくは、以下をご覧ください。 - - * [Auth0 Dashboard](https://manage.auth0.com/#) - Auth0のテナントやアプリケーションを構成して管理する方法について説明します - * [auth0-oidc-client-net SDK](https://github.com/auth0/auth0-oidc-client-net) - このチュートリアルで使用されているSDKをより詳しく説明します - * [Auth0 Marketplace](https://marketplace.auth0.com/) - Auth0の機能性を拡張できる各種の統合を見つけられます -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    +--- +title: ".NET AndroidまたはiOSアプリケーションにログインを追加する" +permalink: "interactive" +'description': "このチュートリアルは、Auth0を使用して、.NET AndroidまたはiOSアプリケーションにユーザーログインを追加する方法について説明します。" +'og:title': ".NET AndroidまたはiOSアプリケーションにログインを追加する" +'og:description': "このチュートリアルは、Auth0を使用して、.NET AndroidまたはiOSアプリケーションにユーザーログインを追加する方法について説明します。" +'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/xamarin.png" +'twitter:title': ".NET AndroidまたはiOSアプリケーションにログインを追加する" +'twitter:description': "このチュートリアルは、Auth0を使用して、.NET AndroidまたはiOSアプリケーションにユーザーログインを追加する方法について説明します。" +sidebarTitle: .NET Android and iOS +--- + +import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; +import { LoggedInForm } from "/snippets/Login.jsx"; +import Mainactivity from "/snippets/quickstart/native/net-android-ios/MainActivity.cs.mdx"; +import Appdelegate from "/snippets/quickstart/native/net-android-ios/AppDelegate.cs.mdx"; +import Myviewcontroller from "/snippets/quickstart/native/net-android-ios/MyViewController.cs.mdx"; + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + +export const sections = [ + { id: "auth0を構成する", title: "Auth0を構成する" }, + { id: "auth0-sdkをインストールする", title: "Auth0 SDKをインストールする" }, + { id: "auth0clientをインスタンス化する", title: "Auth0Clientをインスタンス化する" }, + { id: "androidを構成する", title: "Androidを構成する" }, + { id: "iosを構成する", title: "iOSを構成する" }, + { id: "アプリケーションにログインを追加する", title: "アプリケーションにログインを追加する" }, + { id: "アプリケーションにログアウトを追加する", title: "アプリケーションにログアウトを追加する" }, + { id: "ユーザープロファイル情報を表示する", title: "ユーザープロファイル情報を表示する" } +] + + + + Auth0を使用すると、アプリケーションに手軽に認証を追加することができます。このガイドは、.NET AndroidまたはiOSアプリケーションに[Android](https://www.nuget.org/packages/Auth0.OidcClient.AndroidX/)や[iOS](https://www.nuget.org/packages/Auth0.OidcClient.iOS)用のAuth0 SDKを使ってAuth0を統合し、認証の追加とユーザープロファイル情報の表示を行う方法について説明します。 + + + このクイックスタートは、`Xamarin.Android`と`Xamarin.iOS`の次世代である.NET AndroidとiOSについて説明します。現在、`Xamarin.Android`や`Xamarin.iOS`を使用している場合は、統合が同一でSDKにも互換性があるため、このガイドに従ってください。 + + + このクイックスタートを使用するには、以下の手順に従います: + + - Auth0の無料アカウントにサインアップするか、Auth0にログインします。 + - 統合したいAndroidまたはiOSのプロジェクトで、.NET 6以降を使用したものを用意します。または、ログインした後に、サンプルアプリケーションを表示してダウンロードすることもできます。 + +
    + Auth0のサービスを利用するには、Auth0 Dashboadに設定済みのアプリケーションがある必要があります。Auth0アプリケーションは、プロジェクトに対してどのように認証が動作して欲しいかを構成する場所です。 + + ### アプリケーションを構成する + + 対話型のセレクターを使って「ネイティブアプリケーション」を新規作成するか、統合したいプロジェクトを表す既存のアプリケーションを選択します。Auth0のすべてのアプリケーションには英数字からなる一意のクライアントIDが割り当てられており、アプリケーションのコードがSDKを通じてAuth0 APIを呼び出す際に使用されます。 + + このクイックスタートを使って構成されたすべての設定は、[Dashboard](https://manage.auth0.com/#/)のアプリケーションを自動更新します。今後、アプリケーションの管理もDashboardで行えます。 + + 完了済みの構成を見てみたい場合は、サンプルアプリケーションをご覧ください。 + + ### Callback URLを構成する + + Callback URLとは、Auth0がユーザーを認証後にリダイレクトするアプリケーション内URLです。設定されていない場合、ユーザーはログイン後にアプリケーションに戻りません。 + + + サンプルプロジェクトに沿って進めている場合は、プラットフォームに応じて、これを次のURLの1つに設定します: + + - **Android** :`YOUR_PACKAGE_NAME://{yourDomain}/android/YOUR_PACKAGE_NAME/callback` + - **iOS** :`YOUR_BUNDLE_ID://{yourDomain}/ios/YOUR_BUNDLE_ID/callback` + + + ### ログアウトURLを構成する + + ログアウトURLとは、Auth0がユーザーをログアウト後にリダイレクトするアプリケーション内URLです。設定されていない場合、ユーザーはアプリケーションからログアウトできず、エラーを受け取ります。 + + + サンプルプロジェクトに沿って進めている場合は、プラットフォームに応じて、これを次のURLの1つに設定します: + + - **Android** :`YOUR_PACKAGE_NAME://{yourDomain}/android/YOUR_PACKAGE_NAME/callback` + - **iOS** :`YOUR_BUNDLE_ID://{yourDomain}/ios/YOUR_BUNDLE_ID/callback` + + + 最後に、アプリケーションの**[Application Type(アプリケーションタイプ)]** が**[Native(ネイティブ)]** になっていることを[アプリケーションの設定](https://manage.auth0.com/#/applications/)で必ず確認してください。 +
    + +
    + .NET AndroidとiOSアプリケーションで、Auth0認証が手軽に実装できるように、Auth0は[Android](https://www.nuget.org/packages/Auth0.OidcClient.AndroidX/)と[iOS](https://www.nuget.org/packages/Auth0.OidcClient.iOS)のSDKを提供しています。 + + NuGetパッケージマネージャ([Tools(ツール)] -> [Library Package Manager(ライブラリーパッケージマネージャー)] -> [Package Manager Console(パッケージマネージャーコンソール)])を使用して、AndroidまたはiOSアプリケーションのどちらをビルドするかに応じて、`Auth0.OidcClient.AndroidX`または`Auth0.OidcClient.iOS`パッケージをインストールします。 + + NuGetパッケージマネージャーコンソール(`Install-Package`)や`dotnet` CLI(`dotnet add`)を代わりに使用することもできます。 + + ``` + Install-Package Auth0.OidcClient.AndroidX + Install-Package Auth0.OidcClient.iOS + ``` + + ``` + dotnet add Auth0.OidcClient.AndroidX + dotnet add Auth0.OidcClient.iOS + ``` +
    + +
    + Auth0をアプリケーションに統合するには、Auth0のドメインとクライアントIDを含む`Auth0ClientOptions`のインスタンスを渡して、`Auth0Client`クラスをインスタンス化します。 + + ``` + using Auth0.OidcClient; + var client = new Auth0Client(new Auth0ClientOptions { + Domain = "{yourDomain}", + ClientId = "{yourClientId}" + }, this); + ``` + + SDKは初期設定で、AndroidにはChrome Custom Tabs、iOSにはASWebAuthenticationSessionを利用します。 + + + ##### チェックポイント + Auth0Clientが適切にインスタンス化されました。アプリケーションを実行して次の点を確認します: + Auth0ClientのインスタンスがActivity(Android)またはUIViewController(iOS)で正しく作成されている。 + アプリケーションがAuth0に関連したエラーを投入していない。 + +
    + +
    + ユーザーが認証に成功すると、このクイックスタートで前にセットアップしたCallback URLへリダイレクトされます。 + + Androidデバイスでコールバックを扱うには、Callback URLを扱うインテントを登録する必要があります。これを手軽に実現するには、認証フローをインスタンス化するためにLoginAsyncメソッドを呼び出したのと同じアクティビティーにインテントを登録します。 + + 必ず、サンプルコードにある`YOUR_ANDROID_PACKAGE_NAME`は実際のアプリケーションのパッケージ名(`com.mycompany.myapplication`など)で置き換えてください。また、`DataScheme`、`DataHost`、`DataPathPrefix`のテキストがすべて小文字であることを確認してください。アクティビティーには`LaunchMode = LaunchMode.SingleTask`を設定します。設定しないと、Callback URLが呼び出されるたびに、システムがアクティビティーの新しいインスタンスを作成します。 + + また、`Activity`クラスにある`OnNewIntent`イベントでインテントを扱う必要があります。`ActivityMediator`シングルトンの`Send`メソッドを呼び出して受け取ったURLを渡し、Auth0のOIDCクライアントに認証フローを終わらせるよう通知する必要があります。 + + ``` + protected override void OnNewIntent(Intent intent) + { + + base.OnNewIntent(intent); + + ActivityMediator.Instance.Send(intent.DataString); + + } + ``` +
    + +
    + ユーザーが認証に成功すると、このクイックスタートで前にセットアップしたCallback URLへリダイレクトされます。 + + iOSデバイスでコールバックを扱うには、以下を行います: + + 1. アプリケーションの`Info.plist`ファイルをVisual Studioで開いて、**[Advanced(詳細)]** タブに移動します。 + 2. **[URL Types(URLタイプ)]** にある**[Add URL Type(URLタイプの追加)]** ボタンをクリックします。 + 3. **識別子** をAuth0、**URLスキーマ** をアプリケーションの`バンドル識別子`、**ロール** を`[None(なし)]`に設定します。 + + これは、URLタイプを追加した後でXML表記された`info.plist`ファイルの例です: + + ```xml + CFBundleURLTypes + + + CFBundleTypeRole + None + CFBundleURLName + Auth0 + CFBundleURLSchemes + + YOUR_BUNDLE_IDENTIFIER + + + + ``` + + さらに、`AppDelegate`クラスにある`OpenUrl`イベントでCallback URLを扱う必要があります。`ActivityMediator`シングルトンの`Send`メソッドを呼び出して受け取ったURLを渡し、Auth0のOIDCクライアントに認証フローを終わらせるよう通知する必要があります。 +
    + +
    + Auth0アプリケーションとAuth0 SDKの構成が完了したら、プロジェクトのためにログインをセットアップする必要があります。これを実現するには、SDKの`LoginAsync()`メソッドを使用して、ユーザーをAuth0のユニバーサルログインページにリダイレクトするログインボタンを作成します。 + + ```js + var loginResult = await client.LoginAsync(); + ``` + + エラーがなければ、`LoginAsync()`が返す`LoginResult`で`User`、`IdentityToken`、`AccessToken`、`RefreshToken`にアクセスすることができます。 + + + ##### チェックポイント + ユーザー名とパスワードを使ってログインやサインアップができるようになりました。 + ログインボタンをクリックして次の点を確認します: + AndroidまたはiOSアプリケーションによってAuth0のユニバーサルログインページにリダイレクトされる。 + ログインまたはサインアップできる。 + Auth0によってアプリケーションにリダイレクトされる。 + +
    + +
    + プロジェクトにログインしたユーザーには、ログアウトする方法も必要です。SDKの`LogoutAsync()`メソッドを使用してログアウトボタンを作成します。ユーザーはログアウトすると、Auth0ログアウトエンドポイントにリダイレクトされてから、即座に、このクイックスタートで先ほどセットアップしたログアウトURLにリダイレクトで戻されます。 + + ``` + await client.LogoutAsync(); + ``` + + + ##### チェックポイント + アプリケーションを実行して、ログアウトボタンをクリックします。以下の点を確認します: + AndroidまたはiOSアプリケーションによって、アプリケーションの設定で[Allowed Logout URLs(許可されているログアウトURL)]の1つに指定されているアドレスへリダイレクトされる。 + アプリケーションにログインしていない。 + +
    + +
    + ユーザーがログインやログアウトできるようになったら、認証済のユーザーに関連付けられたプロファイル情報を取得できるようにしたいと考えるはずです。たとえば、ログインしたユーザーの名前やプロフィール写真をプロジェクトに表示したいかもしれません。 + + AndroidまたはiOS用のAuth0 SDKでは、`LoginResult.User`プロパティを通じてユーザー情報を提供します。 + + ``` + if loginResult.IsError == false { + var user = loginResult.User + var name = user.FindFirst(c => c.Type == "name")?.Value + var email = user.FindFirst(c => c.Type == "email")?.Value + var picture = user.FindFirst(c => c.Type == "picture")?.Value + } + ``` +
    + + ## 次のステップ + + 成功です!ここまで来れば、アプリケーションにログイン、ログアウト、ユーザープロファイル情報が備わっているはずです。 + + これでクイックスタートチュートリアルは終了ですが、機能はまだまだたくさんあります。Auth0でできることについて詳しくは、以下をご覧ください。 + + * [Auth0 Dashboard](https://manage.auth0.com/#) - Auth0のテナントやアプリケーションを構成して管理する方法について説明します + * [auth0-oidc-client-net SDK](https://github.com/auth0/auth0-oidc-client-net) - このチュートリアルで使用されているSDKをより詳しく説明します + * [Auth0 Marketplace](https://marketplace.auth0.com/) - Auth0の機能性を拡張できる各種の統合を見つけられます +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    diff --git a/main/docs/ja-jp/quickstart/spa/angular/interactive.mdx b/main/docs/ja-jp/quickstart/spa/angular/interactive.mdx index ed2a4c426..e2eae8587 100644 --- a/main/docs/ja-jp/quickstart/spa/angular/interactive.mdx +++ b/main/docs/ja-jp/quickstart/spa/angular/interactive.mdx @@ -1,237 +1,239 @@ ---- -title: "Angularアプリケーションにログインを追加する" -permalink: "interactive" -'description': "このガイドは、AngularアプリケーションにAuth0 Angular SDKを使ってAuth0を統合し、認証の追加とユーザープロファイル情報の表示を行う方法について説明します。" -'og:title': "Angularアプリケーションにログインを追加する" -'og:description': "このガイドは、AngularアプリケーションにAuth0 Angular SDKを使ってAuth0を統合し、認証の追加とユーザープロファイル情報の表示を行う方法について説明します。" -'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/angular.png" -'twitter:title': "Angularアプリケーションにログインを追加する" -'twitter:description': "このガイドは、AngularアプリケーションにAuth0 Angular SDKを使ってAuth0を統合し、認証の追加とユーザープロファイル情報の表示を行う方法について説明します。" -mode: wide -sidebarTitle: Angular ---- - -import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; -import { LoggedInForm } from "/snippets/Login.jsx"; -import Main from "/snippets/quickstart/spa/angular/main.mdx" -import LoginButton from "/snippets/quickstart/spa/angular/login-button.mdx" -import LogoutButton from "/snippets/quickstart/spa/angular/logout-button.mdx" -import UserProfile from "/snippets/quickstart/spa/angular/user-profile.mdx" - -export const sections = [ - { id: "auth0を構成する", title: "Auth0を構成する" }, - { id: "auth0-angular-sdkをインストールする", title: "Auth0 Angular SDKをインストールする" }, - { id: "auth0を登録-提供する", title: "Auth0を登録・提供する" }, - { id: "アプリケーションにログインを追加する", title: "アプリケーションにログインを追加する" }, - { id: "アプリケーションにログアウトを追加する", title: "アプリケーションにログアウトを追加する" }, - { id: "ユーザープロファイル情報を表示する", title: "ユーザープロファイル情報を表示する" } -] - - - - - Angularでユーザー認証を実装するための詳しい情報については、「[例を挙げて説明するAngular認証ガイド](https://developer.auth0.com/resources/guides/spa/angular/basic-authentication)」を参照してください。このガイドでは、サインアップボタンを作成する方法、ルートガードを追加する方法、そして保護されたAPIをAngularから呼び出す方法が詳しく説明されています。 - - - Auth0を使用すると、アプリケーションに手軽に認証を追加することができます。このガイドは、Angularアプリケーションに[Auth0 Angular SDK](https://github.com/auth0/auth0-angular)を使ってAuth0を統合し、認証の追加とユーザープロファイル情報の表示を行う方法について説明します。 - - このクイックスタートを使用するには、以下の手順に従います: - -
    - Auth0のサービスを利用するには、Auth0 Dashboadに設定済みのアプリケーションがある必要があります。Auth0アプリケーションは、開発中のプロジェクトに対してどのように認証が動作して欲しいかを構成する場所です。 - - ### アプリケーションを構成する - - 対話型のセレクターを使ってAuth0アプリケーションを新規作成するか、統合したいプロジェクトを表す既存のアプリケーションを選択します。Auth0のすべてのアプリケーションには英数字からなる一意のクライアントIDが割り当てられており、アプリケーションのコードがSDKを通じてAuth0 - APIを呼び出す際に使用されます。 - - このクイックスタートを使って構成されたすべての設定は、[Dashboard](https://manage.auth0.com/#/)のアプリケーションを自動更新します。今後、アプリケーションの管理もDashboardで行えます。 - - 代わりに完了済みの構成を見てみたい場合は、サンプルアプリケーションをご覧ください。 - - ### Callback URLを構成する - - Callback URLとは、Auth0がユーザーを認証後にリダイレクトするアプリケーション内URLです。設定されていない場合、ユーザーはログイン後にアプリケーションに戻りません。 - - - サンプルプロジェクトに沿って進めている場合は、`http://localhost:4200`に設定してください。 - - - ### ログアウトURLを構成する - - ログアウトURLとは、Auth0がユーザーをログアウト後にリダイレクトするアプリケーション内URLです。設定されていない場合、ユーザーはアプリケーションからログアウトできず、エラーを受け取ります。 - - - サンプルプロジェクトに沿って進めている場合は、`http://localhost:4200`に設定してください。 - - - ### Allowed Web Origins(許可されているWebオリジン)を構成する - - [Allowed Web - Origin(許可されているWebオリジン)]とは、認証フローにアクセスすることを許可して欲しいURLです。これにはプロジェクトのURLが含まれている必要があります。適切に設定されていない場合、プロジェクトが認証トークンを暗黙でリフレッシュできず、ユーザーがアプリケーションを再び訪問した時、またはページを再読み込みした時にログアウトした状態になってしまいます。 - - - サンプルプロジェクトに沿って進めている場合は、`http://localhost:4200`に設定してください。 - -
    - -
    - Angularアプリで、Auth0の認証・認可を手軽に実装できるように、Auth0は[Angular SDK](https://github.com/auth0/auth0-angular)を提供しています。 - - ターミナルで以下のコマンドを実行してAuth0 Angular SDKをインストールします: - - ```bash - npm install @auth0/auth0-angular - ``` - - SDKはモジュールや認証サービスなど、Auth0をAngularアプリケーションに慣用的に統合しやすくする種類をいくつか公開しています。 -
    - -
    - SDKは、SDKが機能するために必要なすべてのサービスを含んだprovide関数である、`provideAuth0`をエクスポートします。これをアプリケーションで登録するには、以下のようにします。 - - 1. `main.ts`ファイルを開きます。 - 2. `@auth0/auth0-angular`パッケージから`provideAuth0`関数をインポートします。 - 3. `provideAuth0`を`bootstrapApplication`内の`providers`に追加することで、アプリケーションに追加します。 - 4. `AuthService`を`AppComponent`に注入します。 - - `provideAuth0`関数は`domain`プロパティと`clientId`プロパティを取ります。これらのプロパティの値は、Auth0で登録したシングルページアプリケーション(SPA)の**[Settings(設定)]** にある**Domain(ドメイン)** と**Client - ID(クライアントID)**の値に対応します。その上に、`authorizationParams.redirect_uri`を構成します。これによって、認証に成功した後、Auth0はユーザーを特定のURLにリダイレクトで戻すことができます。 - - - [Auth0を使用したカスタムドメイン](/docs/ja-jp/custom-domains)では、ドメインプロパティの値は[Settings(設定)]タブに反映された値でなく、カスタムドメインの値になります。 - -
    - -
    - Auth0アプリケーションとAuth0 Angular - SDKの構成が完了したら、プロジェクトのためにログインをセットアップする必要があります。これを実現するには、`AuthService`クラスからSDKの`loginWithRedirect()`メソッドを使用して、ユーザーをAuth0のユニバーサルログインページにリダイレクトします。そこでAuth0はユーザーを認証することができます。ユーザーが認証に成功すると、アプリケーション、およびこのクイックスタートで前にセットアップしたCallback - URLへリダイレクトされます。 - - アプリケーションで選択時に`loginWithRedirect()`を呼び出すログインボタンを作成します。 - - - ##### チェックポイント - - アプリケーションにログインできるようになります。 - - アプリケーションを実行し、ログインボタンを選択します。以下の点を確認します: - - - ユーザー名とパスワードを使って、ログインまたはサインアップできる。 - - アプリケーションによって[Auth0ユニバーサルログイン](https://auth0.com/universal-login)ページにリダイレクトされる。 - - 認証用にAuth0にリダイレクトされる。 - - 認証した後、Auth0はアプリケーションにリダイレクトで戻される。 - - コンソールでAuth0に関連したエラーを受け取らない。 - -
    - -
    - プロジェクトにログインしたユーザーには、[ログアウトする方法](/docs/ja-jp/logout/guides/logout-auth0)も必要です。SDKには、`AuthService`クラスでアプリからユーザーをログアウトするのに使用できる`logout()`メソッドが用意されています。ユーザーはログアウトすると、[Auth0ログアウトエンドポイント](https://auth0.com/docs/api/authentication?javascript#logout)にリダイレクトされてから、即座に、アプリケーションとこのクイックスタートで先ほどセットアップしたログアウトURLへとリダイレクトで戻されます。 - - アプリケーションで選択時に`logout()`を呼び出すログアウトボタンを作成します。 - - - SDKによって`AuthService`クラスで`isAuthenticated$` - Observableが公開されることで、ユーザーが認証されているかどうかを確認することができます。`isAuthenticated$` - Observableの値に基づいて、条件付きでログインボタンとログアウトボタンを作成することができます。または、シングルボタンを使って、ログインとログアウトの両方のボタンと条件付きレンダリングを組み合わせることができます。 - - - - ##### チェックポイント - - アプリケーションからログアウトできるようになります。 - - アプリケーションを実行し、ログインし、ログアウトボタンを選択します。以下の点を確認します: - - - Auth0のログアウトエンドポイントにリダイレクトされている。 - - Auth0がアプリケーションと正しいログアウトURLへのリダイレクトで戻される。 - - アプリケーションにログインしていない。 - - コンソールでAuth0に関連したエラーを受け取らない。 - -
    - -
    - ユーザーがログインやログアウトできるようになったら、認証済みのユーザーに関連付けられた[プロファイル情報](/docs/ja-jp/users/concepts/overview-user-profile)を取得できるようにしたいと考えるはずです。たとえば、ログインしたユーザーの名前やプロフィール写真を表示することで、ユーザーインターフェイスをパーソナライズできるようになりたいかもしれません。 - - Auth0 Angular SDKは、`AuthService`クラスによって公開された`user$` - Observableを介してユーザー情報を提供します。`user$` - Observableにはユーザーのアイデンティティに関する機密情報とアーティファクトが含まれるため、この方法が使用できるかはユーザーの認証ステータスによります。幸い、`user$` - Observableは、`isAuthenticated$` - Observableがtrueである場合にのみ値を出力するよう構成されています。そのため、ユーザープロファイルデータにアクセスする前に、認証状態を手動で確認する必要はありません。 - - SDKは、`AuthService`クラスでユーザーが認証されているかどうかを確認することができる`isAuthenticated$` - Observableも公開します。これを使って、たとえば、UI要素を表示・非表示にするかを判断することができます。 - - インタラクティブパネルで`UserProfileComponent`コードを確認し、これらの関数の使用方法の例をチェックします。 - - - ##### チェックポイント - - ユーザープロファイル情報を表示することができるようになります。 - - アプリケーションを実行して次の点を確認します: - - - ログイン後にユーザー情報が正しく表示される。 - - ログアウト後にユーザー情報が表示されない。 - -
    - - ## 次のステップ - - 成功です!ここまで来れば、アプリケーションにログイン、ログアウト、ユーザープロファイル情報が備わっているはずです。 - - これでクイックスタートチュートリアルは終了ですが、機能はまだまだたくさんあります。Auth0でできることについて詳しくは、以下をご覧ください。 - - * [Auth0 Dashboard](https://manage.auth0.com/#) - Auth0のテナントやアプリケーションを構成して管理する方法について説明します - * [auth0-angular SDK](https://github.com/auth0/auth0-angular) - このチュートリアルで使用されているSDKをより詳しく説明します - * [Auth0 Marketplace](https://marketplace.auth0.com/) - Auth0の機能性を拡張できる各種の統合を見つけられます -
    - - - - - - - - - - - - -
    - - - - - - - - - -
    - - - - - - - - -
    - - - - - - - - -
    - - - - - - - - +--- +title: "Angularアプリケーションにログインを追加する" +permalink: "interactive" +'description': "このガイドは、AngularアプリケーションにAuth0 Angular SDKを使ってAuth0を統合し、認証の追加とユーザープロファイル情報の表示を行う方法について説明します。" +'og:title': "Angularアプリケーションにログインを追加する" +'og:description': "このガイドは、AngularアプリケーションにAuth0 Angular SDKを使ってAuth0を統合し、認証の追加とユーザープロファイル情報の表示を行う方法について説明します。" +'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/angular.png" +'twitter:title': "Angularアプリケーションにログインを追加する" +'twitter:description': "このガイドは、AngularアプリケーションにAuth0 Angular SDKを使ってAuth0を統合し、認証の追加とユーザープロファイル情報の表示を行う方法について説明します。" +mode: wide +sidebarTitle: Angular +--- + +import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; +import { LoggedInForm } from "/snippets/Login.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + +import Main from "/snippets/quickstart/spa/angular/main.mdx" +import LoginButton from "/snippets/quickstart/spa/angular/login-button.mdx" +import LogoutButton from "/snippets/quickstart/spa/angular/logout-button.mdx" +import UserProfile from "/snippets/quickstart/spa/angular/user-profile.mdx" + +export const sections = [ + { id: "auth0を構成する", title: "Auth0を構成する" }, + { id: "auth0-angular-sdkをインストールする", title: "Auth0 Angular SDKをインストールする" }, + { id: "auth0を登録-提供する", title: "Auth0を登録・提供する" }, + { id: "アプリケーションにログインを追加する", title: "アプリケーションにログインを追加する" }, + { id: "アプリケーションにログアウトを追加する", title: "アプリケーションにログアウトを追加する" }, + { id: "ユーザープロファイル情報を表示する", title: "ユーザープロファイル情報を表示する" } +] + + + + + Angularでユーザー認証を実装するための詳しい情報については、「[例を挙げて説明するAngular認証ガイド](https://developer.auth0.com/resources/guides/spa/angular/basic-authentication)」を参照してください。このガイドでは、サインアップボタンを作成する方法、ルートガードを追加する方法、そして保護されたAPIをAngularから呼び出す方法が詳しく説明されています。 + + + Auth0を使用すると、アプリケーションに手軽に認証を追加することができます。このガイドは、Angularアプリケーションに[Auth0 Angular SDK](https://github.com/auth0/auth0-angular)を使ってAuth0を統合し、認証の追加とユーザープロファイル情報の表示を行う方法について説明します。 + + このクイックスタートを使用するには、以下の手順に従います: + +
    + Auth0のサービスを利用するには、Auth0 Dashboadに設定済みのアプリケーションがある必要があります。Auth0アプリケーションは、開発中のプロジェクトに対してどのように認証が動作して欲しいかを構成する場所です。 + + ### アプリケーションを構成する + + 対話型のセレクターを使ってAuth0アプリケーションを新規作成するか、統合したいプロジェクトを表す既存のアプリケーションを選択します。Auth0のすべてのアプリケーションには英数字からなる一意のクライアントIDが割り当てられており、アプリケーションのコードがSDKを通じてAuth0 + APIを呼び出す際に使用されます。 + + このクイックスタートを使って構成されたすべての設定は、[Dashboard](https://manage.auth0.com/#/)のアプリケーションを自動更新します。今後、アプリケーションの管理もDashboardで行えます。 + + 代わりに完了済みの構成を見てみたい場合は、サンプルアプリケーションをご覧ください。 + + ### Callback URLを構成する + + Callback URLとは、Auth0がユーザーを認証後にリダイレクトするアプリケーション内URLです。設定されていない場合、ユーザーはログイン後にアプリケーションに戻りません。 + + + サンプルプロジェクトに沿って進めている場合は、`http://localhost:4200`に設定してください。 + + + ### ログアウトURLを構成する + + ログアウトURLとは、Auth0がユーザーをログアウト後にリダイレクトするアプリケーション内URLです。設定されていない場合、ユーザーはアプリケーションからログアウトできず、エラーを受け取ります。 + + + サンプルプロジェクトに沿って進めている場合は、`http://localhost:4200`に設定してください。 + + + ### Allowed Web Origins(許可されているWebオリジン)を構成する + + [Allowed Web + Origin(許可されているWebオリジン)]とは、認証フローにアクセスすることを許可して欲しいURLです。これにはプロジェクトのURLが含まれている必要があります。適切に設定されていない場合、プロジェクトが認証トークンを暗黙でリフレッシュできず、ユーザーがアプリケーションを再び訪問した時、またはページを再読み込みした時にログアウトした状態になってしまいます。 + + + サンプルプロジェクトに沿って進めている場合は、`http://localhost:4200`に設定してください。 + +
    + +
    + Angularアプリで、Auth0の認証・認可を手軽に実装できるように、Auth0は[Angular SDK](https://github.com/auth0/auth0-angular)を提供しています。 + + ターミナルで以下のコマンドを実行してAuth0 Angular SDKをインストールします: + + ```bash + npm install @auth0/auth0-angular + ``` + + SDKはモジュールや認証サービスなど、Auth0をAngularアプリケーションに慣用的に統合しやすくする種類をいくつか公開しています。 +
    + +
    + SDKは、SDKが機能するために必要なすべてのサービスを含んだprovide関数である、`provideAuth0`をエクスポートします。これをアプリケーションで登録するには、以下のようにします。 + + 1. `main.ts`ファイルを開きます。 + 2. `@auth0/auth0-angular`パッケージから`provideAuth0`関数をインポートします。 + 3. `provideAuth0`を`bootstrapApplication`内の`providers`に追加することで、アプリケーションに追加します。 + 4. `AuthService`を`AppComponent`に注入します。 + + `provideAuth0`関数は`domain`プロパティと`clientId`プロパティを取ります。これらのプロパティの値は、Auth0で登録したシングルページアプリケーション(SPA)の**[Settings(設定)]** にある**Domain(ドメイン)** と**Client + ID(クライアントID)**の値に対応します。その上に、`authorizationParams.redirect_uri`を構成します。これによって、認証に成功した後、Auth0はユーザーを特定のURLにリダイレクトで戻すことができます。 + + + [Auth0を使用したカスタムドメイン](/docs/ja-jp/custom-domains)では、ドメインプロパティの値は[Settings(設定)]タブに反映された値でなく、カスタムドメインの値になります。 + +
    + +
    + Auth0アプリケーションとAuth0 Angular + SDKの構成が完了したら、プロジェクトのためにログインをセットアップする必要があります。これを実現するには、`AuthService`クラスからSDKの`loginWithRedirect()`メソッドを使用して、ユーザーをAuth0のユニバーサルログインページにリダイレクトします。そこでAuth0はユーザーを認証することができます。ユーザーが認証に成功すると、アプリケーション、およびこのクイックスタートで前にセットアップしたCallback + URLへリダイレクトされます。 + + アプリケーションで選択時に`loginWithRedirect()`を呼び出すログインボタンを作成します。 + + + ##### チェックポイント + + アプリケーションにログインできるようになります。 + + アプリケーションを実行し、ログインボタンを選択します。以下の点を確認します: + + - ユーザー名とパスワードを使って、ログインまたはサインアップできる。 + - アプリケーションによって[Auth0ユニバーサルログイン](https://auth0.com/universal-login)ページにリダイレクトされる。 + - 認証用にAuth0にリダイレクトされる。 + - 認証した後、Auth0はアプリケーションにリダイレクトで戻される。 + - コンソールでAuth0に関連したエラーを受け取らない。 + +
    + +
    + プロジェクトにログインしたユーザーには、[ログアウトする方法](/docs/ja-jp/logout/guides/logout-auth0)も必要です。SDKには、`AuthService`クラスでアプリからユーザーをログアウトするのに使用できる`logout()`メソッドが用意されています。ユーザーはログアウトすると、[Auth0ログアウトエンドポイント](https://auth0.com/docs/api/authentication?javascript#logout)にリダイレクトされてから、即座に、アプリケーションとこのクイックスタートで先ほどセットアップしたログアウトURLへとリダイレクトで戻されます。 + + アプリケーションで選択時に`logout()`を呼び出すログアウトボタンを作成します。 + + + SDKによって`AuthService`クラスで`isAuthenticated$` + Observableが公開されることで、ユーザーが認証されているかどうかを確認することができます。`isAuthenticated$` + Observableの値に基づいて、条件付きでログインボタンとログアウトボタンを作成することができます。または、シングルボタンを使って、ログインとログアウトの両方のボタンと条件付きレンダリングを組み合わせることができます。 + + + + ##### チェックポイント + + アプリケーションからログアウトできるようになります。 + + アプリケーションを実行し、ログインし、ログアウトボタンを選択します。以下の点を確認します: + + - Auth0のログアウトエンドポイントにリダイレクトされている。 + - Auth0がアプリケーションと正しいログアウトURLへのリダイレクトで戻される。 + - アプリケーションにログインしていない。 + - コンソールでAuth0に関連したエラーを受け取らない。 + +
    + +
    + ユーザーがログインやログアウトできるようになったら、認証済みのユーザーに関連付けられた[プロファイル情報](/docs/ja-jp/users/concepts/overview-user-profile)を取得できるようにしたいと考えるはずです。たとえば、ログインしたユーザーの名前やプロフィール写真を表示することで、ユーザーインターフェイスをパーソナライズできるようになりたいかもしれません。 + + Auth0 Angular SDKは、`AuthService`クラスによって公開された`user$` + Observableを介してユーザー情報を提供します。`user$` + Observableにはユーザーのアイデンティティに関する機密情報とアーティファクトが含まれるため、この方法が使用できるかはユーザーの認証ステータスによります。幸い、`user$` + Observableは、`isAuthenticated$` + Observableがtrueである場合にのみ値を出力するよう構成されています。そのため、ユーザープロファイルデータにアクセスする前に、認証状態を手動で確認する必要はありません。 + + SDKは、`AuthService`クラスでユーザーが認証されているかどうかを確認することができる`isAuthenticated$` + Observableも公開します。これを使って、たとえば、UI要素を表示・非表示にするかを判断することができます。 + + インタラクティブパネルで`UserProfileComponent`コードを確認し、これらの関数の使用方法の例をチェックします。 + + + ##### チェックポイント + + ユーザープロファイル情報を表示することができるようになります。 + + アプリケーションを実行して次の点を確認します: + + - ログイン後にユーザー情報が正しく表示される。 + - ログアウト後にユーザー情報が表示されない。 + +
    + + ## 次のステップ + + 成功です!ここまで来れば、アプリケーションにログイン、ログアウト、ユーザープロファイル情報が備わっているはずです。 + + これでクイックスタートチュートリアルは終了ですが、機能はまだまだたくさんあります。Auth0でできることについて詳しくは、以下をご覧ください。 + + * [Auth0 Dashboard](https://manage.auth0.com/#) - Auth0のテナントやアプリケーションを構成して管理する方法について説明します + * [auth0-angular SDK](https://github.com/auth0/auth0-angular) - このチュートリアルで使用されているSDKをより詳しく説明します + * [Auth0 Marketplace](https://marketplace.auth0.com/) - Auth0の機能性を拡張できる各種の統合を見つけられます +
    + + + + + + + + + + + + +
    + + + + + + + + + +
    + + + + + + + + +
    + + + + + + + + +
    + + + + + + + + diff --git a/main/docs/ja-jp/quickstart/spa/flutter/interactive.mdx b/main/docs/ja-jp/quickstart/spa/flutter/interactive.mdx index acd14c8e8..b87afd81a 100644 --- a/main/docs/ja-jp/quickstart/spa/flutter/interactive.mdx +++ b/main/docs/ja-jp/quickstart/spa/flutter/interactive.mdx @@ -1,205 +1,207 @@ ---- -title: "Flutterアプリケーションにログインを追加する" -permalink: "interactive" -'description': "このガイドでは、FlutterアプリケーションにAuth0 Flutter SDKを使ってAuth0を統合する方法を説明します。" -'og:title': "Flutterアプリケーションにログインを追加する" -'og:description': "このガイドでは、FlutterアプリケーションにAuth0 Flutter SDKを使ってAuth0を統合する方法を説明します。" -'og:image': "https://cdn2.auth0.com/docs/1.14567.0/img/share-image.png" -'twitter:title': "Flutterアプリケーションにログインを追加する" -'twitter:description': "このガイドでは、FlutterアプリケーションにAuth0 Flutter SDKを使ってAuth0を統合する方法を説明します。" -sidebarTitle: Flutter -mode: wide ---- - -import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; -import { LoggedInForm } from "/snippets/Login.jsx"; -import MainView from "/snippets/quickstart/spa/flutter/main_view.mdx" -import ProfileView from "/snippets/quickstart/spa/flutter/profile_view.mdx" - -export const sections = [ - { id: "auth0を構成する", title: "Auth0を構成する" }, - { id: "auth0-flutter-sdkをインストールする", title: "Auth0 Flutter SDKをインストールする" }, - { id: "アプリケーションにログインを追加する", title: "アプリケーションにログインを追加する" }, - { id: "アプリケーションにログアウトを追加する", title: "アプリケーションにログアウトを追加する" }, - { id: "ユーザープロファイル情報を表示する", title: "ユーザープロファイル情報を表示する" } -] - - - - Auth0を使用すると、アプリケーションに手軽に認証を追加して、ユーザープロファイル情報にアクセスすることができます。このガイドでは、Flutterアプリケーションに[Auth0 Flutter - SDK](https://github.com/auth0/auth0-flutter)を使ってAuth0を統合する方法を説明します。 - - - Flutter SDKは現在、Android、iOS、またはWebプラットフォームで実行されるFlutterアプリケーションのみに対応しています。 - - - このクイックスタートでは、すでに[Flutter](https://flutter.dev/)アプリケーションが問題なく作動しているものとします。そうでない場合は、[Flutter「入門」ガイド](https://docs.flutter.dev/get-started/install)をチェックして、シンプルなアプリの始め方を確認してください。 - - [Flutterコマンドラインツール](https://docs.flutter.dev/reference/flutter-cli)の知識も必要になります。 - -
    - Auth0にサインアップすると、新しいアプリケーションが作成されたか、あるいは既に作成していた可能性があります。Auth0と通信するためのアプリケーションに関する詳細が必要になります。これらの詳細は、Auth0 - Dashboardの[アプリケーションの設定](https://manage.auth0.com/#/applications)セクションで入手することができます。 - - - - - - - ネイティブまたはシングルページアプリケーションでデフォルトのアプリを使用する場合は、**[Token Endpoint Authentication - Method(トークンエンドポイント認証方法)]**を`None`に更新し、** [Application - Type(アプリケーションタイプ)]**を`SPA`または`Native`に設定していることを確認します。 - - - 必要な情報は以下のとおりです。 - - - **Domain(ドメイン)** - - **Client ID(クライアントID)** - - - このページの上部からサンプルをダウンロードする場合、これらの詳細は入力されています。 - - - ### Callback URLを構成する - - Callback URLとは、Auth0によって認証後のユーザーをリダイレクトするアプリケーション内URLです。アプリのCallback URLは、[アプリケーションの設定](https://manage.auth0.com/#/applications)で**[Allowed Callback - URLs(許可されているコールバックURL)]**フィールドに追加される必要があります。このフィールドが設定されていない場合、ユーザーはアプリケーションにログインできず、エラーが返されます。 - - - このページの上部からダウンロードしたサンプルプロジェクトに沿って進めている場合には、**[Allowed Callback - URLs(許可されているコールバックURL)]**に`http://localhost:3000`を設定します。 - - - ### ログアウトURLを構成する - - ログアウトURLとは、ユーザーが認可サーバーからログアウトした後にAuth0が戻ることができるアプリケーション内URLです。これは、`returnTo`クエリパラメーターで指定されています。アプリのログアウトURLは、[アプリケーションの設定](https://manage.auth0.com/#/applications)で**[Allowed Logout - URLs(許可されているログアウトURL)]**フィールドに追加される必要があります。このフィールドが設定されていない場合、ユーザーはアプリケーションからログアウトできず、エラーが返されます。 - - - このページの上部からダウンロードしたサンプルプロジェクトに沿って進めている場合には、**[Allowed Logout - URLs(許可されているログアウトURL)]**フィールドに追加する必要があるログアウトURLは`http://localhost:3000`です。 - - - ### 許可されているWebオリジンを構成する - - アプリのURLを[アプリケーションの設定](https://manage.auth0.com/#/applications/%7ByourClientId%7D/settings)で**[Allowed Web - Origins(許可されているWebオリジン)]**フィールドに追加する必要があります。ここでアプリケーションURLを登録しないと、アプリケーションは認証トークンを暗黙でリフレッシュできず、ユーザーがアプリケーションを再び訪問した時、またはページを再読み込みした時にログアウトした状態になってしまいます。 - - - このページの上部からダウンロードしたサンプルプロジェクトに沿って進めている場合には、**[Allowed Web - Origins(許可されているWebオリジン)]**を`http://localhost:3000`に設定します。 - -
    - -
    - Auth0 Flutter SDKをプロジェクトに追加します: - - ```bash - flutter pub add auth0_flutter - ``` - - 以下のスクリプトタグを`index.html`ページに追加します: - - ```html - - ``` -
    - -
    - アプリに認証をセットアップするには、[ユニバーサルログイン](/docs/ja-jp/authenticate/login/auth0-universal-login)が最も手軽な方法です。最良のエクスペリエンス、高い安全性、幅広い機能を活用するためにも、ユニバーサルログインの使用をお勧めします。 - - `Auth0Web`クラスを使用して、Auth0のユニバーサルログインをFlutter - Webアプリに統合します。`loginWithRedirect()`を使用して、ユーザーをAuth0のユニバーサルログインページにリダイレクトします。 - - - 通常、`redirectUrl`パラメーターを`loginWithRedirect`に指定する必要があります。この操作を省くと、Auth0はデフォルトで構成されていない、[デフォルトのログインルート](/docs/ja-jp/authenticate/login/auth0-universal-login/configure-default-login-routes)を使用することになります。 - - - ユーザーはログインすると、リダイレクトでアプリケーションに戻されます。次に、起動中に`onLoad`を呼び出し、付与された資格情報を処理することで、このユーザーのIDとアクセストークンにアクセスすることができます。 - - ```js - auth0.onLoad().then((final credentials) => setState(() { - // Handle or store credentials here - - _credentials = credentials; - - })); - ``` - - - ##### チェックポイント - - `loginWithRedirect()`を呼び出してアプリにユーザーをログインするボタンをアプリに追加します。認証のためにAuth0へリダイレクトされてから、アプリケーションに戻されることを確認します。 - - `onLoad`を呼び出した結果、`credentials`にアクセスできることと、IDとアクセストークンにアクセスできることを確認します。 - -
    - -
    - ユーザーをログアウトさせるには、Auth0 Flutter SDKの`logout()`を呼び出してログインセッションをクリアし、ユーザーをAuth0のログアウトエンドポイントにリダイレクトします。[Auth0からのログアウトについて詳しい情報をお読みください](/docs/ja-jp/authenticate/login/logout)。 - - - 通常、`logout`を呼び出すときに`returnToUrl`を指定しますが、そうしない場合、Auth0は [[Allowed Logout URLs(許可されているログアウトURL)]リストの最初のURLにデフォルトで指定されます](/docs/ja-jp/authenticate/login/logout/redirect-users-after-logout)。 - - - - ##### チェックポイント - - `logout()`を呼び出し、ユーザーをアプリケーションからログアウトするアプリにボタンを追加します。このボタンを選択すると、Flutterアプリがログアウトエンドポイントにリダイレクトしてからもう一度戻ることを確認します。アプリケーションにはログインされていないはずです。 - -
    - -
    - ユーザープロファイルは、ページが読み込まれるとユーザープロファイルプロパティを自動的に取得し、アプリケーション起動中に`onLoad`を呼び出すことでアクセス・保存することができます。`onLoad`から返されたオブジェクトには、すべてのユーザープロファイルプロパティのある`user`プロパティが含まれています。これらはIDトークンをデコードすることで内部で入力されます。 - - - ##### チェックポイント - - ログインして、結果の`user`プロパティを調査します。`email`や`name`など、現在のユーザーのプロファイル情報を確認します。 - -
    - - ## 次のステップ - - 成功です!ここまで来れば、アプリケーションにログイン、ログアウト、ユーザープロファイル情報が備わっているはずです。 - - これでクイックスタートチュートリアルは終了ですが、機能はまだまだたくさんあります。Auth0でできることについて詳しくは、以下をご覧ください。 - - * [Auth0 Dashboard](https://manage.auth0.com/#) - Auth0のテナントやアプリケーションを構成して管理する方法について説明します - * [auth0-flutter SDK](https://www.github.com/auth0/auth0-flutter/) - このチュートリアルで使用されているSDKをより詳しく説明します - * [Auth0 Marketplace](https://marketplace.auth0.com/) - Auth0の機能性を拡張できる各種の統合を見つけられます - * [Configure other identity providers](/docs/ja-jp/identityproviders) - * [Enable multifactor authentication](/docs/ja-jp/multifactor-authentication) - * [Learn about attack protection](/docs/ja-jp/attack-protection) - * [Learn about Actions](/docs/ja-jp/customize/actions) -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    +--- +title: "Flutterアプリケーションにログインを追加する" +permalink: "interactive" +'description': "このガイドでは、FlutterアプリケーションにAuth0 Flutter SDKを使ってAuth0を統合する方法を説明します。" +'og:title': "Flutterアプリケーションにログインを追加する" +'og:description': "このガイドでは、FlutterアプリケーションにAuth0 Flutter SDKを使ってAuth0を統合する方法を説明します。" +'og:image': "https://cdn2.auth0.com/docs/1.14567.0/img/share-image.png" +'twitter:title': "Flutterアプリケーションにログインを追加する" +'twitter:description': "このガイドでは、FlutterアプリケーションにAuth0 Flutter SDKを使ってAuth0を統合する方法を説明します。" +sidebarTitle: Flutter +mode: wide +--- + +import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; +import { LoggedInForm } from "/snippets/Login.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + +import MainView from "/snippets/quickstart/spa/flutter/main_view.mdx" +import ProfileView from "/snippets/quickstart/spa/flutter/profile_view.mdx" + +export const sections = [ + { id: "auth0を構成する", title: "Auth0を構成する" }, + { id: "auth0-flutter-sdkをインストールする", title: "Auth0 Flutter SDKをインストールする" }, + { id: "アプリケーションにログインを追加する", title: "アプリケーションにログインを追加する" }, + { id: "アプリケーションにログアウトを追加する", title: "アプリケーションにログアウトを追加する" }, + { id: "ユーザープロファイル情報を表示する", title: "ユーザープロファイル情報を表示する" } +] + + + + Auth0を使用すると、アプリケーションに手軽に認証を追加して、ユーザープロファイル情報にアクセスすることができます。このガイドでは、Flutterアプリケーションに[Auth0 Flutter + SDK](https://github.com/auth0/auth0-flutter)を使ってAuth0を統合する方法を説明します。 + + + Flutter SDKは現在、Android、iOS、またはWebプラットフォームで実行されるFlutterアプリケーションのみに対応しています。 + + + このクイックスタートでは、すでに[Flutter](https://flutter.dev/)アプリケーションが問題なく作動しているものとします。そうでない場合は、[Flutter「入門」ガイド](https://docs.flutter.dev/get-started/install)をチェックして、シンプルなアプリの始め方を確認してください。 + + [Flutterコマンドラインツール](https://docs.flutter.dev/reference/flutter-cli)の知識も必要になります。 + +
    + Auth0にサインアップすると、新しいアプリケーションが作成されたか、あるいは既に作成していた可能性があります。Auth0と通信するためのアプリケーションに関する詳細が必要になります。これらの詳細は、Auth0 + Dashboardの[アプリケーションの設定](https://manage.auth0.com/#/applications)セクションで入手することができます。 + + + + + + + ネイティブまたはシングルページアプリケーションでデフォルトのアプリを使用する場合は、**[Token Endpoint Authentication + Method(トークンエンドポイント認証方法)]**を`None`に更新し、** [Application + Type(アプリケーションタイプ)]**を`SPA`または`Native`に設定していることを確認します。 + + + 必要な情報は以下のとおりです。 + + - **Domain(ドメイン)** + - **Client ID(クライアントID)** + + + このページの上部からサンプルをダウンロードする場合、これらの詳細は入力されています。 + + + ### Callback URLを構成する + + Callback URLとは、Auth0によって認証後のユーザーをリダイレクトするアプリケーション内URLです。アプリのCallback URLは、[アプリケーションの設定](https://manage.auth0.com/#/applications)で**[Allowed Callback + URLs(許可されているコールバックURL)]**フィールドに追加される必要があります。このフィールドが設定されていない場合、ユーザーはアプリケーションにログインできず、エラーが返されます。 + + + このページの上部からダウンロードしたサンプルプロジェクトに沿って進めている場合には、**[Allowed Callback + URLs(許可されているコールバックURL)]**に`http://localhost:3000`を設定します。 + + + ### ログアウトURLを構成する + + ログアウトURLとは、ユーザーが認可サーバーからログアウトした後にAuth0が戻ることができるアプリケーション内URLです。これは、`returnTo`クエリパラメーターで指定されています。アプリのログアウトURLは、[アプリケーションの設定](https://manage.auth0.com/#/applications)で**[Allowed Logout + URLs(許可されているログアウトURL)]**フィールドに追加される必要があります。このフィールドが設定されていない場合、ユーザーはアプリケーションからログアウトできず、エラーが返されます。 + + + このページの上部からダウンロードしたサンプルプロジェクトに沿って進めている場合には、**[Allowed Logout + URLs(許可されているログアウトURL)]**フィールドに追加する必要があるログアウトURLは`http://localhost:3000`です。 + + + ### 許可されているWebオリジンを構成する + + アプリのURLを[アプリケーションの設定](https://manage.auth0.com/#/applications/%7ByourClientId%7D/settings)で**[Allowed Web + Origins(許可されているWebオリジン)]**フィールドに追加する必要があります。ここでアプリケーションURLを登録しないと、アプリケーションは認証トークンを暗黙でリフレッシュできず、ユーザーがアプリケーションを再び訪問した時、またはページを再読み込みした時にログアウトした状態になってしまいます。 + + + このページの上部からダウンロードしたサンプルプロジェクトに沿って進めている場合には、**[Allowed Web + Origins(許可されているWebオリジン)]**を`http://localhost:3000`に設定します。 + +
    + +
    + Auth0 Flutter SDKをプロジェクトに追加します: + + ```bash + flutter pub add auth0_flutter + ``` + + 以下のスクリプトタグを`index.html`ページに追加します: + + ```html + + ``` +
    + +
    + アプリに認証をセットアップするには、[ユニバーサルログイン](/docs/ja-jp/authenticate/login/auth0-universal-login)が最も手軽な方法です。最良のエクスペリエンス、高い安全性、幅広い機能を活用するためにも、ユニバーサルログインの使用をお勧めします。 + + `Auth0Web`クラスを使用して、Auth0のユニバーサルログインをFlutter + Webアプリに統合します。`loginWithRedirect()`を使用して、ユーザーをAuth0のユニバーサルログインページにリダイレクトします。 + + + 通常、`redirectUrl`パラメーターを`loginWithRedirect`に指定する必要があります。この操作を省くと、Auth0はデフォルトで構成されていない、[デフォルトのログインルート](/docs/ja-jp/authenticate/login/auth0-universal-login/configure-default-login-routes)を使用することになります。 + + + ユーザーはログインすると、リダイレクトでアプリケーションに戻されます。次に、起動中に`onLoad`を呼び出し、付与された資格情報を処理することで、このユーザーのIDとアクセストークンにアクセスすることができます。 + + ```js + auth0.onLoad().then((final credentials) => setState(() { + // Handle or store credentials here + + _credentials = credentials; + + })); + ``` + + + ##### チェックポイント + + `loginWithRedirect()`を呼び出してアプリにユーザーをログインするボタンをアプリに追加します。認証のためにAuth0へリダイレクトされてから、アプリケーションに戻されることを確認します。 + + `onLoad`を呼び出した結果、`credentials`にアクセスできることと、IDとアクセストークンにアクセスできることを確認します。 + +
    + +
    + ユーザーをログアウトさせるには、Auth0 Flutter SDKの`logout()`を呼び出してログインセッションをクリアし、ユーザーをAuth0のログアウトエンドポイントにリダイレクトします。[Auth0からのログアウトについて詳しい情報をお読みください](/docs/ja-jp/authenticate/login/logout)。 + + + 通常、`logout`を呼び出すときに`returnToUrl`を指定しますが、そうしない場合、Auth0は [[Allowed Logout URLs(許可されているログアウトURL)]リストの最初のURLにデフォルトで指定されます](/docs/ja-jp/authenticate/login/logout/redirect-users-after-logout)。 + + + + ##### チェックポイント + + `logout()`を呼び出し、ユーザーをアプリケーションからログアウトするアプリにボタンを追加します。このボタンを選択すると、Flutterアプリがログアウトエンドポイントにリダイレクトしてからもう一度戻ることを確認します。アプリケーションにはログインされていないはずです。 + +
    + +
    + ユーザープロファイルは、ページが読み込まれるとユーザープロファイルプロパティを自動的に取得し、アプリケーション起動中に`onLoad`を呼び出すことでアクセス・保存することができます。`onLoad`から返されたオブジェクトには、すべてのユーザープロファイルプロパティのある`user`プロパティが含まれています。これらはIDトークンをデコードすることで内部で入力されます。 + + + ##### チェックポイント + + ログインして、結果の`user`プロパティを調査します。`email`や`name`など、現在のユーザーのプロファイル情報を確認します。 + +
    + + ## 次のステップ + + 成功です!ここまで来れば、アプリケーションにログイン、ログアウト、ユーザープロファイル情報が備わっているはずです。 + + これでクイックスタートチュートリアルは終了ですが、機能はまだまだたくさんあります。Auth0でできることについて詳しくは、以下をご覧ください。 + + * [Auth0 Dashboard](https://manage.auth0.com/#) - Auth0のテナントやアプリケーションを構成して管理する方法について説明します + * [auth0-flutter SDK](https://www.github.com/auth0/auth0-flutter/) - このチュートリアルで使用されているSDKをより詳しく説明します + * [Auth0 Marketplace](https://marketplace.auth0.com/) - Auth0の機能性を拡張できる各種の統合を見つけられます + * [Configure other identity providers](/docs/ja-jp/identityproviders) + * [Enable multifactor authentication](/docs/ja-jp/multifactor-authentication) + * [Learn about attack protection](/docs/ja-jp/attack-protection) + * [Learn about Actions](/docs/ja-jp/customize/actions) +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    diff --git a/main/docs/ja-jp/quickstart/spa/react/interactive.mdx b/main/docs/ja-jp/quickstart/spa/react/interactive.mdx index 1be860140..c6581523d 100644 --- a/main/docs/ja-jp/quickstart/spa/react/interactive.mdx +++ b/main/docs/ja-jp/quickstart/spa/react/interactive.mdx @@ -1,227 +1,229 @@ ---- -title: "Reactアプリケーションにログインを追加する" -permalink: "interactive" -'description': "このガイドは、新規または既存のReactアプリケーションにAuth0 React SDKを使ってAuth0を統合する方法を説明します。" -'og:title': "Reactアプリケーションにログインを追加する" -'og:description': "このガイドは、新規または既存のReactアプリケーションにAuth0 React SDKを使ってAuth0を統合する方法を説明します。" -'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/react.png" -'twitter:title': "Reactアプリケーションにログインを追加する" -'twitter:description': "このガイドは、新規または既存のReactアプリケーションにAuth0 React SDKを使ってAuth0を統合する方法を説明します。" -mode: wide -sidebarTitle: React ---- - -import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; -import { LoggedInForm } from "/snippets/Login.jsx"; -import Index from "/snippets/quickstart/spa/react/index.mdx"; -import Login from "/snippets/quickstart/spa/react/login.mdx"; -import Logout from "/snippets/quickstart/spa/react/logout.mdx"; -import Profile from "/snippets/quickstart/spa/react/profile.mdx"; - -export const sections = [ - { id: "auth0を構成する", title: "Auth0を構成する" }, - { id: "auth0-react-sdkをインストールする", title: "Auth0 React SDKをインストールする" }, - { id: "アプリケーションにログインを追加する", title: "アプリケーションにログインを追加する" }, - { id: "アプリケーションにログアウトを追加する", title: "アプリケーションにログアウトを追加する" }, - { id: "ユーザープロファイル情報を表示する", title: "ユーザープロファイル情報を表示する" } -] - - - - Auth0を使用すると、アプリケーションに手軽に認証を追加することができます。このガイドは、ReactアプリケーションにAuth0 React - SDKを使ってAuth0を統合し、認証の追加とユーザープロファイル情報の表示を行う方法について説明します。 - - このクイックスタートを使用するには、以下の手順に従います: - - - Reactでユーザー認証を実装するための詳しい情報については、[例を挙げて説明するReact認証ガイド](https://developer.auth0.com/resources/guides/spa/react/basic-authentication)を参照してください。このガイドでは、サインアップボタンを作成する方法、React - Routerを使用してルートガードを追加する方法、そして保護されたAPIをReactから呼び出す方法が詳しく説明されています。 - - -
    - Auth0のサービスを利用するには、Auth0 Dashboadに設定済みのアプリケーションがある必要があります。Auth0アプリケーションは、開発中のプロジェクトに対してどのように認証が動作して欲しいかを構成する場所です。 - - ### アプリケーションを構成する - - 対話型のセレクターを使ってAuth0アプリケーションを新規作成するか、統合したいプロジェクトを表す既存のアプリケーションを選択します。Auth0のすべてのアプリケーションには英数字からなる一意のクライアントIDが割り当てられており、アプリケーションのコードがSDKを通じてAuth0 - APIを呼び出す際に使用されます。 - - このクイックスタートを使って構成されたすべての設定は、[Dashboard](https://manage.auth0.com/#/)のアプリケーションを自動更新します。今後、アプリケーションの管理もDashboardで行えます。 - - 完了済みの構成を見てみたい場合は、サンプルアプリケーションをご覧ください。 - - ### Callback URLを構成する - - Callback URLとは、Auth0がユーザーを認証後にリダイレクトするアプリケーション内URLです。設定されていない場合、ユーザーはログイン後にアプリケーションに戻りません。 - - - サンプルプロジェクトに沿って進めている場合は、`http://localhost:3000`に設定してください。 - - - ### ログアウトURLを構成する - - ログアウトURLとは、Auth0がユーザーをログアウト後にリダイレクトするアプリケーション内URLです。設定されていない場合、ユーザーはアプリケーションからログアウトできず、エラーを受け取ります。 - - - サンプルプロジェクトに沿って進めている場合は、`http://localhost:3000`に設定してください。 - - - ### Allowed Web Origins(許可されているWebオリジン)を構成する - - Allowed Web - Origin(許可されているWebオリジン)とは、認証フローへのアクセスを許可されるURLです。これにはプロジェクトのURLが含まれている必要があります。適切に設定されていない場合、プロジェクトが認証トークンを暗黙でリフレッシュできず、ユーザーがアプリケーションを再び訪問した時、またはページを再読み込みした時にログアウトした状態になってしまいます。 - - - サンプルプロジェクトに沿って進めている場合は、`http://localhost:3000`に設定してください。 - -
    - -
    - Reactアプリで、Auth0の認証・認可を手軽に実装できるように、Auth0は[React SDK](https://github.com/auth0/auth0-react)(auth0-react.js)を提供しています。 - - ターミナルで以下のコマンドを実行してAuth0 React SDKをインストールします: - - ```bash - cd - npm install @auth0/auth0-react - ``` - - ### Auth0Providerコンポーネントを構成する - - SDKが正しく機能するためには、次のプロパティをAuth0Providerコンポーネントで設定しなければなりません: - - - `domain`:Auth0テナントのドメインです。通常、Auth0 Dashboardにあるアプリケーションの設定の[Domain(ドメイン)]フィールドで確認できます。[カスタムドメイン](/docs/ja-jp/custom-domains)を使用している場合は、その値を代わりに設定してください。 - - `clientId`:このクイックスタートで前にセットアップした、Auth0アプリケーションのIDです。Auth0 Dashboardにあるアプリケーションの設定の[Client - ID(クライアントID)]フィールドで確認できます。 - - `authorizationParams.redirect_uri`:ユーザー認証の後、Auth0にユーザーをリダイレクトして欲しいアプリケーション内URLです。このクイックスタートで前にセットアップしたCallback - URLと呼応します。Auth0 Dashboardにあるアプリケーションの[Settings(設定)]の[Callback - URLs(コールバックURL)]フィールドでもこの値を確認できます。コードに入力した値と前にセットアップした値は必ず一致させてください。異なった場合はユーザーにエラーが表示されます。 - - - ##### チェックポイント - - Auth0Providerコンポーネントが適切に構成されました。アプリケーションを実行して次の点を検証します: - - - SDKが正しく初期化している。 - - アプリケーションがAuth0に関連したエラーを投入していない。 - -
    - -
    - Auth0アプリケーションとAuth0 React - SDKの構成が完了したら、プロジェクトのためにログインをセットアップする必要があります。これを実現するには、SDKのloginWithRedirect()メソッドを使用して、ユーザをAuth0のユニバーサルログインページにリダイレクトするログインボタンを作成します。ユーザーが認証に成功すると、このクイックスタートで前にセットアップしたCallback - URLへリダイレクトされます。 - - - このガイドでは`useAuth0()`のカスタムReactフックに焦点を当てています。クラスコンポーネントを使用している場合は、[withAuth0()を使用したこちらのサンプル](https://github.com/auth0/auth0-react/blob/master/EXAMPLES.md#use-with-a-class-component)を確認してください。 - - - ログインボタンコンポーネントのためにアプリケーションで`login.js`という名前の新規ファイルを作成し、インタラクティブパネルから右へとコードにコピーします。これにはログインに必要なロジックが含まれています。それから`index.js`ファイルを更新して新しいログインボタンを含めます。 - - - ##### チェックポイント - - ユーザー名とパスワードを使ってログインやサインアップができるようになりました。 - - ログインボタンをクリックして次の点を検証します: - - - ReactアプリケーションによってAuth0ユニバーサルログインページにリダイレクトされる。 - - ログインまたはサインアップできる。 - - Auth0が、`Auth0Provider`を構成するために使った`authorizationParams.redirect_uri`の値を使用し、アプリケーションへリダイレクトする。 - -
    - -
    - プロジェクトにログインしたユーザーには、ログアウトする方法も必要です。SDKのlogout()メソッドを使用してログアウトボタンを作成します。ユーザーはログアウトすると、[Auth0ログアウト](https://auth0.com/docs/api/authentication?javascript#logout)エンドポイントにリダイレクトされてから、即座に、このクイックスタートで先ほどセットアップしたログアウトURLにリダイレクトで戻されます。 - - ログアウトボタンコンポーネントのためにアプリケーションで`logout.js`という名前の新規ファイルを作成し、インタラクティブパネルからコードにコピーします。これにはログアウトに必要なロジックが含まれています。それから`index.js`ファイルを更新して新しいログアウトボタンを含めます。 - - - ##### チェックポイント - - アプリケーションを実行してログアウトボタンをクリックし、次の点を検証します: - - - Reactアプリケーションによって、アプリケーションの設定で[Allowed Logout URLs(許可されているログアウトURL)]の一つに指定したアドレスへリダイレクトされる。 - - アプリケーションにログインしていない。 - -
    - -
    - ユーザーがログインやログアウトできるようになったら、認証済のユーザーに関連付けられた[プロファイル情報](/docs/ja-jp/users/concepts/overview-user-profile)を取得できるようにしたいと考えるはずです。たとえば、ログインしたユーザーの名前やプロファイル画像をプロジェクトに表示できるようになりたいかもしれません。 - - React用のAuth0 - SDKでは、`user`プロパティを通じてユーザー情報を提供します。インタラクティブパネルで`profile.js`コードを確認し、使用方法の例をチェックします。 - - `user`プロパティにはユーザーのアイデンティティに関する機密情報が含まれるため、この方法が使用できるかはユーザーの認証ステータスによります。エラーを防ぐため、常に以下を行ってください: - - - Reactが`user`プロパティを使用するコンポーネントを呼び出す前に、`isAuthenticated`プロパティを使用してAuth0がユーザーを認証したかどうかを定義する。 - - `isAuthenticated`プロパティにアクセスする前に、`isLoading`がfalseであることをチェックして、SDKの読み込みが完了したことを確認する。 - - - - - - - - ##### チェックポイント - - 以下の点を確認します: - - - ログイン後、コンポーネント内の`user.name`やその他のユーザープロパティをすべて正しく表示できる。 - -
    - - ## 次のステップ - -成功です!ここまで来れば、アプリケーションにログイン、ログアウト、ユーザープロファイル情報が備わっているはずです。 - -これでクイックスタートチュートリアルは終了ですが、機能はまだまだたくさんあります。Auth0でできることについて詳しくは、以下をご覧ください。 - -* [Auth0 Dashboard](https://manage.auth0.com/#) - Auth0のテナントやアプリケーションを構成して管理する方法について説明します -* [auth0-react SDK](https://www.github.com/auth0/auth0-react/) - このチュートリアルで使用されているSDKをより詳しく説明します -* [Auth0 Marketplace](https://marketplace.auth0.com/) - Auth0の機能性を拡張できる各種の統合を見つけられます -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    +--- +title: "Reactアプリケーションにログインを追加する" +permalink: "interactive" +'description': "このガイドは、新規または既存のReactアプリケーションにAuth0 React SDKを使ってAuth0を統合する方法を説明します。" +'og:title': "Reactアプリケーションにログインを追加する" +'og:description': "このガイドは、新規または既存のReactアプリケーションにAuth0 React SDKを使ってAuth0を統合する方法を説明します。" +'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/react.png" +'twitter:title': "Reactアプリケーションにログインを追加する" +'twitter:description': "このガイドは、新規または既存のReactアプリケーションにAuth0 React SDKを使ってAuth0を統合する方法を説明します。" +mode: wide +sidebarTitle: React +--- + +import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; +import { LoggedInForm } from "/snippets/Login.jsx"; +import Index from "/snippets/quickstart/spa/react/index.mdx"; +import Login from "/snippets/quickstart/spa/react/login.mdx"; +import Logout from "/snippets/quickstart/spa/react/logout.mdx"; +import Profile from "/snippets/quickstart/spa/react/profile.mdx"; + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + +export const sections = [ + { id: "auth0を構成する", title: "Auth0を構成する" }, + { id: "auth0-react-sdkをインストールする", title: "Auth0 React SDKをインストールする" }, + { id: "アプリケーションにログインを追加する", title: "アプリケーションにログインを追加する" }, + { id: "アプリケーションにログアウトを追加する", title: "アプリケーションにログアウトを追加する" }, + { id: "ユーザープロファイル情報を表示する", title: "ユーザープロファイル情報を表示する" } +] + + + + Auth0を使用すると、アプリケーションに手軽に認証を追加することができます。このガイドは、ReactアプリケーションにAuth0 React + SDKを使ってAuth0を統合し、認証の追加とユーザープロファイル情報の表示を行う方法について説明します。 + + このクイックスタートを使用するには、以下の手順に従います: + + + Reactでユーザー認証を実装するための詳しい情報については、[例を挙げて説明するReact認証ガイド](https://developer.auth0.com/resources/guides/spa/react/basic-authentication)を参照してください。このガイドでは、サインアップボタンを作成する方法、React + Routerを使用してルートガードを追加する方法、そして保護されたAPIをReactから呼び出す方法が詳しく説明されています。 + + +
    + Auth0のサービスを利用するには、Auth0 Dashboadに設定済みのアプリケーションがある必要があります。Auth0アプリケーションは、開発中のプロジェクトに対してどのように認証が動作して欲しいかを構成する場所です。 + + ### アプリケーションを構成する + + 対話型のセレクターを使ってAuth0アプリケーションを新規作成するか、統合したいプロジェクトを表す既存のアプリケーションを選択します。Auth0のすべてのアプリケーションには英数字からなる一意のクライアントIDが割り当てられており、アプリケーションのコードがSDKを通じてAuth0 + APIを呼び出す際に使用されます。 + + このクイックスタートを使って構成されたすべての設定は、[Dashboard](https://manage.auth0.com/#/)のアプリケーションを自動更新します。今後、アプリケーションの管理もDashboardで行えます。 + + 完了済みの構成を見てみたい場合は、サンプルアプリケーションをご覧ください。 + + ### Callback URLを構成する + + Callback URLとは、Auth0がユーザーを認証後にリダイレクトするアプリケーション内URLです。設定されていない場合、ユーザーはログイン後にアプリケーションに戻りません。 + + + サンプルプロジェクトに沿って進めている場合は、`http://localhost:3000`に設定してください。 + + + ### ログアウトURLを構成する + + ログアウトURLとは、Auth0がユーザーをログアウト後にリダイレクトするアプリケーション内URLです。設定されていない場合、ユーザーはアプリケーションからログアウトできず、エラーを受け取ります。 + + + サンプルプロジェクトに沿って進めている場合は、`http://localhost:3000`に設定してください。 + + + ### Allowed Web Origins(許可されているWebオリジン)を構成する + + Allowed Web + Origin(許可されているWebオリジン)とは、認証フローへのアクセスを許可されるURLです。これにはプロジェクトのURLが含まれている必要があります。適切に設定されていない場合、プロジェクトが認証トークンを暗黙でリフレッシュできず、ユーザーがアプリケーションを再び訪問した時、またはページを再読み込みした時にログアウトした状態になってしまいます。 + + + サンプルプロジェクトに沿って進めている場合は、`http://localhost:3000`に設定してください。 + +
    + +
    + Reactアプリで、Auth0の認証・認可を手軽に実装できるように、Auth0は[React SDK](https://github.com/auth0/auth0-react)(auth0-react.js)を提供しています。 + + ターミナルで以下のコマンドを実行してAuth0 React SDKをインストールします: + + ```bash + cd + npm install @auth0/auth0-react + ``` + + ### Auth0Providerコンポーネントを構成する + + SDKが正しく機能するためには、次のプロパティをAuth0Providerコンポーネントで設定しなければなりません: + + - `domain`:Auth0テナントのドメインです。通常、Auth0 Dashboardにあるアプリケーションの設定の[Domain(ドメイン)]フィールドで確認できます。[カスタムドメイン](/docs/ja-jp/custom-domains)を使用している場合は、その値を代わりに設定してください。 + - `clientId`:このクイックスタートで前にセットアップした、Auth0アプリケーションのIDです。Auth0 Dashboardにあるアプリケーションの設定の[Client + ID(クライアントID)]フィールドで確認できます。 + - `authorizationParams.redirect_uri`:ユーザー認証の後、Auth0にユーザーをリダイレクトして欲しいアプリケーション内URLです。このクイックスタートで前にセットアップしたCallback + URLと呼応します。Auth0 Dashboardにあるアプリケーションの[Settings(設定)]の[Callback + URLs(コールバックURL)]フィールドでもこの値を確認できます。コードに入力した値と前にセットアップした値は必ず一致させてください。異なった場合はユーザーにエラーが表示されます。 + + + ##### チェックポイント + + Auth0Providerコンポーネントが適切に構成されました。アプリケーションを実行して次の点を検証します: + + - SDKが正しく初期化している。 + - アプリケーションがAuth0に関連したエラーを投入していない。 + +
    + +
    + Auth0アプリケーションとAuth0 React + SDKの構成が完了したら、プロジェクトのためにログインをセットアップする必要があります。これを実現するには、SDKのloginWithRedirect()メソッドを使用して、ユーザをAuth0のユニバーサルログインページにリダイレクトするログインボタンを作成します。ユーザーが認証に成功すると、このクイックスタートで前にセットアップしたCallback + URLへリダイレクトされます。 + + + このガイドでは`useAuth0()`のカスタムReactフックに焦点を当てています。クラスコンポーネントを使用している場合は、[withAuth0()を使用したこちらのサンプル](https://github.com/auth0/auth0-react/blob/master/EXAMPLES.md#use-with-a-class-component)を確認してください。 + + + ログインボタンコンポーネントのためにアプリケーションで`login.js`という名前の新規ファイルを作成し、インタラクティブパネルから右へとコードにコピーします。これにはログインに必要なロジックが含まれています。それから`index.js`ファイルを更新して新しいログインボタンを含めます。 + + + ##### チェックポイント + + ユーザー名とパスワードを使ってログインやサインアップができるようになりました。 + + ログインボタンをクリックして次の点を検証します: + + - ReactアプリケーションによってAuth0ユニバーサルログインページにリダイレクトされる。 + - ログインまたはサインアップできる。 + - Auth0が、`Auth0Provider`を構成するために使った`authorizationParams.redirect_uri`の値を使用し、アプリケーションへリダイレクトする。 + +
    + +
    + プロジェクトにログインしたユーザーには、ログアウトする方法も必要です。SDKのlogout()メソッドを使用してログアウトボタンを作成します。ユーザーはログアウトすると、[Auth0ログアウト](https://auth0.com/docs/api/authentication?javascript#logout)エンドポイントにリダイレクトされてから、即座に、このクイックスタートで先ほどセットアップしたログアウトURLにリダイレクトで戻されます。 + + ログアウトボタンコンポーネントのためにアプリケーションで`logout.js`という名前の新規ファイルを作成し、インタラクティブパネルからコードにコピーします。これにはログアウトに必要なロジックが含まれています。それから`index.js`ファイルを更新して新しいログアウトボタンを含めます。 + + + ##### チェックポイント + + アプリケーションを実行してログアウトボタンをクリックし、次の点を検証します: + + - Reactアプリケーションによって、アプリケーションの設定で[Allowed Logout URLs(許可されているログアウトURL)]の一つに指定したアドレスへリダイレクトされる。 + - アプリケーションにログインしていない。 + +
    + +
    + ユーザーがログインやログアウトできるようになったら、認証済のユーザーに関連付けられた[プロファイル情報](/docs/ja-jp/users/concepts/overview-user-profile)を取得できるようにしたいと考えるはずです。たとえば、ログインしたユーザーの名前やプロファイル画像をプロジェクトに表示できるようになりたいかもしれません。 + + React用のAuth0 + SDKでは、`user`プロパティを通じてユーザー情報を提供します。インタラクティブパネルで`profile.js`コードを確認し、使用方法の例をチェックします。 + + `user`プロパティにはユーザーのアイデンティティに関する機密情報が含まれるため、この方法が使用できるかはユーザーの認証ステータスによります。エラーを防ぐため、常に以下を行ってください: + + - Reactが`user`プロパティを使用するコンポーネントを呼び出す前に、`isAuthenticated`プロパティを使用してAuth0がユーザーを認証したかどうかを定義する。 + - `isAuthenticated`プロパティにアクセスする前に、`isLoading`がfalseであることをチェックして、SDKの読み込みが完了したことを確認する。 + + + + + + + + ##### チェックポイント + + 以下の点を確認します: + + - ログイン後、コンポーネント内の`user.name`やその他のユーザープロパティをすべて正しく表示できる。 + +
    + + ## 次のステップ + +成功です!ここまで来れば、アプリケーションにログイン、ログアウト、ユーザープロファイル情報が備わっているはずです。 + +これでクイックスタートチュートリアルは終了ですが、機能はまだまだたくさんあります。Auth0でできることについて詳しくは、以下をご覧ください。 + +* [Auth0 Dashboard](https://manage.auth0.com/#) - Auth0のテナントやアプリケーションを構成して管理する方法について説明します +* [auth0-react SDK](https://www.github.com/auth0/auth0-react/) - このチュートリアルで使用されているSDKをより詳しく説明します +* [Auth0 Marketplace](https://marketplace.auth0.com/) - Auth0の機能性を拡張できる各種の統合を見つけられます +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    diff --git a/main/docs/ja-jp/quickstart/spa/vuejs/interactive.mdx b/main/docs/ja-jp/quickstart/spa/vuejs/interactive.mdx index 2b0ce12a8..ed33c8e2c 100644 --- a/main/docs/ja-jp/quickstart/spa/vuejs/interactive.mdx +++ b/main/docs/ja-jp/quickstart/spa/vuejs/interactive.mdx @@ -1,229 +1,231 @@ ---- -title: "Vueアプリケーションにログインを追加する" -permalink: "interactive" -'description': "このガイドは、VueアプリケーションにAuth0 Vue SDKを使ってAuth0を統合し、認証の追加とユーザープロファイル情報の表示を行う方法について説明します。" -'og:title': "Vueアプリケーションにログインを追加する" -'og:description': "このガイドは、VueアプリケーションにAuth0 Vue SDKを使ってAuth0を統合し、認証の追加とユーザープロファイル情報の表示を行う方法について説明します。" -'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/vue.png" -'twitter:title': "Vueアプリケーションにログインを追加する" -'twitter:description': "このガイドは、VueアプリケーションにAuth0 Vue SDKを使ってAuth0を統合し、認証の追加とユーザープロファイル情報の表示を行う方法について説明します。" -mode: wide -sidebarTitle: Vue JS ---- - -import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; -import { LoggedInForm } from "/snippets/Login.jsx"; -import Index from "/snippets/quickstart/spa/vuejs/index.mdx"; -import Login from "/snippets/quickstart/spa/vuejs/login.mdx"; -import Logout from "/snippets/quickstart/spa/vuejs/logout.mdx"; -import Profile from "/snippets/quickstart/spa/vuejs/profile.mdx"; - -export const sections = [ - { id: "auth0を構成する", title: "Auth0を構成する" }, - { id: "auth0-vue-sdkをインストールする", title: "Auth0 Vue SDKをインストールする" }, - { id: "アプリケーションにログインを追加する", title: "アプリケーションにログインを追加する" }, - { id: "アプリケーションにログアウトを追加する", title: "アプリケーションにログアウトを追加する" }, - { id: "ユーザープロファイル情報を表示する", title: "ユーザープロファイル情報を表示する" } -] - - - - Auth0を使用すると、アプリケーションに認証を追加することができます。このガイドは、VueアプリケーションにAuth0 Vue - SDKを使ってAuth0を統合し、認証の追加とユーザープロファイル情報の表示を行う方法について説明します。 - - - このクイックスタートは、Vue 3アプリケーションで[Auth0 Vue](https://github.com/auth0/auth0-vue)を使用するために設計されています。Vue 2を使用している場合は、[Auth0 SPA SDKを使ったVue 2チュートリアル](https://github.com/auth0/auth0-vue/blob/main/tutorial/vue2-login.md)を確認するか、「[例を挙げて説明するVue.js認証2](https://developer.auth0.com/resources/guides/spa/vue/basic-authentication/v2-javascript)」ガイドを参照してください。 - - - このクイックスタートを使用するには、以下の手順に従います: - -
    - Auth0のサービスを利用するには、Auth0 Dashboadに設定済みのアプリケーションがある必要があります。Auth0アプリケーションは、開発中のプロジェクトに対してどのように認証が動作して欲しいかを構成する場所です。 - - ### アプリケーションを構成する - - 対話型のセレクターを使ってAuth0アプリケーションを新規作成するか、統合したいプロジェクトを表す既存のアプリケーションを選択します。Auth0のすべてのアプリケーションには英数字からなる一意のクライアントIDが割り当てられており、アプリケーションのコードがSDKを通じてAuth0 - APIを呼び出す際に使用されます。 - - このクイックスタートを使って構成されたすべての設定は、[Dashboard](https://manage.auth0.com/dashboard/us/dev-1-2s2aq0/)のアプリケーションを自動更新します。今後、アプリケーションの管理もDashboardで行えます。 - - 代わりに完了済みの構成を見てみたい場合は、サンプルアプリケーションをご覧ください。 - - ### Callback URLを構成する - - Callback URLとは、Auth0がユーザーを認証後にリダイレクトするアプリケーション内URLです。設定されていない場合、ユーザーはログイン後にアプリケーションに戻りません。 - - - サンプルプロジェクトに沿って進めている場合は、`http://localhost:3000`に設定してください。 - - - ### ログアウトURLを構成する - - ログアウトURLとは、Auth0がユーザーをログアウト後にリダイレクトするアプリケーション内URLです。設定されていない場合、ユーザーはアプリケーションからログアウトできず、エラーを受け取ります。 - - - サンプルプロジェクトに沿って進めている場合は、`http://localhost:3000`に設定してください。 - - - ### Allowed Web Origins(許可されているWebオリジン)を構成する - - [Allowed Web - Origin(許可されているWebオリジン)]とは、認証フローにアクセスすることを許可して欲しいURLです。これにはプロジェクトのURLが含まれている必要があります。適切に設定されていない場合、プロジェクトが認証トークンを暗黙でリフレッシュできず、ユーザーがアプリケーションを再び訪問した時、またはページを再読み込みした時にログアウトした状態になってしまいます。 - - - サンプルプロジェクトに沿って進めている場合は、`http://localhost:3000`に設定してください。 - -
    - -
    - Vue 3アプリで、Auth0の認証・認可を手軽に実装できるように、Auth0は[Vue SDK](https://github.com/auth0/auth0-vue)を提供しています。 - - ターミナルで以下のコマンドを実行してAuth0 Vue SDKをインストールします: - - ```bash - cd - npm install @auth0/auth0-vue - ``` - - ### プラグインを登録する - - SDKが機能するには、以下のプロパティを使ってVueアプリケーションでプラグインを登録する必要があります。 - - - `domain`:Auth0テナントのドメインです。この値は、Auth0 - Dashboardにあるアプリケーションの[Settings(設定)]の[Domain(ドメイン)]フィールドにあります。[カスタムドメイン](/docs/ja-jp/custom-domains)を使用している場合は、この値をカスタムドメインの値に設定してください。 - - `clientId`:このクイックスタートで前にセットアップした、Auth0アプリケーションのIDです。Auth0 - Dashboardにあるアプリケーションの[Settings(設定)]の[Client ID(クライアントID)]フィールドで確認してください。 - - `authorizationParams.redirect_uri`:ユーザー認証の後、Auth0にユーザーをリダイレクトして欲しいアプリケーション内URLです。このクイックスタートで前にセットアップしたCallback - URLと呼応します。この値は、Auth0 Dashboardにあるアプリケーションの[Settings(設定)]の[Callback - URLs(コールバックURL)]フィールドにあります。コードに入力した値と前にセットアップした値は必ず一致させてください。異なった場合はユーザーにエラーが表示されます。 - - プラグインは、`provide`と`app.config.globalProperties`の両方を使ってSDKを登録します。これによって、[Composition API](https://vuejs.org/guide/introduction.html#composition-api)と[Options API](https://vuejs.org/guide/introduction.html#options-api)の両方が有効になります。 - - - ##### チェックポイント - - プラグインが構成されました。アプリケーションを実行して次の点を確認します: - - - SDKが正しく初期化している - - アプリケーションがAuth0に関連したエラーを投入していない - -
    - -
    - 次に、プロジェクト用のログインを設定します。`useAuth0`の返り値に表示されたSDKの`loginWithRedirect`関数を使用します。これには、コンポーネントのsetup関数でアクセスすることができます。ユーザーはAuth0ユニバーサルログインページにリダイレクトされ、ユーザーの認証後、このクイックスタートで前に設定したCallback - URLにリダイレクトされます。 - - ### Options APIの使用 - - Options - APIでは、`this`アクセサを通じてグローバル`$auth0`プロパティからの同じ`loginWithRedirect`メソッドを使用することができます。 - - - ##### チェックポイント - - Auth0ユニバーサルログインからログインできるようになります。 - - ログインボタンをクリックして次の点を確認します: - - - VueアプリケーションによってAuth0ユニバーサルログインページにリダイレクトされる - - ログインまたはサインアップできる - - Auth0が、プラグインを構成するために使った`authorizationParams.redirect_uri`の値を使用し、アプリケーションへリダイレクトする。 - -
    - -
    - プロジェクトにログインしたユーザーには、ログアウトする方法も必要です。ユーザーがログアウトすると、アプリケーションによって[Auth0 - logout](https://auth0.com/docs/api/authentication?javascript#logout)エンドポイントにリダイレクトされてから、指定された`logoutParams.returnTo`パラメーターにリダイレクトされます。 - - `useAuth0`の返り値に表示された`logout`関数を使用します。これには、コンポーネントの`setup`関数でアクセスすることができ、ユーザーをアプリケーションからログアウトします。 - - ### Options APIの使用 - - Options APIでは、`this`アクセサを通じてグローバル`$auth0`プロパティからの同じ`logout`メソッドを使用することができます。 - - - ##### チェックポイント - - アプリケーションを実行してログアウトボタンをクリックし、次の点を検証します: - - - Vueアプリケーションによって`logoutParams.returnTo`アドレスにリダイレクトされる - - アプリケーションにログインしていない - -
    - -
    - 次に、認証ユーザーに関連する[プロファイル情報](/docs/ja-jp/users/concepts/overview-user-profile)を取得する方法を構成します。たとえば、ログインしたユーザーの名前やプロフィール写真をプロジェクトに表示したいかもしれません。ユーザーが認証を行うと、SDKはユーザーのプロファイル情報を抽出し、メモリ内に保存します。アプリケーションは、リアクティブな`user`プロパティを使ってユーザープロファイルにアクセスすることができます。このプロパティにアクセスするには、コンポーネントの`setup`関数を確認し、`userAuth0`返り値を見つけます。 - - `user`プロパティには、ユーザーIDに関する機微な情報が含まれています。これは、ユーザーの認証ステータスに基づいてのみ利用できます。エラーを防ぐため、常に以下を行ってください: - - - Vueが`user`プロパティを使用するコンポーネントを呼び出す前に、`isAuthenticated`プロパティを使用してAuth0がユーザーを認証したかどうかを定義する。 - - `isAuthenticated`プロパティにアクセスする前に、`isLoading`がfalseであることをチェックして、SDKの読み込みが完了したことを確認する。 - - ### Options APIの使用 - - Options - APIでは、アクセサ`this`を通じてグローバル`$auth0`プロパティからの同じリアクティブな`user`、`isLoading`、および`isAuthenticated`プロパティを使用します。 - - - ##### チェックポイント - - 以下の点を確認します: - - - ログイン後、コンポーネント内の`user`やその他のユーザープロパティをすべて正しく表示できる - -
    - - ## 次のステップ - - 成功です!ここまで来れば、アプリケーションにログイン、ログアウト、ユーザープロファイル情報が備わっているはずです。 - - これでクイックスタートチュートリアルは終了ですが、機能はまだまだたくさんあります。Auth0でできることについて詳しくは、以下をご覧ください。 - - * [Auth0 Dashboard](https://manage.auth0.com/#) - Auth0のテナントやアプリケーションを構成して管理する方法について説明します - * [auth0-vue SDK](https://www.github.com/auth0/auth0-vue) - このチュートリアルで使用されているSDKをより詳しく説明します - * [Auth0 Marketplace](https://marketplace.auth0.com/) - Auth0の機能性を拡張できる各種の統合を見つけられます -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    +--- +title: "Vueアプリケーションにログインを追加する" +permalink: "interactive" +'description': "このガイドは、VueアプリケーションにAuth0 Vue SDKを使ってAuth0を統合し、認証の追加とユーザープロファイル情報の表示を行う方法について説明します。" +'og:title': "Vueアプリケーションにログインを追加する" +'og:description': "このガイドは、VueアプリケーションにAuth0 Vue SDKを使ってAuth0を統合し、認証の追加とユーザープロファイル情報の表示を行う方法について説明します。" +'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/vue.png" +'twitter:title': "Vueアプリケーションにログインを追加する" +'twitter:description': "このガイドは、VueアプリケーションにAuth0 Vue SDKを使ってAuth0を統合し、認証の追加とユーザープロファイル情報の表示を行う方法について説明します。" +mode: wide +sidebarTitle: Vue JS +--- + +import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; +import { LoggedInForm } from "/snippets/Login.jsx"; +import Index from "/snippets/quickstart/spa/vuejs/index.mdx"; +import Login from "/snippets/quickstart/spa/vuejs/login.mdx"; +import Logout from "/snippets/quickstart/spa/vuejs/logout.mdx"; +import Profile from "/snippets/quickstart/spa/vuejs/profile.mdx"; + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + +export const sections = [ + { id: "auth0を構成する", title: "Auth0を構成する" }, + { id: "auth0-vue-sdkをインストールする", title: "Auth0 Vue SDKをインストールする" }, + { id: "アプリケーションにログインを追加する", title: "アプリケーションにログインを追加する" }, + { id: "アプリケーションにログアウトを追加する", title: "アプリケーションにログアウトを追加する" }, + { id: "ユーザープロファイル情報を表示する", title: "ユーザープロファイル情報を表示する" } +] + + + + Auth0を使用すると、アプリケーションに認証を追加することができます。このガイドは、VueアプリケーションにAuth0 Vue + SDKを使ってAuth0を統合し、認証の追加とユーザープロファイル情報の表示を行う方法について説明します。 + + + このクイックスタートは、Vue 3アプリケーションで[Auth0 Vue](https://github.com/auth0/auth0-vue)を使用するために設計されています。Vue 2を使用している場合は、[Auth0 SPA SDKを使ったVue 2チュートリアル](https://github.com/auth0/auth0-vue/blob/main/tutorial/vue2-login.md)を確認するか、「[例を挙げて説明するVue.js認証2](https://developer.auth0.com/resources/guides/spa/vue/basic-authentication/v2-javascript)」ガイドを参照してください。 + + + このクイックスタートを使用するには、以下の手順に従います: + +
    + Auth0のサービスを利用するには、Auth0 Dashboadに設定済みのアプリケーションがある必要があります。Auth0アプリケーションは、開発中のプロジェクトに対してどのように認証が動作して欲しいかを構成する場所です。 + + ### アプリケーションを構成する + + 対話型のセレクターを使ってAuth0アプリケーションを新規作成するか、統合したいプロジェクトを表す既存のアプリケーションを選択します。Auth0のすべてのアプリケーションには英数字からなる一意のクライアントIDが割り当てられており、アプリケーションのコードがSDKを通じてAuth0 + APIを呼び出す際に使用されます。 + + このクイックスタートを使って構成されたすべての設定は、[Dashboard](https://manage.auth0.com/dashboard/us/dev-1-2s2aq0/)のアプリケーションを自動更新します。今後、アプリケーションの管理もDashboardで行えます。 + + 代わりに完了済みの構成を見てみたい場合は、サンプルアプリケーションをご覧ください。 + + ### Callback URLを構成する + + Callback URLとは、Auth0がユーザーを認証後にリダイレクトするアプリケーション内URLです。設定されていない場合、ユーザーはログイン後にアプリケーションに戻りません。 + + + サンプルプロジェクトに沿って進めている場合は、`http://localhost:3000`に設定してください。 + + + ### ログアウトURLを構成する + + ログアウトURLとは、Auth0がユーザーをログアウト後にリダイレクトするアプリケーション内URLです。設定されていない場合、ユーザーはアプリケーションからログアウトできず、エラーを受け取ります。 + + + サンプルプロジェクトに沿って進めている場合は、`http://localhost:3000`に設定してください。 + + + ### Allowed Web Origins(許可されているWebオリジン)を構成する + + [Allowed Web + Origin(許可されているWebオリジン)]とは、認証フローにアクセスすることを許可して欲しいURLです。これにはプロジェクトのURLが含まれている必要があります。適切に設定されていない場合、プロジェクトが認証トークンを暗黙でリフレッシュできず、ユーザーがアプリケーションを再び訪問した時、またはページを再読み込みした時にログアウトした状態になってしまいます。 + + + サンプルプロジェクトに沿って進めている場合は、`http://localhost:3000`に設定してください。 + +
    + +
    + Vue 3アプリで、Auth0の認証・認可を手軽に実装できるように、Auth0は[Vue SDK](https://github.com/auth0/auth0-vue)を提供しています。 + + ターミナルで以下のコマンドを実行してAuth0 Vue SDKをインストールします: + + ```bash + cd + npm install @auth0/auth0-vue + ``` + + ### プラグインを登録する + + SDKが機能するには、以下のプロパティを使ってVueアプリケーションでプラグインを登録する必要があります。 + + - `domain`:Auth0テナントのドメインです。この値は、Auth0 + Dashboardにあるアプリケーションの[Settings(設定)]の[Domain(ドメイン)]フィールドにあります。[カスタムドメイン](/docs/ja-jp/custom-domains)を使用している場合は、この値をカスタムドメインの値に設定してください。 + - `clientId`:このクイックスタートで前にセットアップした、Auth0アプリケーションのIDです。Auth0 + Dashboardにあるアプリケーションの[Settings(設定)]の[Client ID(クライアントID)]フィールドで確認してください。 + - `authorizationParams.redirect_uri`:ユーザー認証の後、Auth0にユーザーをリダイレクトして欲しいアプリケーション内URLです。このクイックスタートで前にセットアップしたCallback + URLと呼応します。この値は、Auth0 Dashboardにあるアプリケーションの[Settings(設定)]の[Callback + URLs(コールバックURL)]フィールドにあります。コードに入力した値と前にセットアップした値は必ず一致させてください。異なった場合はユーザーにエラーが表示されます。 + + プラグインは、`provide`と`app.config.globalProperties`の両方を使ってSDKを登録します。これによって、[Composition API](https://vuejs.org/guide/introduction.html#composition-api)と[Options API](https://vuejs.org/guide/introduction.html#options-api)の両方が有効になります。 + + + ##### チェックポイント + + プラグインが構成されました。アプリケーションを実行して次の点を確認します: + + - SDKが正しく初期化している + - アプリケーションがAuth0に関連したエラーを投入していない + +
    + +
    + 次に、プロジェクト用のログインを設定します。`useAuth0`の返り値に表示されたSDKの`loginWithRedirect`関数を使用します。これには、コンポーネントのsetup関数でアクセスすることができます。ユーザーはAuth0ユニバーサルログインページにリダイレクトされ、ユーザーの認証後、このクイックスタートで前に設定したCallback + URLにリダイレクトされます。 + + ### Options APIの使用 + + Options + APIでは、`this`アクセサを通じてグローバル`$auth0`プロパティからの同じ`loginWithRedirect`メソッドを使用することができます。 + + + ##### チェックポイント + + Auth0ユニバーサルログインからログインできるようになります。 + + ログインボタンをクリックして次の点を確認します: + + - VueアプリケーションによってAuth0ユニバーサルログインページにリダイレクトされる + - ログインまたはサインアップできる + - Auth0が、プラグインを構成するために使った`authorizationParams.redirect_uri`の値を使用し、アプリケーションへリダイレクトする。 + +
    + +
    + プロジェクトにログインしたユーザーには、ログアウトする方法も必要です。ユーザーがログアウトすると、アプリケーションによって[Auth0 + logout](https://auth0.com/docs/api/authentication?javascript#logout)エンドポイントにリダイレクトされてから、指定された`logoutParams.returnTo`パラメーターにリダイレクトされます。 + + `useAuth0`の返り値に表示された`logout`関数を使用します。これには、コンポーネントの`setup`関数でアクセスすることができ、ユーザーをアプリケーションからログアウトします。 + + ### Options APIの使用 + + Options APIでは、`this`アクセサを通じてグローバル`$auth0`プロパティからの同じ`logout`メソッドを使用することができます。 + + + ##### チェックポイント + + アプリケーションを実行してログアウトボタンをクリックし、次の点を検証します: + + - Vueアプリケーションによって`logoutParams.returnTo`アドレスにリダイレクトされる + - アプリケーションにログインしていない + +
    + +
    + 次に、認証ユーザーに関連する[プロファイル情報](/docs/ja-jp/users/concepts/overview-user-profile)を取得する方法を構成します。たとえば、ログインしたユーザーの名前やプロフィール写真をプロジェクトに表示したいかもしれません。ユーザーが認証を行うと、SDKはユーザーのプロファイル情報を抽出し、メモリ内に保存します。アプリケーションは、リアクティブな`user`プロパティを使ってユーザープロファイルにアクセスすることができます。このプロパティにアクセスするには、コンポーネントの`setup`関数を確認し、`userAuth0`返り値を見つけます。 + + `user`プロパティには、ユーザーIDに関する機微な情報が含まれています。これは、ユーザーの認証ステータスに基づいてのみ利用できます。エラーを防ぐため、常に以下を行ってください: + + - Vueが`user`プロパティを使用するコンポーネントを呼び出す前に、`isAuthenticated`プロパティを使用してAuth0がユーザーを認証したかどうかを定義する。 + - `isAuthenticated`プロパティにアクセスする前に、`isLoading`がfalseであることをチェックして、SDKの読み込みが完了したことを確認する。 + + ### Options APIの使用 + + Options + APIでは、アクセサ`this`を通じてグローバル`$auth0`プロパティからの同じリアクティブな`user`、`isLoading`、および`isAuthenticated`プロパティを使用します。 + + + ##### チェックポイント + + 以下の点を確認します: + + - ログイン後、コンポーネント内の`user`やその他のユーザープロパティをすべて正しく表示できる + +
    + + ## 次のステップ + + 成功です!ここまで来れば、アプリケーションにログイン、ログアウト、ユーザープロファイル情報が備わっているはずです。 + + これでクイックスタートチュートリアルは終了ですが、機能はまだまだたくさんあります。Auth0でできることについて詳しくは、以下をご覧ください。 + + * [Auth0 Dashboard](https://manage.auth0.com/#) - Auth0のテナントやアプリケーションを構成して管理する方法について説明します + * [auth0-vue SDK](https://www.github.com/auth0/auth0-vue) - このチュートリアルで使用されているSDKをより詳しく説明します + * [Auth0 Marketplace](https://marketplace.auth0.com/) - Auth0の機能性を拡張できる各種の統合を見つけられます +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    diff --git a/main/docs/ja-jp/quickstart/webapp/apache/interactive.mdx b/main/docs/ja-jp/quickstart/webapp/apache/interactive.mdx index 91b9a4227..4d67d30f9 100644 --- a/main/docs/ja-jp/quickstart/webapp/apache/interactive.mdx +++ b/main/docs/ja-jp/quickstart/webapp/apache/interactive.mdx @@ -1,122 +1,124 @@ ---- -title: "Apache" -permalink: "interactive" -'description': "このチュートリアルでは、Webアプリに認証と認可を追加するために、Apacheを構成する方法について説明します。" -'og:title': "Apache" -'og:description': "このチュートリアルでは、Webアプリに認証と認可を追加するために、Apacheを構成する方法について説明します。" -'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/apache.jpg" -'twitter:title': "Apache" -'twitter:description': "このチュートリアルでは、Webアプリに認証と認可を追加するために、Apacheを構成する方法について説明します。" -mode: wide ---- - -import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; -import { LoggedInForm } from "/snippets/Login.jsx"; -import Code1 from "/snippets/quickstart/webapp/apache/code1.mdx" -import Code2 from "/snippets/quickstart/webapp/apache/code2.mdx" - -export const sections = [ - { id: "システム要件", title: "システム要件" }, - { id: "mod-auth-openidcモジュールをインストールして有効にする", title: "mod_auth_openidcモジュールをインストールして有効にする" }, - { id: "auth0アカウント情報でモジュールを構成する", title: "Auth0アカウント情報でモジュールを構成する" }, - { id: "auth0を構成する", title: "Auth0を構成する" }, - { id: "認可", title: "認可" } -] - - - - このチュートリアルでは、Webアプリに認証と認可を追加するために、Apacheを構成する方法について説明します。ログインして、アカウント用に構成された例を参考にこのクイックタートに従うことをお勧めします。 - -
    - このチュートリアルとサンプルプロジェクトは次を使用してテストが完了しています: - - - Apache 2.4 -
    - -
    - まず、Apacheに`mod_auth_openidc`モジュールをインストールする必要があります。 - - [GitHub](https://github.com/zmartzone/mod_auth_openidc/releases)からバイナリを取得して、OSにインストールすることができます。OSがバイナリのどれとも互換でない場合には、[ソースからビルド](https://github.com/zmartzone/mod_auth_openidc/blob/master/INSTALL)することができます。 - - モジュールをインストールしたら、`a2enmod`コマンドを実行して、Apacheで有効化します。詳細については、[Ubuntu Manpageでの2enmod](https://manpages.ubuntu.com/manpages/focal/man8/a2enmod.8.html)で次を参照してください: - - ``` - a2enmod auth_openidc - ``` - - - Windowsについては、[こちらのPowershellスクリプト](https://github.com/enderandpeter/win-a2enmod#installation)を使用すると、システム上で`a2enmod`を動作させることができます。 - -
    - -
    - 新しい構成ファイル(`auth_openidc.conf`)を更新します。このファイルは`/etc/apache2/mods-available`フォルダーにあります。 - - - Windowsでは、`/apache/conf/httpd.conf`ファイルを使用する必要があります - -
    - -
    - Auth0 Dashboardで以下を行います。 - - 1. **[Applications(アプリケーション)]** > **[Applications(アプリケーション)]** に移動し、リストからアプリケーションを選択します。 - 2. **[Settings(設定)]** ビューに切り替えて、**[Application URIs(アプリケーションURL)]** セクションを見つけます。 - 3. `OIDCRedirectURI`の値を**[Allowed Callback URLs(許可されているCallback URL)]** に追加します。 - 4. ページ下部の**[Advanced Settings(詳細設定)]** を見つけます。 - 5. **[OAuth]** ビューに切り替えます。 - 6. **[JSON Web Token (JWT) Signature Algorithm(JSON Web Token(JWT)署名アルゴリズム)]** を`RS256`に設定します。 -
    - -
    - Apacheを構成して、ユーザーのIDトークンにあるクレームの値を基に特定の場所を保護することができます。これを行うには、`Location`ブロックを`auth_openidc.conf`ファイルに追加します。 - - たとえば、ユーザーのロールを読み出すアクションを作成して、保護された場所へのアクセスを付与するクレームを追加することができます: - - ```js lines - exports.onExecutePostLogin = async (event, api) => { - const roles = event.authorization.roles; // ['user', 'admin'] - if (roles.includes('admin')) { - api.idToken.setCustomClaim('folder', 'admin'); - } - }; - ``` - -
    - ## 次のステップ - - 成功です!ここまで来れば、アプリケーションにログイン、ログアウト、ユーザープロファイル情報が備わっているはずです。 - - これでクイックスタートチュートリアルは終了ですが、機能はまだまだたくさんあります。Auth0でできることについて詳しくは、以下をご覧ください。 - - * [Auth0 Dashboard](https://manage.auth0.com/#) - Auth0のテナントやアプリケーションを構成して管理する方法について説明します - * [Auth0 Marketplace](https://marketplace.auth0.com/) - Auth0の機能性を拡張できる各種の統合を見つけられます -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    +--- +title: "Apache" +permalink: "interactive" +'description': "このチュートリアルでは、Webアプリに認証と認可を追加するために、Apacheを構成する方法について説明します。" +'og:title': "Apache" +'og:description': "このチュートリアルでは、Webアプリに認証と認可を追加するために、Apacheを構成する方法について説明します。" +'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/apache.jpg" +'twitter:title': "Apache" +'twitter:description': "このチュートリアルでは、Webアプリに認証と認可を追加するために、Apacheを構成する方法について説明します。" +mode: wide +--- + +import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; +import { LoggedInForm } from "/snippets/Login.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + +import Code1 from "/snippets/quickstart/webapp/apache/code1.mdx" +import Code2 from "/snippets/quickstart/webapp/apache/code2.mdx" + +export const sections = [ + { id: "システム要件", title: "システム要件" }, + { id: "mod-auth-openidcモジュールをインストールして有効にする", title: "mod_auth_openidcモジュールをインストールして有効にする" }, + { id: "auth0アカウント情報でモジュールを構成する", title: "Auth0アカウント情報でモジュールを構成する" }, + { id: "auth0を構成する", title: "Auth0を構成する" }, + { id: "認可", title: "認可" } +] + + + + このチュートリアルでは、Webアプリに認証と認可を追加するために、Apacheを構成する方法について説明します。ログインして、アカウント用に構成された例を参考にこのクイックタートに従うことをお勧めします。 + +
    + このチュートリアルとサンプルプロジェクトは次を使用してテストが完了しています: + + - Apache 2.4 +
    + +
    + まず、Apacheに`mod_auth_openidc`モジュールをインストールする必要があります。 + + [GitHub](https://github.com/zmartzone/mod_auth_openidc/releases)からバイナリを取得して、OSにインストールすることができます。OSがバイナリのどれとも互換でない場合には、[ソースからビルド](https://github.com/zmartzone/mod_auth_openidc/blob/master/INSTALL)することができます。 + + モジュールをインストールしたら、`a2enmod`コマンドを実行して、Apacheで有効化します。詳細については、[Ubuntu Manpageでの2enmod](https://manpages.ubuntu.com/manpages/focal/man8/a2enmod.8.html)で次を参照してください: + + ``` + a2enmod auth_openidc + ``` + + + Windowsについては、[こちらのPowershellスクリプト](https://github.com/enderandpeter/win-a2enmod#installation)を使用すると、システム上で`a2enmod`を動作させることができます。 + +
    + +
    + 新しい構成ファイル(`auth_openidc.conf`)を更新します。このファイルは`/etc/apache2/mods-available`フォルダーにあります。 + + + Windowsでは、`/apache/conf/httpd.conf`ファイルを使用する必要があります + +
    + +
    + Auth0 Dashboardで以下を行います。 + + 1. **[Applications(アプリケーション)]** > **[Applications(アプリケーション)]** に移動し、リストからアプリケーションを選択します。 + 2. **[Settings(設定)]** ビューに切り替えて、**[Application URIs(アプリケーションURL)]** セクションを見つけます。 + 3. `OIDCRedirectURI`の値を**[Allowed Callback URLs(許可されているCallback URL)]** に追加します。 + 4. ページ下部の**[Advanced Settings(詳細設定)]** を見つけます。 + 5. **[OAuth]** ビューに切り替えます。 + 6. **[JSON Web Token (JWT) Signature Algorithm(JSON Web Token(JWT)署名アルゴリズム)]** を`RS256`に設定します。 +
    + +
    + Apacheを構成して、ユーザーのIDトークンにあるクレームの値を基に特定の場所を保護することができます。これを行うには、`Location`ブロックを`auth_openidc.conf`ファイルに追加します。 + + たとえば、ユーザーのロールを読み出すアクションを作成して、保護された場所へのアクセスを付与するクレームを追加することができます: + + ```js lines + exports.onExecutePostLogin = async (event, api) => { + const roles = event.authorization.roles; // ['user', 'admin'] + if (roles.includes('admin')) { + api.idToken.setCustomClaim('folder', 'admin'); + } + }; + ``` + +
    + ## 次のステップ + + 成功です!ここまで来れば、アプリケーションにログイン、ログアウト、ユーザープロファイル情報が備わっているはずです。 + + これでクイックスタートチュートリアルは終了ですが、機能はまだまだたくさんあります。Auth0でできることについて詳しくは、以下をご覧ください。 + + * [Auth0 Dashboard](https://manage.auth0.com/#) - Auth0のテナントやアプリケーションを構成して管理する方法について説明します + * [Auth0 Marketplace](https://marketplace.auth0.com/) - Auth0の機能性を拡張できる各種の統合を見つけられます +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    diff --git a/main/docs/ja-jp/quickstart/webapp/aspnet-core-blazor-server/interactive.mdx b/main/docs/ja-jp/quickstart/webapp/aspnet-core-blazor-server/interactive.mdx index eff1a9adc..d9f96b6d2 100644 --- a/main/docs/ja-jp/quickstart/webapp/aspnet-core-blazor-server/interactive.mdx +++ b/main/docs/ja-jp/quickstart/webapp/aspnet-core-blazor-server/interactive.mdx @@ -1,164 +1,166 @@ ---- -title: "Blazor Serverアプリケーションにログインを追加する" -permalink: "interactive" -'description': "このガイドは、新規または既存のBlazor ServerアプリケーションにAuth0.AspNetCore.Authentication SDKを使ってAuth0を統合する方法を説明します。" -'og:title': "Blazor Serverアプリケーションにログインを追加する" -'og:description': "このガイドは、新規または既存のBlazor ServerアプリケーションにAuth0.AspNetCore.Authentication SDKを使ってAuth0を統合する方法を説明します。" -'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/asp.png" -'twitter:title': "Blazor Serverアプリケーションにログインを追加する" -'twitter:description': "このガイドは、新規または既存のBlazor ServerアプリケーションにAuth0.AspNetCore.Authentication SDKを使ってAuth0を統合する方法を説明します。" -sidebarTitle: ASP.NET Core Blazor Server -mode: wide ---- - - -import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; -import { LoggedInForm } from "/snippets/Login.jsx"; -import Login from "/snippets/quickstart/webapp/aspnet-core-blazor-server/Login.cshtml.cs.mdx" -import Logout from "/snippets/quickstart/webapp/aspnet-core-blazor-server/Logout.cshtml.cs.mdx" - -export const sections = [ - { id: "auth0を構成する", title: "Auth0を構成する" }, - { id: "sdkをインストールして構成する", title: "SDKをインストールして構成する" }, - { id: "ログイン", title: "ログイン" }, - { id: "ユーザープロファイルを表示する", title: "ユーザープロファイルを表示する" }, - { id: "ログアウト", title: "ログアウト" } -] - - - - Auth0を使用すると、アプリケーションに手軽に認証を追加して、ユーザープロファイル情報にアクセスすることができます。このガイドは、新規または既存のBlazor - Serverアプリケーションに**Auth0.AspNetCore.Authentication** SDKを使ってAuth0を統合する方法を説明します。 - -
    - Auth0のサービスを利用するには、Auth0 Dashboadに設定済みのアプリケーションがある必要があります。Auth0アプリケーションは、開発中のプロジェクトに対してどのように認証が動作して欲しいかを構成する場所です。 - - ### アプリケーションを構成する - - 対話型のセレクターを使ってAuth0アプリケーションを新規作成するか、統合したいプロジェクトを表す既存のアプリケーションを選択します。Auth0のすべてのアプリケーションには英数字からなる一意のクライアントIDが割り当てられており、アプリケーションのコードがSDKを通じてAuth0 - APIを呼び出す際に使用されます。 - - このクイックスタートを使って構成されたすべての設定は、[Dashboard](https://manage.auth0.com/dashboard/us/auth0-dsepaid/)のアプリケーションを自動更新します。今後、アプリケーションの管理もDashboardで行えます。 - - 完了済みの構成を見てみたい場合は、サンプルアプリケーションをご覧ください。 - - ### Callback URLを構成する - - Callback URLとは、Auth0がユーザーを認証後にリダイレクトするアプリケーション内URLです。設定されていない場合、ユーザーはログイン後にアプリケーションに戻りません。 - - - サンプルプロジェクトに沿って進めている場合は、`http://localhost:3000``/callback`に設定してください。 - - - ### ログアウトURLを構成する - - ログアウトURLとは、Auth0がユーザーをログアウト後にリダイレクトするアプリケーション内URLです。設定されていない場合、ユーザーはアプリケーションからログアウトできず、エラーを受け取ります。 - - - サンプルプロジェクトに沿って進めている場合は、`http://localhost:3000`に設定してください。 - -
    - -
    - ### NuGetからインストールする - - Auth0をBlazor Serverと統合するには、`Auth0.AspNetCore.Authentication`[NuGetパッケージ](https://www.nuget.org/packages/Auth0.AspNetCore.Authentication/)をアプリケーションにインストールすることでSDKを使用できます。 - - ### ミドルウェアを構成する - - Blazor - Serverアプリケーションで認証を可能にするには、SDKが提供するミドルウェアを使います。`Program.cs`ファイルに移動して`builder.Services.AddAuth0WebAppAuthentication()`を呼び出し、SDKのミドルウェアを登録します。 - - `Domain`と`ClientId`は必ず構成してください。SDKがどのAuth0テナントとアプリケーションを使用すべきかを認識するために必要となるフィールドです。 - - 認証と認可が`Program.cs`ファイルで有効になったことを確認します。 -
    - -
    - Blazor Serverアプリケーションにユーザーをログインさせるには、`LoginModel`を`Pages`ディレクトリに追加します。 - - `LoginModel`の`OnGet`メソッド内で`HttpContext.ChallengeAsync()`を呼び出し、`Auth0Constants.AuthenticationScheme`を認証スキームとして渡します。これにより当社のSDKが内部に登録しているOIDC認証ハンドラーが発動されます。関連する`authenticationProperties`も必ず指定してください。構築は`LoginAuthenticationPropertiesBuilder`で行えます。 - - `HttpContext.ChallengeAsync()`の呼び出し成功後、ユーザーはAuth0にリダイレクトされます。その後アプリケーションにリダイレクトで戻された際に、OIDCミドルウェアとクッキーミドルウェアの両方にサインインしています。これにより、ユーザーは後続の要求でも認証されるようになります。 - - - ##### チェックポイント - - Loginの構成が完了したら、アプリケーションを実行して次の点を確認します: - - - `Login`ページに移動すると、Auth0にリダイレクトされる。 - - 資格情報を入力すると、リダイレクトでアプリケーションに戻る。 - -
    - -
    - ミドルウェアはAuth0からトークンを取得すると、IDトークンからユーザー情報とクレームを抽出し、`AuthenticationState`を介して利用できるようにします。これは`CascadingParameter`として追加できます。 - - ユーザーの名前や追加クレーム(メールアドレスや画像など)を表示するカスタムのユーザープロファイルページは、`AuthenticationState`の`User`プロパティから関連情報を取得し、Blazorコード内からビューに渡すことで作成できます。 - - - ##### チェックポイント - - ユーザープロファイルを表示するようセットアップし終えたら、アプリケーションを実行して次の点を確認します: - - - ログイン成功後にプロファイルを含んだエンドポイントに移動すると、ユーザーのプロファイルが表示される。 - -
    - -
    - `LogoutModel`の`OnGet`メソッド内から`HttpContext.SignOutAsync`を`CookieAuthenticationDefaults.AuthenticationScheme`認証スキームで呼び出すと、ユーザーをアプリケーションからログアウトさせられます。 - - さらに、ユーザーをAuth0からもログアウトさせたい場合は(これによりシングルサインオンに依拠している他のアプリケーションからもログアウトさせる可能性があります)、`HttpContext.SignOutAsync`を`Auth0Constants.AuthenticationScheme`認証スキームで呼び出します。また、`LogoutAuthenticationPropertiesBuilder`を使って構築できる適切な`authenticationProperties`も同じ認証スキームで呼び出します。 - - - ##### チェックポイント - - Logoutの構成が完了したら、アプリケーションを実行して次の点を確認します: - - - `Logout`ページに移動すると、ユーザーがログアウトする。 - - Auth0からもログアウトすると、Auth0にリダイレクトされ、即座にアプリケーションにリダイレクトで戻される。 - -
    - ## 次のステップ - - 成功です!ここまで来れば、アプリケーションにログイン、ログアウト、ユーザープロファイル情報が備わっているはずです。 - - これでクイックスタートチュートリアルは終了ですが、機能はまだまだたくさんあります。Auth0でできることについて詳しくは、以下をご覧ください。 - - * [Auth0 Dashboard](https://manage.auth0.com/#) - Auth0のテナントやアプリケーションを構成して管理する方法について説明します - * [auth0-aspnetcore-authentication SDK](https://github.com/auth0/auth0-aspnetcore-authentication) - このチュートリアルで使用されているSDKをより詳しく説明します - * [Auth0 Marketplace](https://marketplace.auth0.com/) - Auth0の機能性を拡張できる各種の統合を見つけられます -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    +--- +title: "Blazor Serverアプリケーションにログインを追加する" +permalink: "interactive" +'description': "このガイドは、新規または既存のBlazor ServerアプリケーションにAuth0.AspNetCore.Authentication SDKを使ってAuth0を統合する方法を説明します。" +'og:title': "Blazor Serverアプリケーションにログインを追加する" +'og:description': "このガイドは、新規または既存のBlazor ServerアプリケーションにAuth0.AspNetCore.Authentication SDKを使ってAuth0を統合する方法を説明します。" +'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/asp.png" +'twitter:title': "Blazor Serverアプリケーションにログインを追加する" +'twitter:description': "このガイドは、新規または既存のBlazor ServerアプリケーションにAuth0.AspNetCore.Authentication SDKを使ってAuth0を統合する方法を説明します。" +sidebarTitle: ASP.NET Core Blazor Server +mode: wide +--- + + +import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; +import { LoggedInForm } from "/snippets/Login.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + +import Login from "/snippets/quickstart/webapp/aspnet-core-blazor-server/Login.cshtml.cs.mdx" +import Logout from "/snippets/quickstart/webapp/aspnet-core-blazor-server/Logout.cshtml.cs.mdx" + +export const sections = [ + { id: "auth0を構成する", title: "Auth0を構成する" }, + { id: "sdkをインストールして構成する", title: "SDKをインストールして構成する" }, + { id: "ログイン", title: "ログイン" }, + { id: "ユーザープロファイルを表示する", title: "ユーザープロファイルを表示する" }, + { id: "ログアウト", title: "ログアウト" } +] + + + + Auth0を使用すると、アプリケーションに手軽に認証を追加して、ユーザープロファイル情報にアクセスすることができます。このガイドは、新規または既存のBlazor + Serverアプリケーションに**Auth0.AspNetCore.Authentication** SDKを使ってAuth0を統合する方法を説明します。 + +
    + Auth0のサービスを利用するには、Auth0 Dashboadに設定済みのアプリケーションがある必要があります。Auth0アプリケーションは、開発中のプロジェクトに対してどのように認証が動作して欲しいかを構成する場所です。 + + ### アプリケーションを構成する + + 対話型のセレクターを使ってAuth0アプリケーションを新規作成するか、統合したいプロジェクトを表す既存のアプリケーションを選択します。Auth0のすべてのアプリケーションには英数字からなる一意のクライアントIDが割り当てられており、アプリケーションのコードがSDKを通じてAuth0 + APIを呼び出す際に使用されます。 + + このクイックスタートを使って構成されたすべての設定は、[Dashboard](https://manage.auth0.com/dashboard/us/auth0-dsepaid/)のアプリケーションを自動更新します。今後、アプリケーションの管理もDashboardで行えます。 + + 完了済みの構成を見てみたい場合は、サンプルアプリケーションをご覧ください。 + + ### Callback URLを構成する + + Callback URLとは、Auth0がユーザーを認証後にリダイレクトするアプリケーション内URLです。設定されていない場合、ユーザーはログイン後にアプリケーションに戻りません。 + + + サンプルプロジェクトに沿って進めている場合は、`http://localhost:3000``/callback`に設定してください。 + + + ### ログアウトURLを構成する + + ログアウトURLとは、Auth0がユーザーをログアウト後にリダイレクトするアプリケーション内URLです。設定されていない場合、ユーザーはアプリケーションからログアウトできず、エラーを受け取ります。 + + + サンプルプロジェクトに沿って進めている場合は、`http://localhost:3000`に設定してください。 + +
    + +
    + ### NuGetからインストールする + + Auth0をBlazor Serverと統合するには、`Auth0.AspNetCore.Authentication`[NuGetパッケージ](https://www.nuget.org/packages/Auth0.AspNetCore.Authentication/)をアプリケーションにインストールすることでSDKを使用できます。 + + ### ミドルウェアを構成する + + Blazor + Serverアプリケーションで認証を可能にするには、SDKが提供するミドルウェアを使います。`Program.cs`ファイルに移動して`builder.Services.AddAuth0WebAppAuthentication()`を呼び出し、SDKのミドルウェアを登録します。 + + `Domain`と`ClientId`は必ず構成してください。SDKがどのAuth0テナントとアプリケーションを使用すべきかを認識するために必要となるフィールドです。 + + 認証と認可が`Program.cs`ファイルで有効になったことを確認します。 +
    + +
    + Blazor Serverアプリケーションにユーザーをログインさせるには、`LoginModel`を`Pages`ディレクトリに追加します。 + + `LoginModel`の`OnGet`メソッド内で`HttpContext.ChallengeAsync()`を呼び出し、`Auth0Constants.AuthenticationScheme`を認証スキームとして渡します。これにより当社のSDKが内部に登録しているOIDC認証ハンドラーが発動されます。関連する`authenticationProperties`も必ず指定してください。構築は`LoginAuthenticationPropertiesBuilder`で行えます。 + + `HttpContext.ChallengeAsync()`の呼び出し成功後、ユーザーはAuth0にリダイレクトされます。その後アプリケーションにリダイレクトで戻された際に、OIDCミドルウェアとクッキーミドルウェアの両方にサインインしています。これにより、ユーザーは後続の要求でも認証されるようになります。 + + + ##### チェックポイント + + Loginの構成が完了したら、アプリケーションを実行して次の点を確認します: + + - `Login`ページに移動すると、Auth0にリダイレクトされる。 + - 資格情報を入力すると、リダイレクトでアプリケーションに戻る。 + +
    + +
    + ミドルウェアはAuth0からトークンを取得すると、IDトークンからユーザー情報とクレームを抽出し、`AuthenticationState`を介して利用できるようにします。これは`CascadingParameter`として追加できます。 + + ユーザーの名前や追加クレーム(メールアドレスや画像など)を表示するカスタムのユーザープロファイルページは、`AuthenticationState`の`User`プロパティから関連情報を取得し、Blazorコード内からビューに渡すことで作成できます。 + + + ##### チェックポイント + + ユーザープロファイルを表示するようセットアップし終えたら、アプリケーションを実行して次の点を確認します: + + - ログイン成功後にプロファイルを含んだエンドポイントに移動すると、ユーザーのプロファイルが表示される。 + +
    + +
    + `LogoutModel`の`OnGet`メソッド内から`HttpContext.SignOutAsync`を`CookieAuthenticationDefaults.AuthenticationScheme`認証スキームで呼び出すと、ユーザーをアプリケーションからログアウトさせられます。 + + さらに、ユーザーをAuth0からもログアウトさせたい場合は(これによりシングルサインオンに依拠している他のアプリケーションからもログアウトさせる可能性があります)、`HttpContext.SignOutAsync`を`Auth0Constants.AuthenticationScheme`認証スキームで呼び出します。また、`LogoutAuthenticationPropertiesBuilder`を使って構築できる適切な`authenticationProperties`も同じ認証スキームで呼び出します。 + + + ##### チェックポイント + + Logoutの構成が完了したら、アプリケーションを実行して次の点を確認します: + + - `Logout`ページに移動すると、ユーザーがログアウトする。 + - Auth0からもログアウトすると、Auth0にリダイレクトされ、即座にアプリケーションにリダイレクトで戻される。 + +
    + ## 次のステップ + + 成功です!ここまで来れば、アプリケーションにログイン、ログアウト、ユーザープロファイル情報が備わっているはずです。 + + これでクイックスタートチュートリアルは終了ですが、機能はまだまだたくさんあります。Auth0でできることについて詳しくは、以下をご覧ください。 + + * [Auth0 Dashboard](https://manage.auth0.com/#) - Auth0のテナントやアプリケーションを構成して管理する方法について説明します + * [auth0-aspnetcore-authentication SDK](https://github.com/auth0/auth0-aspnetcore-authentication) - このチュートリアルで使用されているSDKをより詳しく説明します + * [Auth0 Marketplace](https://marketplace.auth0.com/) - Auth0の機能性を拡張できる各種の統合を見つけられます +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    diff --git a/main/docs/ja-jp/quickstart/webapp/aspnet-core/interactive.mdx b/main/docs/ja-jp/quickstart/webapp/aspnet-core/interactive.mdx index 232678215..64d2495f0 100644 --- a/main/docs/ja-jp/quickstart/webapp/aspnet-core/interactive.mdx +++ b/main/docs/ja-jp/quickstart/webapp/aspnet-core/interactive.mdx @@ -1,161 +1,163 @@ ---- -title: "ASP.NET MVCアプリケーションにログインを追加する" -permalink: "interactive" -'description': "このガイドは、新規または既存のASP.NET MVCアプリケーションにAuth0.AspNetCore.Authentication SDKを使ってAuth0を統合する方法を説明します。" -'og:title': "ASP.NET MVCアプリケーションにログインを追加する" -'og:description': "このガイドは、新規または既存のASP.NET MVCアプリケーションにAuth0.AspNetCore.Authentication SDKを使ってAuth0を統合する方法を説明します。" -'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/asp.png" -'twitter:title': "ASP.NET MVCアプリケーションにログインを追加する" -'twitter:description': "このガイドは、新規または既存のASP.NET MVCアプリケーションにAuth0.AspNetCore.Authentication SDKを使ってAuth0を統合する方法を説明します。" -sidebarTitle: ASP.NET Core MVC -mode: wide ---- - -import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; -import { LoggedInForm } from "/snippets/Login.jsx"; -import AppSettingsJSON from "/snippets/quickstart/webapp/aspnet-core/appsettings.json.mdx"; -import AccountController from "/snippets/quickstart/webapp/aspnet-core/AccountController.cs.mdx"; - -export const sections = [ - { id: "auth0を構成する", title: "Auth0を構成する" }, - { id: "sdkをインストールして構成する", title: "SDKをインストールして構成する" }, - { id: "ログイン", title: "ログイン" }, - { id: "ユーザープロファイルを表示する", title: "ユーザープロファイルを表示する" }, - { id: "ログアウト", title: "ログアウト" } -] - - - - Auth0を使用すると、アプリケーションに手軽に認証を追加して、ユーザープロファイル情報にアクセスすることができます。このガイドは、新規または既存のASP.NET - MVCアプリケーションに**Auth0.AspNetCore.Authentication** SDKを使ってAuth0を統合する方法を説明します。 - -
    - Auth0のサービスを利用するには、Auth0 Dashboadに設定済みのアプリケーションがある必要があります。Auth0アプリケーションは、開発中のプロジェクトに対してどのように認証が動作して欲しいかを構成する場所です。 - - ### アプリケーションを構成する - - 対話型のセレクターを使ってAuth0アプリケーションを新規作成するか、統合したいプロジェクトを表す既存のアプリケーションを選択します。Auth0のすべてのアプリケーションには英数字からなる一意のクライアントIDが割り当てられており、アプリケーションのコードがSDKを通じてAuth0 - APIを呼び出す際に使用されます。 - - このクイックスタートを使って構成されたすべての設定は、[Dashboard](https://manage.auth0.com/#/)のアプリケーションを自動更新します。今後、アプリケーションの管理もDashboardで行えます。 - - 完了済みの構成を見てみたい場合は、サンプルアプリケーションをご覧ください。 - - ### Callback URLを構成する - - Callback URLとは、Auth0がユーザーを認証後にリダイレクトするアプリケーション内URLです。設定されていない場合、ユーザーはログイン後にアプリケーションに戻りません。 - - - サンプルプロジェクトに沿って進めている場合は、`http://localhost:3000/callback`に設定してください。 - - - ### ログアウトURLを構成する - - ログアウトURLとは、Auth0がユーザーをログアウト後にリダイレクトするアプリケーション内URLです。設定されていない場合、ユーザーはアプリケーションからログアウトできず、エラーを受け取ります。 - - - サンプルプロジェクトに沿って進めている場合は、`http://localhost:3000`に設定してください。 - -
    - -
    - ### Nugetからインストールする - - Auth0をASP.NET Coreと統合するには、`Auth0.AspNetCore.Authentication`[Nugetパッケージ](https://www.nuget.org/packages/Auth0.AspNetCore.Authentication/)をアプリケーションにインストールすることでSDKを使用できます。 - - ### ミドルウェアを構成する - - ASP.NET - Coreアプリケーションで認証を可能にするには、SDKが提供するミドルウェアを使います。`Program.cs`ファイルに移動して`builder.Services.AddAuth0WebAppAuthentication()`を呼び出し、SDKのミドルウェアを登録します。 - - `Domain`と`ClientId`は必ず構成してください。SDKがどのAuth0テナントとアプリケーションを使用すべきかを認識するために必要となるフィールドです。 - - 認証と認可が`Program.cs`ファイルで有効になったことを確認します。 -
    - -
    - ユーザーによるASP.NET MVCアプリケーションへのログインを許可するには、コントローラーに`Login`アクションを追加します。 - - `HttpContext.ChallengeAsync()`を呼び出し、`Auth0Constants.AuthenticationScheme`を認証スキームとして渡します。これによりSDKが内部に登録しているOIDC認証ハンドラーが発動されます。関連する`authenticationProperties`も必ず指定してください。構築は`LoginAuthenticationPropertiesBuilder`で行えます。 - - `HttpContext.ChallengeAsync()`の呼び出し成功後、ユーザーはAuth0にリダイレクトされます。その後アプリケーションにリダイレクトで戻された際に、OIDCミドルウェアとクッキーミドルウェアの両方にサインインしています。これにより、ユーザーは後続の要求でも認証されるようになります。 - - - ##### チェックポイント - - Loginの構成が完了したら、アプリケーションを実行して次の点を確認します: - - - `Login`アクションに移動すると、Auth0にリダイレクトされる。 - - 資格情報を入力すると、リダイレクトでアプリケーションに戻る。 - -
    - -
    - ミドルウェアはAuth0からトークンを取得すると、IDトークンからユーザー情報とクレームを抽出し、コントローラーで`User.Claims`プロパティとして利用できるようにします。 - - ユーザーの名前、メールアドレス、プロファイル画像を表示するカスタムユーザープロファイルを作成するには、`User`から関連する情報を取得し、コントローラー内からビューに渡します。 - - - ##### チェックポイント - - ユーザープロファイルを表示するようアクションをセットアップし終えたら、アプリケーションを実行して次の点を確認します: - - - ログイン成功後に`Profile`アクションに移動すると、ユーザープロファイルが表示される。 - -
    - -
    - コントローラーのアクション内から`HttpContext.SignOutAsync`を`CookieAuthenticationDefaults.AuthenticationScheme`認証スキームで呼び出すと、ユーザーをアプリケーションからログアウトさせられます。 - - さらに、ユーザーをAuth0からもログアウトさせたい場合は(これによりシングルサインオンに依拠している他のアプリケーションからもログアウトさせる可能性があります)、`HttpContext.SignOutAsync`を`Auth0Constants.AuthenticationScheme`認証スキームで呼び出します。また、`LogoutAuthenticationPropertiesBuilder`を使って構築できる適切な`authenticationProperties`も同じ認証スキームで呼び出します。 - - - ##### チェックポイント - - Logoutの構成が完了したら、アプリケーションを実行して次の点を確認します: - - - `Logout`アクションに移動すると、ユーザーが確実にログアウトする。 - - Auth0からもログアウトすると、Auth0にリダイレクトされ、即座にアプリケーションにリダイレクトで戻される。 - -
    - - ## 次のステップ - - 成功です!ここまで来れば、アプリケーションにログイン、ログアウト、ユーザープロファイル情報が備わっているはずです。 - - これでクイックスタートチュートリアルは終了ですが、機能はまだまだたくさんあります。Auth0でできることについて詳しくは、以下をご覧ください。 - - * [Auth0 Dashboard](https://manage.auth0.com/#) - Auth0のテナントやアプリケーションを構成して管理する方法について説明します - * [auth0-aspnetcore-authentication SDK](https://github.com/auth0/auth0-aspnetcore-authentication) - このチュートリアルで使用されているSDKをより詳しく説明します - * [Auth0 Marketplace](https://marketplace.auth0.com/) - Auth0の機能性を拡張できる各種の統合を見つけられます -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    +--- +title: "ASP.NET MVCアプリケーションにログインを追加する" +permalink: "interactive" +'description': "このガイドは、新規または既存のASP.NET MVCアプリケーションにAuth0.AspNetCore.Authentication SDKを使ってAuth0を統合する方法を説明します。" +'og:title': "ASP.NET MVCアプリケーションにログインを追加する" +'og:description': "このガイドは、新規または既存のASP.NET MVCアプリケーションにAuth0.AspNetCore.Authentication SDKを使ってAuth0を統合する方法を説明します。" +'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/asp.png" +'twitter:title': "ASP.NET MVCアプリケーションにログインを追加する" +'twitter:description': "このガイドは、新規または既存のASP.NET MVCアプリケーションにAuth0.AspNetCore.Authentication SDKを使ってAuth0を統合する方法を説明します。" +sidebarTitle: ASP.NET Core MVC +mode: wide +--- + +import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; +import { LoggedInForm } from "/snippets/Login.jsx"; +import AppSettingsJSON from "/snippets/quickstart/webapp/aspnet-core/appsettings.json.mdx"; +import AccountController from "/snippets/quickstart/webapp/aspnet-core/AccountController.cs.mdx"; + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + +export const sections = [ + { id: "auth0を構成する", title: "Auth0を構成する" }, + { id: "sdkをインストールして構成する", title: "SDKをインストールして構成する" }, + { id: "ログイン", title: "ログイン" }, + { id: "ユーザープロファイルを表示する", title: "ユーザープロファイルを表示する" }, + { id: "ログアウト", title: "ログアウト" } +] + + + + Auth0を使用すると、アプリケーションに手軽に認証を追加して、ユーザープロファイル情報にアクセスすることができます。このガイドは、新規または既存のASP.NET + MVCアプリケーションに**Auth0.AspNetCore.Authentication** SDKを使ってAuth0を統合する方法を説明します。 + +
    + Auth0のサービスを利用するには、Auth0 Dashboadに設定済みのアプリケーションがある必要があります。Auth0アプリケーションは、開発中のプロジェクトに対してどのように認証が動作して欲しいかを構成する場所です。 + + ### アプリケーションを構成する + + 対話型のセレクターを使ってAuth0アプリケーションを新規作成するか、統合したいプロジェクトを表す既存のアプリケーションを選択します。Auth0のすべてのアプリケーションには英数字からなる一意のクライアントIDが割り当てられており、アプリケーションのコードがSDKを通じてAuth0 + APIを呼び出す際に使用されます。 + + このクイックスタートを使って構成されたすべての設定は、[Dashboard](https://manage.auth0.com/#/)のアプリケーションを自動更新します。今後、アプリケーションの管理もDashboardで行えます。 + + 完了済みの構成を見てみたい場合は、サンプルアプリケーションをご覧ください。 + + ### Callback URLを構成する + + Callback URLとは、Auth0がユーザーを認証後にリダイレクトするアプリケーション内URLです。設定されていない場合、ユーザーはログイン後にアプリケーションに戻りません。 + + + サンプルプロジェクトに沿って進めている場合は、`http://localhost:3000/callback`に設定してください。 + + + ### ログアウトURLを構成する + + ログアウトURLとは、Auth0がユーザーをログアウト後にリダイレクトするアプリケーション内URLです。設定されていない場合、ユーザーはアプリケーションからログアウトできず、エラーを受け取ります。 + + + サンプルプロジェクトに沿って進めている場合は、`http://localhost:3000`に設定してください。 + +
    + +
    + ### Nugetからインストールする + + Auth0をASP.NET Coreと統合するには、`Auth0.AspNetCore.Authentication`[Nugetパッケージ](https://www.nuget.org/packages/Auth0.AspNetCore.Authentication/)をアプリケーションにインストールすることでSDKを使用できます。 + + ### ミドルウェアを構成する + + ASP.NET + Coreアプリケーションで認証を可能にするには、SDKが提供するミドルウェアを使います。`Program.cs`ファイルに移動して`builder.Services.AddAuth0WebAppAuthentication()`を呼び出し、SDKのミドルウェアを登録します。 + + `Domain`と`ClientId`は必ず構成してください。SDKがどのAuth0テナントとアプリケーションを使用すべきかを認識するために必要となるフィールドです。 + + 認証と認可が`Program.cs`ファイルで有効になったことを確認します。 +
    + +
    + ユーザーによるASP.NET MVCアプリケーションへのログインを許可するには、コントローラーに`Login`アクションを追加します。 + + `HttpContext.ChallengeAsync()`を呼び出し、`Auth0Constants.AuthenticationScheme`を認証スキームとして渡します。これによりSDKが内部に登録しているOIDC認証ハンドラーが発動されます。関連する`authenticationProperties`も必ず指定してください。構築は`LoginAuthenticationPropertiesBuilder`で行えます。 + + `HttpContext.ChallengeAsync()`の呼び出し成功後、ユーザーはAuth0にリダイレクトされます。その後アプリケーションにリダイレクトで戻された際に、OIDCミドルウェアとクッキーミドルウェアの両方にサインインしています。これにより、ユーザーは後続の要求でも認証されるようになります。 + + + ##### チェックポイント + + Loginの構成が完了したら、アプリケーションを実行して次の点を確認します: + + - `Login`アクションに移動すると、Auth0にリダイレクトされる。 + - 資格情報を入力すると、リダイレクトでアプリケーションに戻る。 + +
    + +
    + ミドルウェアはAuth0からトークンを取得すると、IDトークンからユーザー情報とクレームを抽出し、コントローラーで`User.Claims`プロパティとして利用できるようにします。 + + ユーザーの名前、メールアドレス、プロファイル画像を表示するカスタムユーザープロファイルを作成するには、`User`から関連する情報を取得し、コントローラー内からビューに渡します。 + + + ##### チェックポイント + + ユーザープロファイルを表示するようアクションをセットアップし終えたら、アプリケーションを実行して次の点を確認します: + + - ログイン成功後に`Profile`アクションに移動すると、ユーザープロファイルが表示される。 + +
    + +
    + コントローラーのアクション内から`HttpContext.SignOutAsync`を`CookieAuthenticationDefaults.AuthenticationScheme`認証スキームで呼び出すと、ユーザーをアプリケーションからログアウトさせられます。 + + さらに、ユーザーをAuth0からもログアウトさせたい場合は(これによりシングルサインオンに依拠している他のアプリケーションからもログアウトさせる可能性があります)、`HttpContext.SignOutAsync`を`Auth0Constants.AuthenticationScheme`認証スキームで呼び出します。また、`LogoutAuthenticationPropertiesBuilder`を使って構築できる適切な`authenticationProperties`も同じ認証スキームで呼び出します。 + + + ##### チェックポイント + + Logoutの構成が完了したら、アプリケーションを実行して次の点を確認します: + + - `Logout`アクションに移動すると、ユーザーが確実にログアウトする。 + - Auth0からもログアウトすると、Auth0にリダイレクトされ、即座にアプリケーションにリダイレクトで戻される。 + +
    + + ## 次のステップ + + 成功です!ここまで来れば、アプリケーションにログイン、ログアウト、ユーザープロファイル情報が備わっているはずです。 + + これでクイックスタートチュートリアルは終了ですが、機能はまだまだたくさんあります。Auth0でできることについて詳しくは、以下をご覧ください。 + + * [Auth0 Dashboard](https://manage.auth0.com/#) - Auth0のテナントやアプリケーションを構成して管理する方法について説明します + * [auth0-aspnetcore-authentication SDK](https://github.com/auth0/auth0-aspnetcore-authentication) - このチュートリアルで使用されているSDKをより詳しく説明します + * [Auth0 Marketplace](https://marketplace.auth0.com/) - Auth0の機能性を拡張できる各種の統合を見つけられます +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    diff --git a/main/docs/ja-jp/quickstart/webapp/aspnet-owin/interactive.mdx b/main/docs/ja-jp/quickstart/webapp/aspnet-owin/interactive.mdx index 785c83b2d..4ad942b5d 100644 --- a/main/docs/ja-jp/quickstart/webapp/aspnet-owin/interactive.mdx +++ b/main/docs/ja-jp/quickstart/webapp/aspnet-owin/interactive.mdx @@ -1,199 +1,201 @@ ---- -title: "ASP.NET OWINアプリケーションにログインを追加する" -permalink: "interactive" -'description': "このガイドは、新規または既存のASP.NET OWINアプリケーションにMicrosoft.Owin.Security.OpenIdConnect Nugetパッケージを使ってAuth0を統合する方法を説明します。" -'og:title': "ASP.NET OWINアプリケーションにログインを追加する" -'og:description': "このガイドは、新規または既存のASP.NET OWINアプリケーションにMicrosoft.Owin.Security.OpenIdConnect Nugetパッケージを使ってAuth0を統合する方法を説明します。" -'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/asp.png" -'twitter:title': "ASP.NET OWINアプリケーションにログインを追加する" -'twitter:description': "このガイドは、新規または既存のASP.NET OWINアプリケーションにMicrosoft.Owin.Security.OpenIdConnect Nugetパッケージを使ってAuth0を統合する方法を説明します。" -sidebarTitle: ASP.NET OWIN -mode: wide ---- - -import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; -import { LoggedInForm } from "/snippets/Login.jsx"; -import WebConfig from "/snippets/quickstart/webapp/aspnet-owin/web-config.mdx" -import AccountController1 from "/snippets/quickstart/webapp/aspnet-owin/AccountController1.mdx" -import AccountController2 from "/snippets/quickstart/webapp/aspnet-owin/AccountController2.mdx" -import AccountController3 from "/snippets/quickstart/webapp/aspnet-owin/AccountController3.mdx" - -export const sections = [ - { id: "auth0を構成する", title: "Auth0を構成する" }, - { id: "プロジェクトを構成する", title: "プロジェクトを構成する" }, - { id: "ミドルウェアを構成する", title: "ミドルウェアを構成する" }, - { id: "アプリケーションにログインを追加する", title: "アプリケーションにログインを追加する" }, - { id: "アプリケーションにログアウトを追加する", title: "アプリケーションにログアウトを追加する" }, - { id: "ユーザープロファイル情報を表示する", title: "ユーザープロファイル情報を表示する" } -] - - - - Auth0を使用すると、アプリケーションに手軽に認証を追加して、ユーザープロファイル情報にアクセスすることができます。このガイドは、新規または既存のASP.NET - OWINアプリケーションに`Microsoft.Owin.Security.OpenIdConnect` Nugetパッケージを使ってAuth0を統合する方法を説明します。 - -
    - Auth0のサービスを利用するには、Auth0 Dashboadに設定済みのアプリケーションがある必要があります。Auth0アプリケーションは、開発中のプロジェクトに対してどのように認証が動作して欲しいかを構成する場所です。 - - ### アプリケーションを構成する - - 対話型のセレクターを使ってAuth0アプリケーションを新規作成するか、統合したいプロジェクトを表す既存のアプリケーションを選択します。Auth0のすべてのアプリケーションには英数字からなる一意のクライアントIDが割り当てられており、アプリケーションのコードがSDKを通じてAuth0 - APIを呼び出す際に使用されます。 - - このクイックスタートを使って構成されたすべての設定は、[Dashboard](https://manage.auth0.com/#/)のアプリケーションを自動更新します。今後、アプリケーションの管理もDashboardで行えます。 - - 完了済みの構成を見てみたい場合は、サンプルアプリケーションをご覧ください。 - - ### Callback URLを構成する - - Callback URLとは、Auth0がユーザーを認証後にリダイレクトするアプリケーション内URLです。設定されていない場合、ユーザーはログイン後にアプリケーションに戻りません。 - - - サンプルプロジェクトに沿って進めている場合は、`http://localhost:3000``/callback`に設定してください。 - - - ### ログアウトURLを構成する - - ログアウトURLとは、Auth0がユーザーをログアウト後にリダイレクトするアプリケーション内URLです。設定されていない場合、ユーザーはアプリケーションからログアウトできず、エラーを受け取ります。 - - - サンプルプロジェクトに沿って進めている場合は、`http://localhost:3000`に設定してください。 - -
    - -
    - ### NuGetからインストールする - - Auth0をASP.NET - OWINに統合するには、`Microsoft.Owin.Security.OpenIdConnect`および`Microsoft.Owin.Security.Cookies` - NuGetパッケージが使用できます。 - - ```text lines - Install-Package Microsoft.Owin.Security.OpenIdConnect - Install-Package Microsoft.Owin.Security.Cookies - ``` - - - OWINクッキーミドルウェアとSystem.Webクッキーを同時に構成すると不具合が発生します。この問題の影響を抑えるには、詳細について[「System.Web cookie integration - issues(System.Webクッキーの統合不具合)」ドキュメント](https://github.com/aspnet/AspNetKatana/wiki/System.Web-response-cookie-integration-issues)でご確認ください。 - - - ### 資格情報を構成する - - SDKが適切に動作するためには、`Web.config`で次のプロパティを設定します: - - - `auth0:Domain`:Auth0テナントのドメインです。Auth0 - Dashboardにあるアプリケーションの**[Settings(設定)]** の[Domain(ドメイン)]フィールドで確認できます。[カスタムドメイン](/docs/ja-jp/custom-domains)を使用している場合は、この値をカスタムドメインの値に設定してください。 - - `auth0:ClientId`:Auth0 Dashboardで作成したAuth0アプリケーションのIDです。Auth0 - Dashboardにあるアプリケーションの**[Settings(設定)]** の[Client ID(クライアントID)]フィールドで確認できます。 -
    - -
    - ASP.NET OWINアプリケーションで認証を有効にするには、StartupクラスのConfigurationメソッドに移動し、クッキーミドルウェアとOIDCミドルウェアを構成します。 - - 認証の作動にはクッキーミドルウェアとOpenID Connectミドルウェアの両方が(この順番で)要求されるため、どちらも必ず登録してください。OpenID - ConnectミドルウェアはAuth0による認証をハンドリングします。ユーザーの認証が完了すると、そのIDはクッキーミドルウェアに保存されます。 - - コードスニペットではAuthenticationTypeが**Auth0** に設定されています。次のセクションでAuthenticationTypeを使用しOpenID - Connectミドルウェアにチャレンジして、認証フローを開始します。RedirectToIdentityProvider通知イベントが正しいログアウトURLを構築します。 -
    - -
    - ユーザーによるASP.NET OWINアプリケーションへのログインを許可するには、コントローラーに`Login`アクションを追加します。 - - `HttpContext.GetOwinContext().Authentication.Challenge`を呼び出し、認証スキームとして`"Auth0"`を渡します。これにより、以前登録されたOIDC認証ハンドラーが発動されます。対応する`AuthenticationProperties`(`RedirectUri`含む)を必ず指定してください。 - - `HttpContext.GetOwinContext().Authentication.Challenge`の呼び出し成功後、ユーザーはAuth0にリダイレクトされます。その後アプリケーションにリダイレクトで戻された際に、OIDCミドルウェアとクッキーミドルウェアの両方にサインインしています。これにより、ユーザーは後続の要求でも認証されるようになります。 - - - ##### チェックポイント - - Loginの構成が完了したら、アプリケーションを実行して次の点を確認します: - - - `Login`アクションに移動すると、Auth0にリダイレクトされる。 - - 資格情報を入力すると、リダイレクトでアプリケーションに戻る。 - -
    - -
    - ユーザーをアプリケーションからログアウトさせるには、コントローラーのアクションから`HttpContext.GetOwinContext().Authentication.SignOut`を`CookieAuthenticationDefaults.AuthenticationType`認証スキームで呼び出します。 - - さらに、ユーザーをAuth0からログアウトさせたい場合は(この際にシングルサインオンに依拠している他のアプリケーションからもログアウトさせる可能性があります)、 - `HttpContext.GetOwinContext().Authentication.SignOut`を`"Auth0"`認証スキームで呼び出します。 - - - ##### チェックポイント - - Logoutの構成が完了したら、アプリケーションを実行して次の点を確認します: - - - `Logout`アクションに移動すると、ユーザーがログアウトする。 - - ログアウト中Auth0にリダイレクトし、その後ログアウト中にただちにアプリケーションにリダイレクトで戻る。 - -
    - -
    - ミドルウェアはAuth0からトークンを取得すると、IDトークンからユーザー情報とクレームを抽出し、`ClaimsIdentity`として利用できるようにします。抽出した情報にはコントローラーの`User`プロパティを使ってアクセスします。 - - ユーザープロファイルを作成するには、`User`からユーザーの名前、メールアドレス、プロファイル画像を取得し、コントローラー内からビューに渡します。 - - - ##### チェックポイント - - ユーザープロファイルを表示するようアクションをセットアップし終えたら、アプリケーションを実行して次の点を確認します: - - - ログイン成功後に`Profile`アクションに移動すると、ユーザープロファイルが表示される。 - -
    - - ## 次のステップ - - 成功です!ここまで来れば、アプリケーションにログイン、ログアウト、ユーザープロファイル情報が備わっているはずです。 - - これでクイックスタートチュートリアルは終了ですが、機能はまだまだたくさんあります。Auth0でできることについて詳しくは、以下をご覧ください。 - - * [Auth0 Dashboard](https://manage.auth0.com/#) - Auth0のテナントやアプリケーションを構成して管理する方法について説明します - * [Auth0 Marketplace](https://marketplace.auth0.com/) - Auth0の機能性を拡張できる各種の統合を見つけられます -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    +--- +title: "ASP.NET OWINアプリケーションにログインを追加する" +permalink: "interactive" +'description': "このガイドは、新規または既存のASP.NET OWINアプリケーションにMicrosoft.Owin.Security.OpenIdConnect Nugetパッケージを使ってAuth0を統合する方法を説明します。" +'og:title': "ASP.NET OWINアプリケーションにログインを追加する" +'og:description': "このガイドは、新規または既存のASP.NET OWINアプリケーションにMicrosoft.Owin.Security.OpenIdConnect Nugetパッケージを使ってAuth0を統合する方法を説明します。" +'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/asp.png" +'twitter:title': "ASP.NET OWINアプリケーションにログインを追加する" +'twitter:description': "このガイドは、新規または既存のASP.NET OWINアプリケーションにMicrosoft.Owin.Security.OpenIdConnect Nugetパッケージを使ってAuth0を統合する方法を説明します。" +sidebarTitle: ASP.NET OWIN +mode: wide +--- + +import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; +import { LoggedInForm } from "/snippets/Login.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + +import WebConfig from "/snippets/quickstart/webapp/aspnet-owin/web-config.mdx" +import AccountController1 from "/snippets/quickstart/webapp/aspnet-owin/AccountController1.mdx" +import AccountController2 from "/snippets/quickstart/webapp/aspnet-owin/AccountController2.mdx" +import AccountController3 from "/snippets/quickstart/webapp/aspnet-owin/AccountController3.mdx" + +export const sections = [ + { id: "auth0を構成する", title: "Auth0を構成する" }, + { id: "プロジェクトを構成する", title: "プロジェクトを構成する" }, + { id: "ミドルウェアを構成する", title: "ミドルウェアを構成する" }, + { id: "アプリケーションにログインを追加する", title: "アプリケーションにログインを追加する" }, + { id: "アプリケーションにログアウトを追加する", title: "アプリケーションにログアウトを追加する" }, + { id: "ユーザープロファイル情報を表示する", title: "ユーザープロファイル情報を表示する" } +] + + + + Auth0を使用すると、アプリケーションに手軽に認証を追加して、ユーザープロファイル情報にアクセスすることができます。このガイドは、新規または既存のASP.NET + OWINアプリケーションに`Microsoft.Owin.Security.OpenIdConnect` Nugetパッケージを使ってAuth0を統合する方法を説明します。 + +
    + Auth0のサービスを利用するには、Auth0 Dashboadに設定済みのアプリケーションがある必要があります。Auth0アプリケーションは、開発中のプロジェクトに対してどのように認証が動作して欲しいかを構成する場所です。 + + ### アプリケーションを構成する + + 対話型のセレクターを使ってAuth0アプリケーションを新規作成するか、統合したいプロジェクトを表す既存のアプリケーションを選択します。Auth0のすべてのアプリケーションには英数字からなる一意のクライアントIDが割り当てられており、アプリケーションのコードがSDKを通じてAuth0 + APIを呼び出す際に使用されます。 + + このクイックスタートを使って構成されたすべての設定は、[Dashboard](https://manage.auth0.com/#/)のアプリケーションを自動更新します。今後、アプリケーションの管理もDashboardで行えます。 + + 完了済みの構成を見てみたい場合は、サンプルアプリケーションをご覧ください。 + + ### Callback URLを構成する + + Callback URLとは、Auth0がユーザーを認証後にリダイレクトするアプリケーション内URLです。設定されていない場合、ユーザーはログイン後にアプリケーションに戻りません。 + + + サンプルプロジェクトに沿って進めている場合は、`http://localhost:3000``/callback`に設定してください。 + + + ### ログアウトURLを構成する + + ログアウトURLとは、Auth0がユーザーをログアウト後にリダイレクトするアプリケーション内URLです。設定されていない場合、ユーザーはアプリケーションからログアウトできず、エラーを受け取ります。 + + + サンプルプロジェクトに沿って進めている場合は、`http://localhost:3000`に設定してください。 + +
    + +
    + ### NuGetからインストールする + + Auth0をASP.NET + OWINに統合するには、`Microsoft.Owin.Security.OpenIdConnect`および`Microsoft.Owin.Security.Cookies` + NuGetパッケージが使用できます。 + + ```text lines + Install-Package Microsoft.Owin.Security.OpenIdConnect + Install-Package Microsoft.Owin.Security.Cookies + ``` + + + OWINクッキーミドルウェアとSystem.Webクッキーを同時に構成すると不具合が発生します。この問題の影響を抑えるには、詳細について[「System.Web cookie integration + issues(System.Webクッキーの統合不具合)」ドキュメント](https://github.com/aspnet/AspNetKatana/wiki/System.Web-response-cookie-integration-issues)でご確認ください。 + + + ### 資格情報を構成する + + SDKが適切に動作するためには、`Web.config`で次のプロパティを設定します: + + - `auth0:Domain`:Auth0テナントのドメインです。Auth0 + Dashboardにあるアプリケーションの**[Settings(設定)]** の[Domain(ドメイン)]フィールドで確認できます。[カスタムドメイン](/docs/ja-jp/custom-domains)を使用している場合は、この値をカスタムドメインの値に設定してください。 + - `auth0:ClientId`:Auth0 Dashboardで作成したAuth0アプリケーションのIDです。Auth0 + Dashboardにあるアプリケーションの**[Settings(設定)]** の[Client ID(クライアントID)]フィールドで確認できます。 +
    + +
    + ASP.NET OWINアプリケーションで認証を有効にするには、StartupクラスのConfigurationメソッドに移動し、クッキーミドルウェアとOIDCミドルウェアを構成します。 + + 認証の作動にはクッキーミドルウェアとOpenID Connectミドルウェアの両方が(この順番で)要求されるため、どちらも必ず登録してください。OpenID + ConnectミドルウェアはAuth0による認証をハンドリングします。ユーザーの認証が完了すると、そのIDはクッキーミドルウェアに保存されます。 + + コードスニペットではAuthenticationTypeが**Auth0** に設定されています。次のセクションでAuthenticationTypeを使用しOpenID + Connectミドルウェアにチャレンジして、認証フローを開始します。RedirectToIdentityProvider通知イベントが正しいログアウトURLを構築します。 +
    + +
    + ユーザーによるASP.NET OWINアプリケーションへのログインを許可するには、コントローラーに`Login`アクションを追加します。 + + `HttpContext.GetOwinContext().Authentication.Challenge`を呼び出し、認証スキームとして`"Auth0"`を渡します。これにより、以前登録されたOIDC認証ハンドラーが発動されます。対応する`AuthenticationProperties`(`RedirectUri`含む)を必ず指定してください。 + + `HttpContext.GetOwinContext().Authentication.Challenge`の呼び出し成功後、ユーザーはAuth0にリダイレクトされます。その後アプリケーションにリダイレクトで戻された際に、OIDCミドルウェアとクッキーミドルウェアの両方にサインインしています。これにより、ユーザーは後続の要求でも認証されるようになります。 + + + ##### チェックポイント + + Loginの構成が完了したら、アプリケーションを実行して次の点を確認します: + + - `Login`アクションに移動すると、Auth0にリダイレクトされる。 + - 資格情報を入力すると、リダイレクトでアプリケーションに戻る。 + +
    + +
    + ユーザーをアプリケーションからログアウトさせるには、コントローラーのアクションから`HttpContext.GetOwinContext().Authentication.SignOut`を`CookieAuthenticationDefaults.AuthenticationType`認証スキームで呼び出します。 + + さらに、ユーザーをAuth0からログアウトさせたい場合は(この際にシングルサインオンに依拠している他のアプリケーションからもログアウトさせる可能性があります)、 + `HttpContext.GetOwinContext().Authentication.SignOut`を`"Auth0"`認証スキームで呼び出します。 + + + ##### チェックポイント + + Logoutの構成が完了したら、アプリケーションを実行して次の点を確認します: + + - `Logout`アクションに移動すると、ユーザーがログアウトする。 + - ログアウト中Auth0にリダイレクトし、その後ログアウト中にただちにアプリケーションにリダイレクトで戻る。 + +
    + +
    + ミドルウェアはAuth0からトークンを取得すると、IDトークンからユーザー情報とクレームを抽出し、`ClaimsIdentity`として利用できるようにします。抽出した情報にはコントローラーの`User`プロパティを使ってアクセスします。 + + ユーザープロファイルを作成するには、`User`からユーザーの名前、メールアドレス、プロファイル画像を取得し、コントローラー内からビューに渡します。 + + + ##### チェックポイント + + ユーザープロファイルを表示するようアクションをセットアップし終えたら、アプリケーションを実行して次の点を確認します: + + - ログイン成功後に`Profile`アクションに移動すると、ユーザープロファイルが表示される。 + +
    + + ## 次のステップ + + 成功です!ここまで来れば、アプリケーションにログイン、ログアウト、ユーザープロファイル情報が備わっているはずです。 + + これでクイックスタートチュートリアルは終了ですが、機能はまだまだたくさんあります。Auth0でできることについて詳しくは、以下をご覧ください。 + + * [Auth0 Dashboard](https://manage.auth0.com/#) - Auth0のテナントやアプリケーションを構成して管理する方法について説明します + * [Auth0 Marketplace](https://marketplace.auth0.com/) - Auth0の機能性を拡張できる各種の統合を見つけられます +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    diff --git a/main/docs/ja-jp/quickstart/webapp/django/interactive.mdx b/main/docs/ja-jp/quickstart/webapp/django/interactive.mdx index 4c4b0bcc6..18c9dd1f9 100644 --- a/main/docs/ja-jp/quickstart/webapp/django/interactive.mdx +++ b/main/docs/ja-jp/quickstart/webapp/django/interactive.mdx @@ -21,6 +21,8 @@ import Urls from "/snippets/quickstart/webapp/django/urls.py.mdx"; import Views from "/snippets/quickstart/webapp/django/views.py.mdx"; import Views2 from "/snippets/quickstart/webapp/django/views.py2.mdx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + export const sections = [ { id: "auth0を構成する", title: "Auth0を構成する" }, { id: "依存関係をインストールする", title: "依存関係をインストールする" }, @@ -204,48 +206,48 @@ export const codeExample = ` AUTH0_CLIENT_ID={yourClientId} - + - + - + - + - + - + - + - + - + - + diff --git a/main/docs/ja-jp/quickstart/webapp/golang/interactive.mdx b/main/docs/ja-jp/quickstart/webapp/golang/interactive.mdx index b9f413fea..d23bb9f78 100644 --- a/main/docs/ja-jp/quickstart/webapp/golang/interactive.mdx +++ b/main/docs/ja-jp/quickstart/webapp/golang/interactive.mdx @@ -1,340 +1,342 @@ ---- -title: "Goアプリケーションにログインを追加する" -permalink: "interactive" -'description': "このガイドは、新規または既存のGo WebアプリケーションにAuth0を統合する方法を説明します。" -'og:title': "Goアプリケーションにログインを追加する" -'og:description': "このガイドは、新規または既存のGo WebアプリケーションにAuth0を統合する方法を説明します。" -'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/golang.png" -'twitter:title': "Goアプリケーションにログインを追加する" -'twitter:description': "このガイドは、新規または既存のGo WebアプリケーションにAuth0を統合する方法を説明します。" -sidebarTitle: Go -mode: wide ---- - -import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; -import { LoggedInForm } from "/snippets/Login.jsx"; -import Auth from "/snippets/quickstart/webapp/golang/auth.go.mdx"; -import Callback from "/snippets/quickstart/webapp/golang/callback.go.mdx"; -import Env from "/snippets/quickstart/webapp/golang/.env.mdx"; -import Go from "/snippets/quickstart/webapp/golang/go.mod.mdx"; -import Isauthenticated from "/snippets/quickstart/webapp/golang/isAuthenticated.go.mdx"; -import Login from "/snippets/quickstart/webapp/golang/login.go.mdx"; -import Logout from "/snippets/quickstart/webapp/golang/logout.go.mdx"; -import Main from "/snippets/quickstart/webapp/golang/main.go.mdx"; -import Router from "/snippets/quickstart/webapp/golang/router.go.mdx"; -import User from "/snippets/quickstart/webapp/golang/user.go.mdx"; - -export const sections = [ - { id: "auth0を構成する", title: "Auth0を構成する" }, - { id: "依存関係をインストールする", title: "依存関係をインストールする" }, - { id: "環境変数を構成する", title: "環境変数を構成する" }, - { id: "oauth2パッケージとopenid-connectパッケージを構成する", title: "OAuth2パッケージとOpenID Connectパッケージを構成する" }, - { id: "アプリケーションルートをセットアップする", title: "アプリケーションルートをセットアップする" }, - { id: "アプリケーションにログインを追加する", title: "アプリケーションにログインを追加する" }, - { id: "認証コールバックを処理する", title: "認証コールバックを処理する" }, - { id: "ユーザープロファイル情報を表示する", title: "ユーザープロファイル情報を表示する" }, - { id: "アプリケーションにログアウトを追加する", title: "アプリケーションにログアウトを追加する" }, - { id: "ルートを保護する", title: "ルートを保護する" }, - { id: "アプリケーションを仕上げる", title: "アプリケーションを仕上げる" } -] - - - - Auth0を使用すると、アプリケーションに手軽に認証を追加して、ユーザープロファイル情報にアクセスすることができますこのガイドは、新規または既存のGo WebアプリケーションにAuth0を統合する方法を説明します。 - -
    - Auth0のサービスを利用するには、Auth0 Dashboadに設定済みのアプリケーションがある必要があります。Auth0アプリケーションは、開発中のプロジェクトに対してどのように認証が動作して欲しいかを構成する場所です。 - - ### アプリケーションを構成する - - 対話型のセレクターを使ってAuth0アプリケーションを新規作成するか、統合したいプロジェクトを表す既存のアプリケーションを選択します。Auth0のすべてのアプリケーションには英数字からなる一意のクライアントIDが割り当てられており、アプリケーションのコードがSDKを通じてAuth0 - APIを呼び出す際に使用されます。 - - このクイックスタートを使って構成されたすべての設定は、[Dashboard](https://manage.auth0.com/dashboard/us/auth0-dsepaid/)のアプリケーションを自動更新します。今後、アプリケーションの管理もDashboardで行えます。 - - 完了済みの構成を見てみたい場合は、サンプルアプリケーションをご覧ください。 - - ### Callback URLを構成する - - Callback URLとは、Auth0がユーザーを認証後にリダイレクトするアプリケーション内URLです。設定されていない場合、ユーザーはログイン後にアプリケーションに戻りません。 - - - サンプルプロジェクトに沿って進めている場合は、`http://localhost:3000``/callback`に設定してください。 - - - ### ログアウトURLを構成する - - ログアウトURLとは、Auth0がユーザーをログアウト後にリダイレクトするアプリケーション内URLです。設定されていない場合、ユーザーはアプリケーションからログアウトできず、エラーを受け取ります。 - - - サンプルプロジェクトに沿って進めている場合は、`http://localhost:3000`に設定してください。 - -
    - -
    - `go.mod`ファイルを作成して、アプリケーションの依存関係をすべてリストします。 - - GoアプリケーションでAuth0を統合するには、`coreos/go-oidc/v3`パッケージと`x/oauth2`パッケージを追加します。 - - OIDCパッケージとOAuth2パッケージに加え、`joho/godotenv`、`gin-gonic/gin`、`gin-contrib/sessions`を追加します。 - - - この例ではルーティングに`gin`を使用しますが、お好きなルーターを使用できます。 - - - `go.mod`ファイルを必要な依存関係で保存し、ターミナルで次のコマンドを使ってインストールします: - - ```text lines - go mod download - ``` -
    - -
    - プロジェクトディレクトリのルート内の`.env`で以下の環境変数を設定してください: - - - **AUTH0_DOMAIN** :Auth0テナントのドメインです。Auth0 - Dashboardにあるアプリケーションの[Settings(設定)]の[Domain(ドメイン)]フィールドで確認してください。カスタムドメインを使用する場合は、この値をカスタムドメインの値に設定してください。 - - **AUTH0_CLIENT_ID** :このクイックスタートで前にセットアップしたAuth0アプリケーションのIDです。Auth0 - Dashboardにあるアプリケーションの[Settings(設定)]の[Client ID(クライアントID)]フィールドで確認してください。 - - **AUTH0_CLIENT_SECRET** :このクイックスタートで前にセットアップしたAuth0アプリケーションのシークレットです。Auth0 - Dashboardにあるアプリケーションの[Settings(設定)]の[Client Secret(クライアントシークレット)]フィールドで確認してください。 - - **AUTH0_CALLBACK_URL** :認証成功後にユーザーをリダイレクトするためにAuth0が使用するURLです。 -
    - -
    - 次にOAuth2パッケージとOpenID Connectパッケージを構成します。 - - `platform/authenticator`フォルダーに`auth.go`という名前のファイルを作成します。このパッケージ内で、[OAuth2](https://godoc.org/golang.org/x/oauth2)クライアントと[OIDC](https://godoc.org/github.com/coreos/go-oidc)クライアントを構成してリターンするメソッドを作成し、IDトークンを検証するもう1つのメソッドを作成します。 -
    - -
    - `platform/router`フォルダーに`router.go`という名前のファイルを作成します。このパッケージで、[github.com/gin-gonic/gin](https://github.com/gin-gonic/gin)を使ってルートを構成、リターンするメソッドを作成します。`login`ハンドラーと`callback`ハンドラーで使用するために、`Authenticator`のインスタンスをメソッドに渡すことになります。 -
    - -
    - ユーザーが自分で認証するには、`/login`ルートを処理するハンドラー関数を作成する必要があります。 - - `web/app/login`フォルダーに`login.go`という名前のファイルを作成し、`Handler`関数を追加します。ハンドラーの実行時にユーザーはAuth0へリダイレクトされ、資格情報を入力できるようになります。 - - `/login`ルートを呼び出すには、`web/template`ディレクトリにある`home.html`テンプレートに`/login`へのリンクを追加します。 -
    - -
    - ユーザーはAuth0ユニバーサルログインページを使って認証すると、 `/callback`ルートでアプリに戻ります。 - - `web/app/callback`フォルダーに`callback.go`という名前のファイルを作成し、`Handler`関数を追加します。 - - このハンドラーはAuth0によって提供された`code`クエリ文字列を受け取り、IDトークンおよびアクセストークンと交換します。 - - IDトークンが有効である場合、セッションにプロファイル情報とアクセストークンが保存されます。プロファイル情報はIDトークンに含まれるクレームに基づいています。セッションストレージは、必要に応じてアプリケーションがこの情報にアクセスすることを許可します。 -
    - -
    - ユーザーがログインできるようになったら、認証済みのユーザーに関連付けられたプロファイル情報を取得し、使用できるようにしたいと考えるはずです。 - - ニックネームやプロフィール写真といったプロファイル情報は、前のセッションで保存された`profile`からアクセスできます。 - - `web/app/user/user.go`で`/user`エンドポイント用のハンドラーを作成し、対応するHTMLファイルを返します。`profile`が`ctx.HTML()`に渡されているため、同じHTMLファイル内の`picture`や`nickname`といったプロファイル情報にアクセスできます。 - - このようなHTMLファイルは以下の例のように見えることがありますが、カスタムクレームを含め、いかなるプロファイル情報も取得できます。 -
    - -
    - ユーザーをログアウトさせるには、セッションのデータを消去し、ユーザーをAuth0ログアウトエンドポイントにリダイレクトします。詳細は[ログアウトドキュメント](/docs/ja-jp/logout)をご覧ください。 - - `web/app/logout`フォルダーに`logout.go`という名前のファイルを作成し、ユーザーをAuth0ログアウトエンドポイントにリダイレクトするために`Handler`関数を追加します。 - - `returnTo` URLは、アプリケーションの設定セクションで[Allowed Logout URLs(許可されているログアウトURL)]のリストに載っていなければなりません。詳細は「[ログアウト後にユーザーをリダイレクトする](/docs/ja-jp/logout/guides/redirect-users-after-logout)」をご覧ください。 - - `web/static/js`フォルダーに`user.js`という名前のファイルを作成し、ログインしたユーザーからクッキーを削除するためのコードを追加します。 -
    - -
    - 推奨プラクティスでは、認証されたユーザーだけが特定のルートにアクセスできるようにするべきです。認証されていないユーザーが保護されたルートにアクセスしようとした場合、アプリケーションによってリダイレクトされる必要があります。 - - この場合、HTTPの要求に接続するミドルウェアを実装します。ミドルウェアの関数は、要求がエンドポイントハンドラーにルートされるべきか、ブロックされるべきかを決定します。 - - `platform/middleware`に`isAuthenticated.go`という名前のファイルを作成し、`profile`セッションキーに基づいてユーザーが認証されているかいないかをチェックする関数を追加します。認証されていないユーザーは、ミドルウェアがアプリケーションのルートへリダイレクトします。 - - ミドルウェアを作成すると、ルーターに追加することで、認証を必要とするすべてのルートにセットアップできます。 -
    - -
    - 鑑別工具とルーターの構成が完了したら、アプリケーションのエントリーポイントを使って全体を結び付けます。`main.go`内で、鑑別工具とルーターのインスタンスを作成すると鑑別工具インスタンスが渡されます。 - - `.env`ファイルを使用している場合は、`main()`関数の冒頭で`godotenv.Load()`を呼び出さなくてはなりません。 - - ターミナルで次のコマンドを使いアプリケーションを仕上げます: - - ```text lines - go run main.go - ``` -
    - - ## 次のステップ - - 成功です!ここまで来れば、アプリケーションにログイン、ログアウト、ユーザープロファイル情報が備わっているはずです。 - - これでクイックスタートチュートリアルは終了ですが、機能はまだまだたくさんあります。Auth0でできることについて詳しくは、以下をご覧ください。 - - * [Auth0 Dashboard](https://manage.auth0.com/#) - Auth0のテナントやアプリケーションを構成して管理する方法について説明します - * [Auth0 Marketplace](https://marketplace.auth0.com/) - Auth0の機能性を拡張できる各種の統合を見つけられます -
    - - - - - - - - - - - - - - - - -
    - - - - - - - - - - - - - -
    - - - - - - - - - - - - - - -
    - - - - - - - - - - - - - - - -
    - - - - - - - - - - - - - -
    - - - - - - - - - - - - - - -
    - - - - - - - - - - - - - - - -
    - - - - - - - - - - - - - -
    - - - - - - - - - - - - - - -
    - - - - - - - -
    - - - - - - - - - - - - - - +--- +title: "Goアプリケーションにログインを追加する" +permalink: "interactive" +'description': "このガイドは、新規または既存のGo WebアプリケーションにAuth0を統合する方法を説明します。" +'og:title': "Goアプリケーションにログインを追加する" +'og:description': "このガイドは、新規または既存のGo WebアプリケーションにAuth0を統合する方法を説明します。" +'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/golang.png" +'twitter:title': "Goアプリケーションにログインを追加する" +'twitter:description': "このガイドは、新規または既存のGo WebアプリケーションにAuth0を統合する方法を説明します。" +sidebarTitle: Go +mode: wide +--- + +import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; +import { LoggedInForm } from "/snippets/Login.jsx"; +import Auth from "/snippets/quickstart/webapp/golang/auth.go.mdx"; +import Callback from "/snippets/quickstart/webapp/golang/callback.go.mdx"; +import Env from "/snippets/quickstart/webapp/golang/.env.mdx"; +import Go from "/snippets/quickstart/webapp/golang/go.mod.mdx"; +import Isauthenticated from "/snippets/quickstart/webapp/golang/isAuthenticated.go.mdx"; +import Login from "/snippets/quickstart/webapp/golang/login.go.mdx"; +import Logout from "/snippets/quickstart/webapp/golang/logout.go.mdx"; +import Main from "/snippets/quickstart/webapp/golang/main.go.mdx"; +import Router from "/snippets/quickstart/webapp/golang/router.go.mdx"; +import User from "/snippets/quickstart/webapp/golang/user.go.mdx"; + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + +export const sections = [ + { id: "auth0を構成する", title: "Auth0を構成する" }, + { id: "依存関係をインストールする", title: "依存関係をインストールする" }, + { id: "環境変数を構成する", title: "環境変数を構成する" }, + { id: "oauth2パッケージとopenid-connectパッケージを構成する", title: "OAuth2パッケージとOpenID Connectパッケージを構成する" }, + { id: "アプリケーションルートをセットアップする", title: "アプリケーションルートをセットアップする" }, + { id: "アプリケーションにログインを追加する", title: "アプリケーションにログインを追加する" }, + { id: "認証コールバックを処理する", title: "認証コールバックを処理する" }, + { id: "ユーザープロファイル情報を表示する", title: "ユーザープロファイル情報を表示する" }, + { id: "アプリケーションにログアウトを追加する", title: "アプリケーションにログアウトを追加する" }, + { id: "ルートを保護する", title: "ルートを保護する" }, + { id: "アプリケーションを仕上げる", title: "アプリケーションを仕上げる" } +] + + + + Auth0を使用すると、アプリケーションに手軽に認証を追加して、ユーザープロファイル情報にアクセスすることができますこのガイドは、新規または既存のGo WebアプリケーションにAuth0を統合する方法を説明します。 + +
    + Auth0のサービスを利用するには、Auth0 Dashboadに設定済みのアプリケーションがある必要があります。Auth0アプリケーションは、開発中のプロジェクトに対してどのように認証が動作して欲しいかを構成する場所です。 + + ### アプリケーションを構成する + + 対話型のセレクターを使ってAuth0アプリケーションを新規作成するか、統合したいプロジェクトを表す既存のアプリケーションを選択します。Auth0のすべてのアプリケーションには英数字からなる一意のクライアントIDが割り当てられており、アプリケーションのコードがSDKを通じてAuth0 + APIを呼び出す際に使用されます。 + + このクイックスタートを使って構成されたすべての設定は、[Dashboard](https://manage.auth0.com/dashboard/us/auth0-dsepaid/)のアプリケーションを自動更新します。今後、アプリケーションの管理もDashboardで行えます。 + + 完了済みの構成を見てみたい場合は、サンプルアプリケーションをご覧ください。 + + ### Callback URLを構成する + + Callback URLとは、Auth0がユーザーを認証後にリダイレクトするアプリケーション内URLです。設定されていない場合、ユーザーはログイン後にアプリケーションに戻りません。 + + + サンプルプロジェクトに沿って進めている場合は、`http://localhost:3000``/callback`に設定してください。 + + + ### ログアウトURLを構成する + + ログアウトURLとは、Auth0がユーザーをログアウト後にリダイレクトするアプリケーション内URLです。設定されていない場合、ユーザーはアプリケーションからログアウトできず、エラーを受け取ります。 + + + サンプルプロジェクトに沿って進めている場合は、`http://localhost:3000`に設定してください。 + +
    + +
    + `go.mod`ファイルを作成して、アプリケーションの依存関係をすべてリストします。 + + GoアプリケーションでAuth0を統合するには、`coreos/go-oidc/v3`パッケージと`x/oauth2`パッケージを追加します。 + + OIDCパッケージとOAuth2パッケージに加え、`joho/godotenv`、`gin-gonic/gin`、`gin-contrib/sessions`を追加します。 + + + この例ではルーティングに`gin`を使用しますが、お好きなルーターを使用できます。 + + + `go.mod`ファイルを必要な依存関係で保存し、ターミナルで次のコマンドを使ってインストールします: + + ```text lines + go mod download + ``` +
    + +
    + プロジェクトディレクトリのルート内の`.env`で以下の環境変数を設定してください: + + - **AUTH0_DOMAIN** :Auth0テナントのドメインです。Auth0 + Dashboardにあるアプリケーションの[Settings(設定)]の[Domain(ドメイン)]フィールドで確認してください。カスタムドメインを使用する場合は、この値をカスタムドメインの値に設定してください。 + - **AUTH0_CLIENT_ID** :このクイックスタートで前にセットアップしたAuth0アプリケーションのIDです。Auth0 + Dashboardにあるアプリケーションの[Settings(設定)]の[Client ID(クライアントID)]フィールドで確認してください。 + - **AUTH0_CLIENT_SECRET** :このクイックスタートで前にセットアップしたAuth0アプリケーションのシークレットです。Auth0 + Dashboardにあるアプリケーションの[Settings(設定)]の[Client Secret(クライアントシークレット)]フィールドで確認してください。 + - **AUTH0_CALLBACK_URL** :認証成功後にユーザーをリダイレクトするためにAuth0が使用するURLです。 +
    + +
    + 次にOAuth2パッケージとOpenID Connectパッケージを構成します。 + + `platform/authenticator`フォルダーに`auth.go`という名前のファイルを作成します。このパッケージ内で、[OAuth2](https://godoc.org/golang.org/x/oauth2)クライアントと[OIDC](https://godoc.org/github.com/coreos/go-oidc)クライアントを構成してリターンするメソッドを作成し、IDトークンを検証するもう1つのメソッドを作成します。 +
    + +
    + `platform/router`フォルダーに`router.go`という名前のファイルを作成します。このパッケージで、[github.com/gin-gonic/gin](https://github.com/gin-gonic/gin)を使ってルートを構成、リターンするメソッドを作成します。`login`ハンドラーと`callback`ハンドラーで使用するために、`Authenticator`のインスタンスをメソッドに渡すことになります。 +
    + +
    + ユーザーが自分で認証するには、`/login`ルートを処理するハンドラー関数を作成する必要があります。 + + `web/app/login`フォルダーに`login.go`という名前のファイルを作成し、`Handler`関数を追加します。ハンドラーの実行時にユーザーはAuth0へリダイレクトされ、資格情報を入力できるようになります。 + + `/login`ルートを呼び出すには、`web/template`ディレクトリにある`home.html`テンプレートに`/login`へのリンクを追加します。 +
    + +
    + ユーザーはAuth0ユニバーサルログインページを使って認証すると、 `/callback`ルートでアプリに戻ります。 + + `web/app/callback`フォルダーに`callback.go`という名前のファイルを作成し、`Handler`関数を追加します。 + + このハンドラーはAuth0によって提供された`code`クエリ文字列を受け取り、IDトークンおよびアクセストークンと交換します。 + + IDトークンが有効である場合、セッションにプロファイル情報とアクセストークンが保存されます。プロファイル情報はIDトークンに含まれるクレームに基づいています。セッションストレージは、必要に応じてアプリケーションがこの情報にアクセスすることを許可します。 +
    + +
    + ユーザーがログインできるようになったら、認証済みのユーザーに関連付けられたプロファイル情報を取得し、使用できるようにしたいと考えるはずです。 + + ニックネームやプロフィール写真といったプロファイル情報は、前のセッションで保存された`profile`からアクセスできます。 + + `web/app/user/user.go`で`/user`エンドポイント用のハンドラーを作成し、対応するHTMLファイルを返します。`profile`が`ctx.HTML()`に渡されているため、同じHTMLファイル内の`picture`や`nickname`といったプロファイル情報にアクセスできます。 + + このようなHTMLファイルは以下の例のように見えることがありますが、カスタムクレームを含め、いかなるプロファイル情報も取得できます。 +
    + +
    + ユーザーをログアウトさせるには、セッションのデータを消去し、ユーザーをAuth0ログアウトエンドポイントにリダイレクトします。詳細は[ログアウトドキュメント](/docs/ja-jp/logout)をご覧ください。 + + `web/app/logout`フォルダーに`logout.go`という名前のファイルを作成し、ユーザーをAuth0ログアウトエンドポイントにリダイレクトするために`Handler`関数を追加します。 + + `returnTo` URLは、アプリケーションの設定セクションで[Allowed Logout URLs(許可されているログアウトURL)]のリストに載っていなければなりません。詳細は「[ログアウト後にユーザーをリダイレクトする](/docs/ja-jp/logout/guides/redirect-users-after-logout)」をご覧ください。 + + `web/static/js`フォルダーに`user.js`という名前のファイルを作成し、ログインしたユーザーからクッキーを削除するためのコードを追加します。 +
    + +
    + 推奨プラクティスでは、認証されたユーザーだけが特定のルートにアクセスできるようにするべきです。認証されていないユーザーが保護されたルートにアクセスしようとした場合、アプリケーションによってリダイレクトされる必要があります。 + + この場合、HTTPの要求に接続するミドルウェアを実装します。ミドルウェアの関数は、要求がエンドポイントハンドラーにルートされるべきか、ブロックされるべきかを決定します。 + + `platform/middleware`に`isAuthenticated.go`という名前のファイルを作成し、`profile`セッションキーに基づいてユーザーが認証されているかいないかをチェックする関数を追加します。認証されていないユーザーは、ミドルウェアがアプリケーションのルートへリダイレクトします。 + + ミドルウェアを作成すると、ルーターに追加することで、認証を必要とするすべてのルートにセットアップできます。 +
    + +
    + 鑑別工具とルーターの構成が完了したら、アプリケーションのエントリーポイントを使って全体を結び付けます。`main.go`内で、鑑別工具とルーターのインスタンスを作成すると鑑別工具インスタンスが渡されます。 + + `.env`ファイルを使用している場合は、`main()`関数の冒頭で`godotenv.Load()`を呼び出さなくてはなりません。 + + ターミナルで次のコマンドを使いアプリケーションを仕上げます: + + ```text lines + go run main.go + ``` +
    + + ## 次のステップ + + 成功です!ここまで来れば、アプリケーションにログイン、ログアウト、ユーザープロファイル情報が備わっているはずです。 + + これでクイックスタートチュートリアルは終了ですが、機能はまだまだたくさんあります。Auth0でできることについて詳しくは、以下をご覧ください。 + + * [Auth0 Dashboard](https://manage.auth0.com/#) - Auth0のテナントやアプリケーションを構成して管理する方法について説明します + * [Auth0 Marketplace](https://marketplace.auth0.com/) - Auth0の機能性を拡張できる各種の統合を見つけられます +
    + + + + + + + + + + + + + + + + +
    + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + + +
    + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + + +
    + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + +
    + + + + + + + +
    + + + + + + + + + + + + + + diff --git a/main/docs/ja-jp/quickstart/webapp/java-ee/interactive.mdx b/main/docs/ja-jp/quickstart/webapp/java-ee/interactive.mdx index 7cf069fd3..0db52c221 100644 --- a/main/docs/ja-jp/quickstart/webapp/java-ee/interactive.mdx +++ b/main/docs/ja-jp/quickstart/webapp/java-ee/interactive.mdx @@ -1,523 +1,525 @@ ---- -title: "Java EEアプリケーションにログインを追加する" -permalink: "interactive" -'description': "このチュートリアルは、Java EE Webアプリケーションにユーザーログインを追加する方法について説明します。" -'og:title': "Java EEアプリケーションにログインを追加する" -'og:description': "このチュートリアルは、Java EE Webアプリケーションにユーザーログインを追加する方法について説明します。" -'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/java.png" -'twitter:title': "Java EEアプリケーションにログインを追加する" -'twitter:description': "このチュートリアルは、Java EE Webアプリケーションにユーザーログインを追加する方法について説明します。" -sidebarTitle: Java EE -mode: wide ---- - -import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; -import { LoggedInForm } from "/snippets/Login.jsx"; -import Web from "/snippets/quickstart/webapp/java-ee/web.xml.mdx"; -import Auth0authenticationconfig from "/snippets/quickstart/webapp/java-ee/Auth0AuthenticationConfig.java.mdx"; -import Loginservlet from "/snippets/quickstart/webapp/java-ee/LoginServlet.java.mdx"; -import Homeservlet from "/snippets/quickstart/webapp/java-ee/HomeServlet.java.mdx"; -import Logoutservlet from "/snippets/quickstart/webapp/java-ee/LogoutServlet.java.mdx"; - -export const sections = [ - { id: "システム要件", title: "システム要件" }, - { id: "auth0を構成する", title: "Auth0を構成する" }, - { id: "javaeeにauth0の使用を構成する", title: "JavaEEにAuth0の使用を構成する" }, - { id: "java-ee-securityを構成する", title: "Java EE Securityを構成する" }, - { id: "認証をトリガーする", title: "認証をトリガーする" }, - { id: "ユーザー情報を表示する", title: "ユーザー情報を表示する" }, - { id: "ログアウトを処理する", title: "ログアウトを処理する" }, - { id: "サンプルを実行する", title: "サンプルを実行する" } -] - - - - このチュートリアルは、Java EE Webアプリケーションにユーザーログインを追加する方法について説明します。ログインして、アカウント用に構成された例を参考にこのクイックタートに従うことをお勧めします。 - -
    - このチュートリアルとサンプルプロジェクトは次を使用してテストが完了しています: - - - Java 11 -
    - -
    - ### アプリケーションキーを取得する - - Auth0にサインアップしたときには、新しいアプリケーションが作成されたか、すでに作成済みであった可能性があります。Auth0と通信するには、アプリケーションについての詳細が必要になります。これらの詳細は、Auth0 - Dashboardの[アプリケーションの設定](https://manage.auth0.com/#/applications)セクションで入手できます。 - - - - - - 以下の情報が必要です。 - - - **Domain (ドメイン)** - - **Client ID(クライアントID)** - - **Client Secret(クライアントシークレット)** - - - このページの上部からサンプルをダウンロードした場合は、これらの詳細が入力されます。 - - - ### Callback URLを構成する - - Callback URLはアプリケーション内にあるURLで、Auth0は認証後にユーザーをここにリダイレクトします。アプリのCallback URLは[アプリケーションの設定](https://manage.auth0.com/#/applications)にある**[Allowed Callback - URLs(許可されているコールバックURL)]**フィールドに追加する必要があります。このフィールドが設定されていない場合、ユーザーはアプリケーションにログインできず、エラーが返されます。 - - - このページの上部からダウンロードしたサンプルプロジェクトに沿って進めている場合には、**[Allowed Callback - URLs(許可されているコールバックURL)]**フィールドに`http://localhost:3000/callback`を追加する必要があります。 - - - ### ログアウトURLを構成する - - ログアウトURLはアプリケーション内にあるURLで、Auth0は認可サーバーからのログアウト後にユーザーをここに戻すことができます。これは、`returnTo`クエリパラメーターで指定されます。アプリのログアウトURLは[アプリケーションの設定](https://manage.auth0.com/#/applications)にある**[Allowed Logout - URLs(許可されているログアウトURL)]**フィールドに追加する必要があります。このフィールドが設定されていない場合、ユーザーはアプリケーションからログアウトできず、エラーが返されます。 - - - このページの上部からダウンロードしたサンプルプロジェクトに沿って進めている場合には、**[Allowed Logout - URLs(許可されているログアウトURL)]**フィールドに`http://localhost:3000/`を追加する必要があります。 - -
    - -
    - ### 依存関係をセットアップする - - Java EEアプリケーションをAuth0と統合するには、以下の依存関係を追加します。 - - - **javax.javaee-api** :Java EE 8を使ってアプリケーションを作成するために必要なJava EE 8 - APIです。実際の統合はアプリケーションコンテナーが提供するため、WARファイルに含める必要はありません。 - - **javax.security.enterprise** :EEアプリケーションでセキュリティ上の懸念に対処できるようにするJava EE 8 Security - APIです。`javax.javaee-api`の依存関係と同様に、統合はアプリケーションコンテナーが提供するため、WARファイルには含まれません。 - - **auth0-java-mvc-commons** :[Auth0 Java MVC SDK](https://github.com/auth0/auth0-java-mvc-common)は、サーバー側のMVC - WebアプリケーションにAuth0とJavaを使用できるようにします。これは、アプリケーションがAuth0を使ったユーザー認証で呼び出すべき認可URLを生成します。 - - Mavenを使用している場合は、次の依存関係を`pom.xml`に追加します: - - ```xml lines - - - com.auth0 - mvc-auth-commons - [1.0, 2.0) - - - javax - javaee-api - 8.0.1 - provided - - - javax.security.enterprise - javax.security.enterprise-api - 1.0 - provided - - ``` - - Gradleを使用している場合は、次を`build.gradle`に追加します: - - ```java lines - // build.gradle - providedCompile 'javax:javaee-api:8.0.1' - providedCompile 'javax.security.enterprise:javax.security.enterprise-api:1.0' - implementation 'com.auth0:mvc-auth-commons:1. ' - ``` - - ### Java EEアプリケーションを構成する - - - このチュートリアルに付属のサンプルはJSPを使用して作成され、[WildFly](https://wildfly.org/)アプリケーションサーバーでテストが完了しています。他のアプリケーションコンテナーや技術を使用して作業する場合には、一部の手順を調整する必要があるかもしれません。 - - - Java - EEアプリケーションは、Auth0アプリケーションを使ってユーザーを認証するために、いくつかの情報を必要とします。この情報の保管にはデプロイメント記述子である`web.xml`ファイルを使用できますが、別の安全な場所に保管することもできます。 - - この情報は、ユーザーがアプリケーションにログインできるように、**auth0-java-mvc-commons** ライブラリーを構成するために使用されます。ライブラリーとその構成オプションについては、ライブラリーの[README](https://github.com/auth0/auth0-java-mvc-common/blob/master/README.md)を参照してください。 -
    - -
    - Java EE 8 Security - APIには新たに`HttpAuthenticationMechanism`インターフェイスが搭載され、アプリケーションがユーザーの資格情報を取得できるようにしています。Basic認証とフォームベースの認証にはデフォルトの実装があり、カスタム認証ストラテジーを構成しやすくしています。 - - Auth0を使用して認証するには、以下のインターフェイスをカスタムで実装します。 - - - HttpAuthenticationMechanism:Auth0から戻されるユーザーの認証ワークフローを処理します([JavaDoc](https://javaee.github.io/javaee-spec/javadocs/javax/security/enterprise/authentication/mechanism/http/HttpAuthenticationMechanism.html))。 - - IdentityStore:ユーザーの資格情報を検証します([JavaDoc](https://javaee.github.io/javaee-spec/javadocs/javax/security/enterprise/identitystore/IdentityStore.html))。 - - CallerPrincipal:現在のHTTP要求の呼び出し元プリンシパルを表します([JavaDoc](https://javaee.github.io/javaee-spec/javadocs/javax/security/enterprise/CallerPrincipal.html))。 - - Credential:呼び出し元が認証に使用する資格情報を表します([JavaDoc](https://javaee.github.io/javaee-spec/javadocs/javax/security/enterprise/credential/Credential.html))。 - - まず、アプリケーションがAuth0設定を使用できるように、@ApplicationScoped Beanを作成してWebコンテキストから値を取得し、getterを通して利用できるようにします。 - - 次に、現在の要求の呼び出し元を表すカスタムの`CallerPrincipal`を作成します: - - ```java lines - // src/main/java/com/auth0/example/security/Auth0JwtPrincipal.java - public class Auth0JwtPrincipal extends CallerPrincipal { - private final DecodedJWT idToken; - - - - Auth0JwtPrincipal(DecodedJWT idToken) { - - super(idToken.getClaim("name").asString()); - - this.idToken = idToken; - - } - - - - public DecodedJWT getIdToken() { - - return this.idToken; - - } - - } - ``` - - これで、ユーザーの資格情報を表すために使用されるカスタムの`Credential`が実装できるようになりました。これには、プリンシパルについての情報が保管されます: - - ```java lines - // src/main/java/com/auth0/example/security/Auth0JwtCredential.java - class Auth0JwtCredential implements Credential { - private Auth0JwtPrincipal auth0JwtPrincipal; - - - - Auth0JwtCredential(String token) { - - DecodedJWT decodedJWT = JWT.decode(token); - - this.auth0JwtPrincipal = new Auth0JwtPrincipal(decodedJWT); - - } - - - - Auth0JwtPrincipal getAuth0JwtPrincipal() { - - return auth0JwtPrincipal; - - } - - } - ``` - - これで、呼び出し元プリンシパルと資格情報を表すクラスが定義できました。次に、`IdentityStore`のカスタム実装を作成します。このクラスはユーザー資格情報の検証に使用されます。 - - ```java lines - // src/main/java/com/auth0/example/security/Auth0JwtIdentityStore.java - @ApplicationScoped - public class Auth0JwtIdentityStore implements IdentityStore { - @Override - - public CredentialValidationResult validate(final Credential credential) { - - CredentialValidationResult result = CredentialValidationResult.NOT_VALIDATED_RESULT; - - if (credential instanceof Auth0JwtCredential) { - - Auth0JwtCredential auth0JwtCredential = (Auth0JwtCredential) credential; - - result = new CredentialValidationResult(auth0JwtCredential.getAuth0JwtPrincipal()); - - } - - return result; - - } - - } - ``` - - `credential`が`Auth0Credential`の場合はユーザーの呼び出しが認証され有効であるため、正常として、資格情報を使って作成された`CredentialValidationResult`が返されます。`Auth0Credential`でない場合には、`CredentialValidationResult.NOT_VALIDATED_RESULT`が返されます。 - - これらのすべてを使用する`HttpAuthenticationMechanism`インターフェイスを実装する前に、Beanを作成して、Auth0 Java MVC - SDKにある構成済みの`AuthenticationController`インスタンスが提供されるようにします。`AuthenticationController`はユーザーがログインする認可URLの構築と、ユーザーを認証するトークン交換の処理に使用されます。 - - - Auth0アプリケーションに**RS256署名アルゴリズム** (新しいAuth0アプリケーション作成時のデフォルト)の使用が構成されている場合には、`JwkProvider`を構成して、トークン署名の検証に使われる公開鍵を取得するようにします。その他の構成オプションについては、[jwks-rsa-javaレポジトリ](https://github.com/auth0/jwks-rsa-java)を参照してください。 - - Auth0アプリケーションに**HS256署名アルゴリズム** の使用が構成されている場合には、`JwkProvider`を構成する必要はありません。 - - - 使用可能な署名アルゴリズムについては、[こちらのドキュメント](/docs/ja-jp/tokens/concepts/signing-algorithms)を参照してください。 - - - 以下のサンプルは、**RS256署名アルゴリズム** の使用に`AuthenticationController`をどのように構成するのかを示しています。 - - ```java lines - // src/main/java/com/auth0/example/security/Auth0AuthenticationProvider.java - @ApplicationScoped - public class Auth0AuthenticationProvider { - @Produces - - public AuthenticationController authenticationController(Auth0AuthenticationConfig config) { - - JwkProvider jwkProvider = new JwkProviderBuilder(config.getDomain()).build(); - - return AuthenticationController.newBuilder(config.getDomain(), config.getClientId(), config.getClientSecret()) - - .withJwkProvider(jwkProvider) - - .build(); - - } - - } - ``` - - 最後に、カスタムの`HttpAuthenticationMechanism`を実装します。 - - ```java lines expandable - // src/main/java/com/auth0/example/security/Auth0AuthenticationMechanism.java - @ApplicationScoped - @AutoApplySession - public class Auth0AuthenticationMechanism implements HttpAuthenticationMechanism { - private final AuthenticationController authenticationController; - - private final IdentityStoreHandler identityStoreHandler; - - - - @Inject - - Auth0AuthenticationMechanism(AuthenticationController authenticationController, IdentityStoreHandler identityStoreHandler) { - - this.authenticationController = authenticationController; - - this.identityStoreHandler = identityStoreHandler; - - } - - - - @Override - - public AuthenticationStatus validateRequest(HttpServletRequest httpServletRequest, - - HttpServletResponse httpServletResponse, - - HttpMessageContext httpMessageContext) throws AuthenticationException { - - - - // Exchange the code for the ID token, and notify container of result. - - if (isCallbackRequest(httpServletRequest)) { - - try { - - Tokens tokens = authenticationController.handle(httpServletRequest, httpServletResponse); - - Auth0JwtCredential auth0JwtCredential = new Auth0JwtCredential(tokens.getIdToken()); - - CredentialValidationResult result = identityStoreHandler.validate(auth0JwtCredential); - - return httpMessageContext.notifyContainerAboutLogin(result); - - } catch (IdentityVerificationException e) { - - return httpMessageContext.responseUnauthorized(); - - } - - } - - return httpMessageContext.doNothing(); - - } - - - - private boolean isCallbackRequest(HttpServletRequest request) { - - return request.getRequestURI().equals("/callback") && request.getParameter("code") != null; - - } - - } - ``` - - このクラスは`validateRequest`メソッドをオーバーライドします。このメソッドはAuth0アプリケーションに対するすべての要求で呼び出され、コンテナーに認証ステータスを通知します。 - - このサンプルでは、[認可コードフロー](/docs/ja-jp/flows/concepts/auth-code)を使用して、認証フロー中に認可コードをトークンと交換します。この要求が`/callback`エンドポイントに対するもので、`code`要求パラメーターが含まれている場合には、以下にあるいくつかの重要な処理を行います。 - - - `AuthenticationController`の`handle`メソッドを呼び出して、認可コードをIDトークンおよびアクセストークンと交換する。 - - IDトークンを使用して、新たに`Auth0Credential`を作成する。 - - カスタムの`IdentityStore`実装の`validate`メソッドを呼び出して、検証結果を取得する。 - - アプリケーションコンテナーにログインステータスを通知する。 - - 要求されたリソースが`/callback`でない場合には、`httpMessageContext.doNothing()`を返して、要求の処理が続行できるようにします。後ほど、認証のトリガーやWebビューの表示で認証情報をどのように使用するかについて説明します。 - - 最後に、認証したユーザーのセッションをコンテナーが作成できるように、`@AutoApplySession`アノテーションが追加されたことに注意してください。 -
    - -
    - ユーザーがログインできるようにするには、`/login`パスへの要求を処理するサーブレットを作成します。 - - `LoginController`は、ユーザーがAuth0で認証できるように、正しい認可URLに要求をリダイレクトします。正しい認可URLの構築には、`Auth0AuthenticationConfig`を通して投入された構成値と、Auth0 - Java MVC - SDKが提供する`AuthenticationController`が使用されます。このサンプルはデフォルトで`openid profile email`スコープを要求して、アプリケーションが基本的なプロファイル情報を認証済みのユーザーから取得できるようにします。これらのスコープについては、[OpenID Connectスコープ](/docs/ja-jp/scopes/current/oidc-scopes)のドキュメントをお読みください。 - - ユーザーが資格情報を入力し、要求されたアクセス権を認可すると、Auth0は`callbackUrl`に対して要求を発行し、IDトークンおよびアクセストークンと交換できる`code`クエリパラメーターを含めます。先ほど説明したように、上記で作成した`Auth0HttpAuthenticationMechanism`がこの交換を処理し、アプリケーションコンテナーに認証ステータスを通知できるようにします。そうすることで、`/callback`パスへの要求を処理するサーブレットは、ログイン前に要求された元のリソースに要求を転送するか、ホームページにリダイレクトするだけで済みます。 - - ```java lines - // src/main/com/auth0/example/web/CallbackServlet.java - @WebServlet(urlPatterns = {"/callback"}) - public class CallbackServlet extends HttpServlet { - @Override - - public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { - - String referer = (String) request.getSession().getAttribute("Referer"); - - String redirectTo = referer != null ? referer : "/"; - - - - response.sendRedirect(redirectTo); - - } - - } - ``` -
    - -
    - 認証したユーザーのプロファイル情報を取得するには、`Auth0JwtPrincipal`を使用することができます。`HomeServlet.java`のサンプルコードでは、[IDトークン](/docs/ja-jp/tokens/id-token)でクレームを使ってプロファイルデータを要求属性に設定する方法を例示しています。 - - そのプロファイル情報は、ユーザーについての情報を表示するビューで使用できます。 - - ```xml lines - - - -
  • -
    - - -
  • -
    - -
  • - - - Profile picture - -
    - -
    "{profile.get('name').asString()}"
    - Profile - Log out -
    -
  • -
    -
    - ``` -
    - -
    - ユーザーをログアウトさせるには、アプリケーションセッションを消去して、Auth0からユーザーをログアウトさせる必要があります。これは`LogoutServlet`で処理されます。 - - まず、`request.getSession().invalidate()`を呼び出して、セッションを消去します。それから、ログアウトURLを構築して、必ず`returnTo`クエリパラメーターを含めます。ユーザーはログアウト後にこのURLにリダイレクトされます。最後に、アプリケーションのをログアウトURLに応答をリダイレクトします。 -
    - -
    - サンプルを構築し実行するには、Mavenゴールに対してwildfly:runを実行し、このアプリケーションをデプロイした組み込みのWildFlyアプリケーションサーバーを起動します。詳細については、[WildFly - Maven Plugin](https://docs.jboss.org/wildfly/plugins/maven/latest/)のドキュメントを参照してください。 - - LinuxまたはMacOSを使用している場合は、次を行います: - - ```sh lines - ./mvnw clean wildfly:run - ``` - - Windows: - - ```sh lines - mvnw.cmd clean wildfly:run - ``` - - 使用しているブラウザーで`http:``//localhost:3000`をポイントします。**ログイン** リンクを使用して、Auth0テナントにログインまたはサインアップします。 - - ログインに成功すると、ユーザーのプロフィール画像とログインリンクのあるドロップダウンメニューが表示されます。**プロファイル** リンクをクリックすると、ユーザーのプロファイルページを表示することができます。ドロップダウンメニューにある**ログアウト** リンクをクリックすると、ログアウトできます。 -
    - - ## 次のステップ - - 成功です!ここまで来れば、アプリケーションにログイン、ログアウト、ユーザープロファイル情報が備わっているはずです。 - - これでクイックスタートチュートリアルは終了ですが、機能はまだまだたくさんあります。Auth0でできることについて詳しくは、以下をご覧ください。 - - * [Auth0 Dashboard](https://manage.auth0.com/#) - Auth0のテナントやアプリケーションを構成して管理する方法について説明します - * [auth0-java-mvc-common SDK](https://github.com/auth0/auth0-java-mvc-common) - このチュートリアルで使用されているSDKをより詳しく説明します - * [Auth0 Marketplace](https://marketplace.auth0.com/) - Auth0の機能性を拡張できる各種の統合を見つけられます -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    +--- +title: "Java EEアプリケーションにログインを追加する" +permalink: "interactive" +'description': "このチュートリアルは、Java EE Webアプリケーションにユーザーログインを追加する方法について説明します。" +'og:title': "Java EEアプリケーションにログインを追加する" +'og:description': "このチュートリアルは、Java EE Webアプリケーションにユーザーログインを追加する方法について説明します。" +'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/java.png" +'twitter:title': "Java EEアプリケーションにログインを追加する" +'twitter:description': "このチュートリアルは、Java EE Webアプリケーションにユーザーログインを追加する方法について説明します。" +sidebarTitle: Java EE +mode: wide +--- + +import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; +import { LoggedInForm } from "/snippets/Login.jsx"; +import Web from "/snippets/quickstart/webapp/java-ee/web.xml.mdx"; +import Auth0authenticationconfig from "/snippets/quickstart/webapp/java-ee/Auth0AuthenticationConfig.java.mdx"; +import Loginservlet from "/snippets/quickstart/webapp/java-ee/LoginServlet.java.mdx"; +import Homeservlet from "/snippets/quickstart/webapp/java-ee/HomeServlet.java.mdx"; +import Logoutservlet from "/snippets/quickstart/webapp/java-ee/LogoutServlet.java.mdx"; + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + +export const sections = [ + { id: "システム要件", title: "システム要件" }, + { id: "auth0を構成する", title: "Auth0を構成する" }, + { id: "javaeeにauth0の使用を構成する", title: "JavaEEにAuth0の使用を構成する" }, + { id: "java-ee-securityを構成する", title: "Java EE Securityを構成する" }, + { id: "認証をトリガーする", title: "認証をトリガーする" }, + { id: "ユーザー情報を表示する", title: "ユーザー情報を表示する" }, + { id: "ログアウトを処理する", title: "ログアウトを処理する" }, + { id: "サンプルを実行する", title: "サンプルを実行する" } +] + + + + このチュートリアルは、Java EE Webアプリケーションにユーザーログインを追加する方法について説明します。ログインして、アカウント用に構成された例を参考にこのクイックタートに従うことをお勧めします。 + +
    + このチュートリアルとサンプルプロジェクトは次を使用してテストが完了しています: + + - Java 11 +
    + +
    + ### アプリケーションキーを取得する + + Auth0にサインアップしたときには、新しいアプリケーションが作成されたか、すでに作成済みであった可能性があります。Auth0と通信するには、アプリケーションについての詳細が必要になります。これらの詳細は、Auth0 + Dashboardの[アプリケーションの設定](https://manage.auth0.com/#/applications)セクションで入手できます。 + + + + + + 以下の情報が必要です。 + + - **Domain (ドメイン)** + - **Client ID(クライアントID)** + - **Client Secret(クライアントシークレット)** + + + このページの上部からサンプルをダウンロードした場合は、これらの詳細が入力されます。 + + + ### Callback URLを構成する + + Callback URLはアプリケーション内にあるURLで、Auth0は認証後にユーザーをここにリダイレクトします。アプリのCallback URLは[アプリケーションの設定](https://manage.auth0.com/#/applications)にある**[Allowed Callback + URLs(許可されているコールバックURL)]**フィールドに追加する必要があります。このフィールドが設定されていない場合、ユーザーはアプリケーションにログインできず、エラーが返されます。 + + + このページの上部からダウンロードしたサンプルプロジェクトに沿って進めている場合には、**[Allowed Callback + URLs(許可されているコールバックURL)]**フィールドに`http://localhost:3000/callback`を追加する必要があります。 + + + ### ログアウトURLを構成する + + ログアウトURLはアプリケーション内にあるURLで、Auth0は認可サーバーからのログアウト後にユーザーをここに戻すことができます。これは、`returnTo`クエリパラメーターで指定されます。アプリのログアウトURLは[アプリケーションの設定](https://manage.auth0.com/#/applications)にある**[Allowed Logout + URLs(許可されているログアウトURL)]**フィールドに追加する必要があります。このフィールドが設定されていない場合、ユーザーはアプリケーションからログアウトできず、エラーが返されます。 + + + このページの上部からダウンロードしたサンプルプロジェクトに沿って進めている場合には、**[Allowed Logout + URLs(許可されているログアウトURL)]**フィールドに`http://localhost:3000/`を追加する必要があります。 + +
    + +
    + ### 依存関係をセットアップする + + Java EEアプリケーションをAuth0と統合するには、以下の依存関係を追加します。 + + - **javax.javaee-api** :Java EE 8を使ってアプリケーションを作成するために必要なJava EE 8 + APIです。実際の統合はアプリケーションコンテナーが提供するため、WARファイルに含める必要はありません。 + - **javax.security.enterprise** :EEアプリケーションでセキュリティ上の懸念に対処できるようにするJava EE 8 Security + APIです。`javax.javaee-api`の依存関係と同様に、統合はアプリケーションコンテナーが提供するため、WARファイルには含まれません。 + - **auth0-java-mvc-commons** :[Auth0 Java MVC SDK](https://github.com/auth0/auth0-java-mvc-common)は、サーバー側のMVC + WebアプリケーションにAuth0とJavaを使用できるようにします。これは、アプリケーションがAuth0を使ったユーザー認証で呼び出すべき認可URLを生成します。 + + Mavenを使用している場合は、次の依存関係を`pom.xml`に追加します: + + ```xml lines + + + com.auth0 + mvc-auth-commons + [1.0, 2.0) + + + javax + javaee-api + 8.0.1 + provided + + + javax.security.enterprise + javax.security.enterprise-api + 1.0 + provided + + ``` + + Gradleを使用している場合は、次を`build.gradle`に追加します: + + ```java lines + // build.gradle + providedCompile 'javax:javaee-api:8.0.1' + providedCompile 'javax.security.enterprise:javax.security.enterprise-api:1.0' + implementation 'com.auth0:mvc-auth-commons:1. ' + ``` + + ### Java EEアプリケーションを構成する + + + このチュートリアルに付属のサンプルはJSPを使用して作成され、[WildFly](https://wildfly.org/)アプリケーションサーバーでテストが完了しています。他のアプリケーションコンテナーや技術を使用して作業する場合には、一部の手順を調整する必要があるかもしれません。 + + + Java + EEアプリケーションは、Auth0アプリケーションを使ってユーザーを認証するために、いくつかの情報を必要とします。この情報の保管にはデプロイメント記述子である`web.xml`ファイルを使用できますが、別の安全な場所に保管することもできます。 + + この情報は、ユーザーがアプリケーションにログインできるように、**auth0-java-mvc-commons** ライブラリーを構成するために使用されます。ライブラリーとその構成オプションについては、ライブラリーの[README](https://github.com/auth0/auth0-java-mvc-common/blob/master/README.md)を参照してください。 +
    + +
    + Java EE 8 Security + APIには新たに`HttpAuthenticationMechanism`インターフェイスが搭載され、アプリケーションがユーザーの資格情報を取得できるようにしています。Basic認証とフォームベースの認証にはデフォルトの実装があり、カスタム認証ストラテジーを構成しやすくしています。 + + Auth0を使用して認証するには、以下のインターフェイスをカスタムで実装します。 + + - HttpAuthenticationMechanism:Auth0から戻されるユーザーの認証ワークフローを処理します([JavaDoc](https://javaee.github.io/javaee-spec/javadocs/javax/security/enterprise/authentication/mechanism/http/HttpAuthenticationMechanism.html))。 + - IdentityStore:ユーザーの資格情報を検証します([JavaDoc](https://javaee.github.io/javaee-spec/javadocs/javax/security/enterprise/identitystore/IdentityStore.html))。 + - CallerPrincipal:現在のHTTP要求の呼び出し元プリンシパルを表します([JavaDoc](https://javaee.github.io/javaee-spec/javadocs/javax/security/enterprise/CallerPrincipal.html))。 + - Credential:呼び出し元が認証に使用する資格情報を表します([JavaDoc](https://javaee.github.io/javaee-spec/javadocs/javax/security/enterprise/credential/Credential.html))。 + + まず、アプリケーションがAuth0設定を使用できるように、@ApplicationScoped Beanを作成してWebコンテキストから値を取得し、getterを通して利用できるようにします。 + + 次に、現在の要求の呼び出し元を表すカスタムの`CallerPrincipal`を作成します: + + ```java lines + // src/main/java/com/auth0/example/security/Auth0JwtPrincipal.java + public class Auth0JwtPrincipal extends CallerPrincipal { + private final DecodedJWT idToken; + + + + Auth0JwtPrincipal(DecodedJWT idToken) { + + super(idToken.getClaim("name").asString()); + + this.idToken = idToken; + + } + + + + public DecodedJWT getIdToken() { + + return this.idToken; + + } + + } + ``` + + これで、ユーザーの資格情報を表すために使用されるカスタムの`Credential`が実装できるようになりました。これには、プリンシパルについての情報が保管されます: + + ```java lines + // src/main/java/com/auth0/example/security/Auth0JwtCredential.java + class Auth0JwtCredential implements Credential { + private Auth0JwtPrincipal auth0JwtPrincipal; + + + + Auth0JwtCredential(String token) { + + DecodedJWT decodedJWT = JWT.decode(token); + + this.auth0JwtPrincipal = new Auth0JwtPrincipal(decodedJWT); + + } + + + + Auth0JwtPrincipal getAuth0JwtPrincipal() { + + return auth0JwtPrincipal; + + } + + } + ``` + + これで、呼び出し元プリンシパルと資格情報を表すクラスが定義できました。次に、`IdentityStore`のカスタム実装を作成します。このクラスはユーザー資格情報の検証に使用されます。 + + ```java lines + // src/main/java/com/auth0/example/security/Auth0JwtIdentityStore.java + @ApplicationScoped + public class Auth0JwtIdentityStore implements IdentityStore { + @Override + + public CredentialValidationResult validate(final Credential credential) { + + CredentialValidationResult result = CredentialValidationResult.NOT_VALIDATED_RESULT; + + if (credential instanceof Auth0JwtCredential) { + + Auth0JwtCredential auth0JwtCredential = (Auth0JwtCredential) credential; + + result = new CredentialValidationResult(auth0JwtCredential.getAuth0JwtPrincipal()); + + } + + return result; + + } + + } + ``` + + `credential`が`Auth0Credential`の場合はユーザーの呼び出しが認証され有効であるため、正常として、資格情報を使って作成された`CredentialValidationResult`が返されます。`Auth0Credential`でない場合には、`CredentialValidationResult.NOT_VALIDATED_RESULT`が返されます。 + + これらのすべてを使用する`HttpAuthenticationMechanism`インターフェイスを実装する前に、Beanを作成して、Auth0 Java MVC + SDKにある構成済みの`AuthenticationController`インスタンスが提供されるようにします。`AuthenticationController`はユーザーがログインする認可URLの構築と、ユーザーを認証するトークン交換の処理に使用されます。 + + - Auth0アプリケーションに**RS256署名アルゴリズム** (新しいAuth0アプリケーション作成時のデフォルト)の使用が構成されている場合には、`JwkProvider`を構成して、トークン署名の検証に使われる公開鍵を取得するようにします。その他の構成オプションについては、[jwks-rsa-javaレポジトリ](https://github.com/auth0/jwks-rsa-java)を参照してください。 + - Auth0アプリケーションに**HS256署名アルゴリズム** の使用が構成されている場合には、`JwkProvider`を構成する必要はありません。 + + + 使用可能な署名アルゴリズムについては、[こちらのドキュメント](/docs/ja-jp/tokens/concepts/signing-algorithms)を参照してください。 + + + 以下のサンプルは、**RS256署名アルゴリズム** の使用に`AuthenticationController`をどのように構成するのかを示しています。 + + ```java lines + // src/main/java/com/auth0/example/security/Auth0AuthenticationProvider.java + @ApplicationScoped + public class Auth0AuthenticationProvider { + @Produces + + public AuthenticationController authenticationController(Auth0AuthenticationConfig config) { + + JwkProvider jwkProvider = new JwkProviderBuilder(config.getDomain()).build(); + + return AuthenticationController.newBuilder(config.getDomain(), config.getClientId(), config.getClientSecret()) + + .withJwkProvider(jwkProvider) + + .build(); + + } + + } + ``` + + 最後に、カスタムの`HttpAuthenticationMechanism`を実装します。 + + ```java lines expandable + // src/main/java/com/auth0/example/security/Auth0AuthenticationMechanism.java + @ApplicationScoped + @AutoApplySession + public class Auth0AuthenticationMechanism implements HttpAuthenticationMechanism { + private final AuthenticationController authenticationController; + + private final IdentityStoreHandler identityStoreHandler; + + + + @Inject + + Auth0AuthenticationMechanism(AuthenticationController authenticationController, IdentityStoreHandler identityStoreHandler) { + + this.authenticationController = authenticationController; + + this.identityStoreHandler = identityStoreHandler; + + } + + + + @Override + + public AuthenticationStatus validateRequest(HttpServletRequest httpServletRequest, + + HttpServletResponse httpServletResponse, + + HttpMessageContext httpMessageContext) throws AuthenticationException { + + + + // Exchange the code for the ID token, and notify container of result. + + if (isCallbackRequest(httpServletRequest)) { + + try { + + Tokens tokens = authenticationController.handle(httpServletRequest, httpServletResponse); + + Auth0JwtCredential auth0JwtCredential = new Auth0JwtCredential(tokens.getIdToken()); + + CredentialValidationResult result = identityStoreHandler.validate(auth0JwtCredential); + + return httpMessageContext.notifyContainerAboutLogin(result); + + } catch (IdentityVerificationException e) { + + return httpMessageContext.responseUnauthorized(); + + } + + } + + return httpMessageContext.doNothing(); + + } + + + + private boolean isCallbackRequest(HttpServletRequest request) { + + return request.getRequestURI().equals("/callback") && request.getParameter("code") != null; + + } + + } + ``` + + このクラスは`validateRequest`メソッドをオーバーライドします。このメソッドはAuth0アプリケーションに対するすべての要求で呼び出され、コンテナーに認証ステータスを通知します。 + + このサンプルでは、[認可コードフロー](/docs/ja-jp/flows/concepts/auth-code)を使用して、認証フロー中に認可コードをトークンと交換します。この要求が`/callback`エンドポイントに対するもので、`code`要求パラメーターが含まれている場合には、以下にあるいくつかの重要な処理を行います。 + + - `AuthenticationController`の`handle`メソッドを呼び出して、認可コードをIDトークンおよびアクセストークンと交換する。 + - IDトークンを使用して、新たに`Auth0Credential`を作成する。 + - カスタムの`IdentityStore`実装の`validate`メソッドを呼び出して、検証結果を取得する。 + - アプリケーションコンテナーにログインステータスを通知する。 + + 要求されたリソースが`/callback`でない場合には、`httpMessageContext.doNothing()`を返して、要求の処理が続行できるようにします。後ほど、認証のトリガーやWebビューの表示で認証情報をどのように使用するかについて説明します。 + + 最後に、認証したユーザーのセッションをコンテナーが作成できるように、`@AutoApplySession`アノテーションが追加されたことに注意してください。 +
    + +
    + ユーザーがログインできるようにするには、`/login`パスへの要求を処理するサーブレットを作成します。 + + `LoginController`は、ユーザーがAuth0で認証できるように、正しい認可URLに要求をリダイレクトします。正しい認可URLの構築には、`Auth0AuthenticationConfig`を通して投入された構成値と、Auth0 + Java MVC + SDKが提供する`AuthenticationController`が使用されます。このサンプルはデフォルトで`openid profile email`スコープを要求して、アプリケーションが基本的なプロファイル情報を認証済みのユーザーから取得できるようにします。これらのスコープについては、[OpenID Connectスコープ](/docs/ja-jp/scopes/current/oidc-scopes)のドキュメントをお読みください。 + + ユーザーが資格情報を入力し、要求されたアクセス権を認可すると、Auth0は`callbackUrl`に対して要求を発行し、IDトークンおよびアクセストークンと交換できる`code`クエリパラメーターを含めます。先ほど説明したように、上記で作成した`Auth0HttpAuthenticationMechanism`がこの交換を処理し、アプリケーションコンテナーに認証ステータスを通知できるようにします。そうすることで、`/callback`パスへの要求を処理するサーブレットは、ログイン前に要求された元のリソースに要求を転送するか、ホームページにリダイレクトするだけで済みます。 + + ```java lines + // src/main/com/auth0/example/web/CallbackServlet.java + @WebServlet(urlPatterns = {"/callback"}) + public class CallbackServlet extends HttpServlet { + @Override + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { + + String referer = (String) request.getSession().getAttribute("Referer"); + + String redirectTo = referer != null ? referer : "/"; + + + + response.sendRedirect(redirectTo); + + } + + } + ``` +
    + +
    + 認証したユーザーのプロファイル情報を取得するには、`Auth0JwtPrincipal`を使用することができます。`HomeServlet.java`のサンプルコードでは、[IDトークン](/docs/ja-jp/tokens/id-token)でクレームを使ってプロファイルデータを要求属性に設定する方法を例示しています。 + + そのプロファイル情報は、ユーザーについての情報を表示するビューで使用できます。 + + ```xml lines + + + +
  • +
    + + +
  • +
    + +
  • + + + Profile picture + + +
  • + + + ``` +
    + +
    + ユーザーをログアウトさせるには、アプリケーションセッションを消去して、Auth0からユーザーをログアウトさせる必要があります。これは`LogoutServlet`で処理されます。 + + まず、`request.getSession().invalidate()`を呼び出して、セッションを消去します。それから、ログアウトURLを構築して、必ず`returnTo`クエリパラメーターを含めます。ユーザーはログアウト後にこのURLにリダイレクトされます。最後に、アプリケーションのをログアウトURLに応答をリダイレクトします。 +
    + +
    + サンプルを構築し実行するには、Mavenゴールに対してwildfly:runを実行し、このアプリケーションをデプロイした組み込みのWildFlyアプリケーションサーバーを起動します。詳細については、[WildFly + Maven Plugin](https://docs.jboss.org/wildfly/plugins/maven/latest/)のドキュメントを参照してください。 + + LinuxまたはMacOSを使用している場合は、次を行います: + + ```sh lines + ./mvnw clean wildfly:run + ``` + + Windows: + + ```sh lines + mvnw.cmd clean wildfly:run + ``` + + 使用しているブラウザーで`http:``//localhost:3000`をポイントします。**ログイン** リンクを使用して、Auth0テナントにログインまたはサインアップします。 + + ログインに成功すると、ユーザーのプロフィール画像とログインリンクのあるドロップダウンメニューが表示されます。**プロファイル** リンクをクリックすると、ユーザーのプロファイルページを表示することができます。ドロップダウンメニューにある**ログアウト** リンクをクリックすると、ログアウトできます。 +
    + + ## 次のステップ + + 成功です!ここまで来れば、アプリケーションにログイン、ログアウト、ユーザープロファイル情報が備わっているはずです。 + + これでクイックスタートチュートリアルは終了ですが、機能はまだまだたくさんあります。Auth0でできることについて詳しくは、以下をご覧ください。 + + * [Auth0 Dashboard](https://manage.auth0.com/#) - Auth0のテナントやアプリケーションを構成して管理する方法について説明します + * [auth0-java-mvc-common SDK](https://github.com/auth0/auth0-java-mvc-common) - このチュートリアルで使用されているSDKをより詳しく説明します + * [Auth0 Marketplace](https://marketplace.auth0.com/) - Auth0の機能性を拡張できる各種の統合を見つけられます + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/main/docs/ja-jp/quickstart/webapp/java-spring-boot/interactive.mdx b/main/docs/ja-jp/quickstart/webapp/java-spring-boot/interactive.mdx index dd59bebb0..54ea1713f 100644 --- a/main/docs/ja-jp/quickstart/webapp/java-spring-boot/interactive.mdx +++ b/main/docs/ja-jp/quickstart/webapp/java-spring-boot/interactive.mdx @@ -1,281 +1,283 @@ ---- -title: "Spring Webアプリケーションにログインを追加する" -permalink: "interactive" -'description': "このガイドでは、Spring BootアプリケーションにAuth0 Spring Boot SDKを使ってAuth0を統合する方法を説明します。" -'og:title': "Spring Webアプリケーションにログインを追加する" -'og:description': "このガイドでは、Spring BootアプリケーションにAuth0 Spring Boot SDKを使ってAuth0を統合する方法を説明します。" -'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/spring.png" -'twitter:title': "Spring Webアプリケーションにログインを追加する" -'twitter:description': "このガイドでは、Spring BootアプリケーションにAuth0 Spring Boot SDKを使ってAuth0を統合する方法を説明します。" -sidebarTitle: Java Spring Boot -mode: wide ---- - -import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; -import { LoggedInForm } from "/snippets/Login.jsx"; -import Application from "/snippets/quickstart/webapp/java-spring-boot/application.yml.mdx"; -import Securityconfig from "/snippets/quickstart/webapp/java-spring-boot/SecurityConfig.java.mdx"; -import Index from "/snippets/quickstart/webapp/java-spring-boot/index.html.mdx"; -import Homecontroller from "/snippets/quickstart/webapp/java-spring-boot/HomeController.java.mdx"; -import Securityconfigwithlogout from "/snippets/quickstart/webapp/java-spring-boot/SecurityConfigWithLogout.java.mdx"; - -export const sections = [ - { id: "auth0を構成する", title: "Auth0を構成する" }, - { id: "sprint-bootアプリケーションを構成する", title: "Sprint Bootアプリケーションを構成する" }, - { id: "spring-securityを構成する", title: "Spring Securityを構成する" }, - { id: "アプリケーションにログインを追加する", title: "アプリケーションにログインを追加する" }, - { id: "表紙ページを追加する", title: "表紙ページを追加する" }, - { id: "コントローラーを追加する", title: "コントローラーを追加する" }, - { id: "アプリケーションにログアウトを追加する", title: "アプリケーションにログアウトを追加する" } -] - - - - - このチュートリアルでは[Spring MVC](https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html)を使用します。[Spring WebFlux](https://docs.spring.io/spring/docs/current/spring-framework-reference/web-reactive.html#spring-web-reactive)を使用している場合、認証を追加する手順は似ていますが、実装の詳細は一部異なります。[Spring Boot WebFluxサンプルコード](https://github.com/auth0-samples/auth0-spring-boot-login-samples/tree/master/webflux-login)で、Auth0とSpring Boot - WebFluxアプリケーションの統合方法を確認してください。 - - -
    - Auth0のサービスを利用するには、Auth0 Dashboadでセットアップしたアプリケーションが必要です。Auth0アプリケーションは、開発中のプロジェクトに対してどのように認証が動作して欲しいかを構成する場所です。 - - ### アプリケーションを構成する - - インタラクティブセレクターを使ってAuth0アプリケーションを新規作成するか、統合したいプロジェクトを表す既存のアプリケーションを選択します。Auth0の全てのアプリケーションには英数字からなる一意のクライアントIDが割り当てられており、アプリケーションのコードがSDKを通じてAuth0 - APIを呼び出す際に使用されます。 - - このクイックスタートを使って構成されたすべての設定は、[Dashboard](https://manage.auth0.com/#/)のアプリケーションに自動更新を行います。今後、アプリケーションの管理はDashboardで行えます。 - - 代わりに完了済みの構成を見てみたい場合は、サンプルアプリケーションをご覧ください。 - - ### Callback URLを構成する - - Callback URLとは、Auth0がユーザーを認証後にリダイレクトするアプリケーション内URLです。設定されていない場合、ユーザーはログイン後にアプリケーションに戻りません。 - - - サンプルプロジェクトに沿って進めている場合には、次の値に設定します: - - `http://localhost:3000/login/oauth2/code/okta` - - - ### ログアウトURLを構成する - - ログアウトURLとは、Auth0がユーザーをログアウト後にリダイレクトするアプリケーション内URLです。設定されていない場合、ユーザーはアプリケーションからログアウトできず、エラーを受け取ります。 - - - サンプルプロジェクトに沿って進めている場合には、次の値に設定します: - - `http://localhost:3000` - -
    - -
    - ### Spring依存関係を追加する - - Spring BootアプリケーションをAuth0と統合するには、[Okta Spring Boot Starter](https://github.com/okta/okta-spring-boot/)をアプリケーションの依存関係に含めます。 - - - このガイドでは、ビューレイヤー用に[Thymeleaf](https://www.thymeleaf.org/)と[Spring Security統合モジュール](https://github.com/thymeleaf/thymeleaf-extras-springsecurity)を使用しています。別の表示技術を使用している場合、Spring - Securityの構成とコンポーネントはそのまま同じです。 - - - Gradleを使用している場合は、以下のようにこれらの依存関係を含めることができます。 - - ```text lines - plugins { - id 'java' - id 'org.springframework.boot' version '3.1.4' - id 'io.spring.dependency-management' version '1.1.3' - } - implementation 'com.okta.spring:okta-spring-boot-starter:3.0.5' - implementation 'org.springframework.boot:spring-boot-starter-web' - implementation 'org.springframework.boot:spring-boot-starter-thymeleaf' - implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity6' - implementation 'nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect' - ``` - - Mavenを使用している場合: - - ```xml lines expandable - - org.springframework.boot - spring-boot-starter-parent - 3.1.4 - - - - - com.okta - okta-spring-boot-starter - 3.0.5 - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-oauth2-client - - - org.springframework.boot - spring-boot-starter-thymeleaf - - - org.thymeleaf.extras - thymeleaf-extras-springsecurity6 - - - nz.net.ultraq.thymeleaf - thymeleaf-layout-dialect - - - ``` -
    - -
    - Okta Spring Boot - Starterでは、Auth0でアプリケーションを簡単に構成できます。以下のサンプルでは`application.yml`ファイルを使用していますが、プロパティファイルや他の[サポートされる表出化メカニズム](https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-external-config)を使用することもできます。 - - ```yml lines - #src/main/resources/application.yml - okta: - oauth2: - issuer: https://dev-gja8kxz4ndtex3rq.us.auth0.com/ - - client-id: mz9iNEIo2PHu7oeh8QRt19ndTyyCIgai - - client-secret: yLTW7npKO4g1HHsCENiZbOaHHXLmhVefJxdNnXcyhOBOomZ2tgjJjSC2pMK7Swvr - - #The sample and instructions above for the callback and logout URL configuration use port 3000. - #If you wish to use a different port, change this and be sure your callback and logout URLs are - #configured with the correct port. - server: - port: 3000 - ``` -
    - -
    - Auth0でユーザーログインを有効にするには、[SecurityFilterChain](https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/web/SecurityFilterChain.html)を登録するクラスを作成し、`@Configuration`の注釈を追加します。 - - - すべてまたは特定のパスで認証を必須にするために、[HttpSecurity](https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/config/annotation/web/builders/HttpSecurity.html)インスタンスを構成することができます。たとえば、ホームページを除くすべてのパスで認証を必須にするには、以下のようにします: - - - ```java lines - http.authorizeHttpRequests(authorize -> authorize - .requestMatchers("/").permitAll() - - .anyRequest().authenticated() - - ); - ``` -
    - -
    - Okta Spring Boot - Starterは以前に定義したクライアント構成を使って、ユーザーがアプリケーションの`/oauth2/authorization/okta`パスにアクセスしたときのログインを処理します。これを使用して、アプリケーションでログインリンクを作成することができます。 - - このページは、ユーザー認証時にユーザー属性を返します。テンプレートの`/logout`リンクを使用して、ログアウト機能を実装します。 -
    - -
    - 受信要求を処理するようにコントロールを作成します。このコントローラは`index.html`ページをレンダリングします。ユーザー認証時に、アプリケーションはユーザーのプロファイル情報の属性を取得し、ページをレンダリングします。 - - - ##### チェックポイント - - ログインリンクをクリックすると、アプリケーションによって[Auth0ユニバーサルログイン](https://auth0.com/universal-login)ページにリダイレクトされ、ユーザー名とパスワードまたはソーシャルプロバイダーを使ってログインまたはサインアップできるようになったことを確認します。 - - - - Auth0は、Googleソーシャルプロバイダーを新しいテナントでデフォルトで有効にし、[ソーシャルIDプロバイダー](/docs/ja-jp/connections/identity-providers-social)でログインテストを実施するための開発者キーを提供します。ただし、これらの開発者キーにはいくつかの制限が設けられており、これによってアプリケーションが異なる動作をする場合があります。この動作の様子と修正方法については、「[Auth0開発者キーを使ってソーシャル接続をテストする](/docs/ja-jp/connections/social/devkeys#limitations-of-developer-keys)」ドキュメントを参照してください。 - -
    - -
    - アプリケーションにログインできるようになったら、[ログアウトする方法](/docs/ja-jp/logout/guides/logout-auth0)が必要です。デフォルトで、ログアウトが有効になると、Spring - Securityはユーザーをアプリケーションからログアウトし、セッションを消去します。Auth0から正常にログアウトするには、`LogoutHandler`でユーザーを[Auth0ログアウトエンドポイント](https://auth0.com/docs/api/authentication?javascript#logout)(`https://{yourDomain}/v2/logout`)にリダイレクトした直後に、アプリケーションにリダイレクトします。 - - `SecurityConfig`クラスで`LogoutHandler`を指定すると、Auth0ログアウトエンドポイントにリダイレクトされ、ログアウトハンドラを追加するように`HttpSecurity`を構成します。 - - - ##### チェックポイント - - ログアウトリンクをクリックすると、「Settings(設定)」にある[Allowed Logout - URLs(許可されているログアウトURL)]のいずれかに指定されたアドレスにリダイレクトされ、アプリケーションにログインされなくなります。 - -
    - - ## 次のステップ - - 成功です!ここまで来れば、アプリケーションにログイン、ログアウト、ユーザープロファイル情報が備わっているはずです。 - - これでクイックスタートチュートリアルは終了ですが、機能はまだまだたくさんあります。Auth0でできることについて詳しくは、以下をご覧ください。 - - * [Auth0 Dashboard](https://manage.auth0.com/#) - Auth0のテナントやアプリケーションを構成して管理する方法について説明します - * [Okta Spring Boot Starter SDK](https://github.com/okta/okta-spring-boot/) - このチュートリアルで使用されているSDKをより詳しく説明します - * [Auth0 Marketplace](https://marketplace.auth0.com/) - Auth0の機能性を拡張できる各種の統合を見つけられます -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    +--- +title: "Spring Webアプリケーションにログインを追加する" +permalink: "interactive" +'description': "このガイドでは、Spring BootアプリケーションにAuth0 Spring Boot SDKを使ってAuth0を統合する方法を説明します。" +'og:title': "Spring Webアプリケーションにログインを追加する" +'og:description': "このガイドでは、Spring BootアプリケーションにAuth0 Spring Boot SDKを使ってAuth0を統合する方法を説明します。" +'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/spring.png" +'twitter:title': "Spring Webアプリケーションにログインを追加する" +'twitter:description': "このガイドでは、Spring BootアプリケーションにAuth0 Spring Boot SDKを使ってAuth0を統合する方法を説明します。" +sidebarTitle: Java Spring Boot +mode: wide +--- + +import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; +import { LoggedInForm } from "/snippets/Login.jsx"; +import Application from "/snippets/quickstart/webapp/java-spring-boot/application.yml.mdx"; +import Securityconfig from "/snippets/quickstart/webapp/java-spring-boot/SecurityConfig.java.mdx"; +import Index from "/snippets/quickstart/webapp/java-spring-boot/index.html.mdx"; +import Homecontroller from "/snippets/quickstart/webapp/java-spring-boot/HomeController.java.mdx"; +import Securityconfigwithlogout from "/snippets/quickstart/webapp/java-spring-boot/SecurityConfigWithLogout.java.mdx"; + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + +export const sections = [ + { id: "auth0を構成する", title: "Auth0を構成する" }, + { id: "sprint-bootアプリケーションを構成する", title: "Sprint Bootアプリケーションを構成する" }, + { id: "spring-securityを構成する", title: "Spring Securityを構成する" }, + { id: "アプリケーションにログインを追加する", title: "アプリケーションにログインを追加する" }, + { id: "表紙ページを追加する", title: "表紙ページを追加する" }, + { id: "コントローラーを追加する", title: "コントローラーを追加する" }, + { id: "アプリケーションにログアウトを追加する", title: "アプリケーションにログアウトを追加する" } +] + + + + + このチュートリアルでは[Spring MVC](https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html)を使用します。[Spring WebFlux](https://docs.spring.io/spring/docs/current/spring-framework-reference/web-reactive.html#spring-web-reactive)を使用している場合、認証を追加する手順は似ていますが、実装の詳細は一部異なります。[Spring Boot WebFluxサンプルコード](https://github.com/auth0-samples/auth0-spring-boot-login-samples/tree/master/webflux-login)で、Auth0とSpring Boot + WebFluxアプリケーションの統合方法を確認してください。 + + +
    + Auth0のサービスを利用するには、Auth0 Dashboadでセットアップしたアプリケーションが必要です。Auth0アプリケーションは、開発中のプロジェクトに対してどのように認証が動作して欲しいかを構成する場所です。 + + ### アプリケーションを構成する + + インタラクティブセレクターを使ってAuth0アプリケーションを新規作成するか、統合したいプロジェクトを表す既存のアプリケーションを選択します。Auth0の全てのアプリケーションには英数字からなる一意のクライアントIDが割り当てられており、アプリケーションのコードがSDKを通じてAuth0 + APIを呼び出す際に使用されます。 + + このクイックスタートを使って構成されたすべての設定は、[Dashboard](https://manage.auth0.com/#/)のアプリケーションに自動更新を行います。今後、アプリケーションの管理はDashboardで行えます。 + + 代わりに完了済みの構成を見てみたい場合は、サンプルアプリケーションをご覧ください。 + + ### Callback URLを構成する + + Callback URLとは、Auth0がユーザーを認証後にリダイレクトするアプリケーション内URLです。設定されていない場合、ユーザーはログイン後にアプリケーションに戻りません。 + + + サンプルプロジェクトに沿って進めている場合には、次の値に設定します: + + `http://localhost:3000/login/oauth2/code/okta` + + + ### ログアウトURLを構成する + + ログアウトURLとは、Auth0がユーザーをログアウト後にリダイレクトするアプリケーション内URLです。設定されていない場合、ユーザーはアプリケーションからログアウトできず、エラーを受け取ります。 + + + サンプルプロジェクトに沿って進めている場合には、次の値に設定します: + + `http://localhost:3000` + +
    + +
    + ### Spring依存関係を追加する + + Spring BootアプリケーションをAuth0と統合するには、[Okta Spring Boot Starter](https://github.com/okta/okta-spring-boot/)をアプリケーションの依存関係に含めます。 + + + このガイドでは、ビューレイヤー用に[Thymeleaf](https://www.thymeleaf.org/)と[Spring Security統合モジュール](https://github.com/thymeleaf/thymeleaf-extras-springsecurity)を使用しています。別の表示技術を使用している場合、Spring + Securityの構成とコンポーネントはそのまま同じです。 + + + Gradleを使用している場合は、以下のようにこれらの依存関係を含めることができます。 + + ```text lines + plugins { + id 'java' + id 'org.springframework.boot' version '3.1.4' + id 'io.spring.dependency-management' version '1.1.3' + } + implementation 'com.okta.spring:okta-spring-boot-starter:3.0.5' + implementation 'org.springframework.boot:spring-boot-starter-web' + implementation 'org.springframework.boot:spring-boot-starter-thymeleaf' + implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity6' + implementation 'nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect' + ``` + + Mavenを使用している場合: + + ```xml lines expandable + + org.springframework.boot + spring-boot-starter-parent + 3.1.4 + + + + + com.okta + okta-spring-boot-starter + 3.0.5 + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-oauth2-client + + + org.springframework.boot + spring-boot-starter-thymeleaf + + + org.thymeleaf.extras + thymeleaf-extras-springsecurity6 + + + nz.net.ultraq.thymeleaf + thymeleaf-layout-dialect + + + ``` +
    + +
    + Okta Spring Boot + Starterでは、Auth0でアプリケーションを簡単に構成できます。以下のサンプルでは`application.yml`ファイルを使用していますが、プロパティファイルや他の[サポートされる表出化メカニズム](https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-external-config)を使用することもできます。 + + ```yml lines + #src/main/resources/application.yml + okta: + oauth2: + issuer: https://dev-gja8kxz4ndtex3rq.us.auth0.com/ + + client-id: mz9iNEIo2PHu7oeh8QRt19ndTyyCIgai + + client-secret: yLTW7npKO4g1HHsCENiZbOaHHXLmhVefJxdNnXcyhOBOomZ2tgjJjSC2pMK7Swvr + + #The sample and instructions above for the callback and logout URL configuration use port 3000. + #If you wish to use a different port, change this and be sure your callback and logout URLs are + #configured with the correct port. + server: + port: 3000 + ``` +
    + +
    + Auth0でユーザーログインを有効にするには、[SecurityFilterChain](https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/web/SecurityFilterChain.html)を登録するクラスを作成し、`@Configuration`の注釈を追加します。 + + + すべてまたは特定のパスで認証を必須にするために、[HttpSecurity](https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/config/annotation/web/builders/HttpSecurity.html)インスタンスを構成することができます。たとえば、ホームページを除くすべてのパスで認証を必須にするには、以下のようにします: + + + ```java lines + http.authorizeHttpRequests(authorize -> authorize + .requestMatchers("/").permitAll() + + .anyRequest().authenticated() + + ); + ``` +
    + +
    + Okta Spring Boot + Starterは以前に定義したクライアント構成を使って、ユーザーがアプリケーションの`/oauth2/authorization/okta`パスにアクセスしたときのログインを処理します。これを使用して、アプリケーションでログインリンクを作成することができます。 + + このページは、ユーザー認証時にユーザー属性を返します。テンプレートの`/logout`リンクを使用して、ログアウト機能を実装します。 +
    + +
    + 受信要求を処理するようにコントロールを作成します。このコントローラは`index.html`ページをレンダリングします。ユーザー認証時に、アプリケーションはユーザーのプロファイル情報の属性を取得し、ページをレンダリングします。 + + + ##### チェックポイント + + ログインリンクをクリックすると、アプリケーションによって[Auth0ユニバーサルログイン](https://auth0.com/universal-login)ページにリダイレクトされ、ユーザー名とパスワードまたはソーシャルプロバイダーを使ってログインまたはサインアップできるようになったことを確認します。 + + + + Auth0は、Googleソーシャルプロバイダーを新しいテナントでデフォルトで有効にし、[ソーシャルIDプロバイダー](/docs/ja-jp/connections/identity-providers-social)でログインテストを実施するための開発者キーを提供します。ただし、これらの開発者キーにはいくつかの制限が設けられており、これによってアプリケーションが異なる動作をする場合があります。この動作の様子と修正方法については、「[Auth0開発者キーを使ってソーシャル接続をテストする](/docs/ja-jp/connections/social/devkeys#limitations-of-developer-keys)」ドキュメントを参照してください。 + +
    + +
    + アプリケーションにログインできるようになったら、[ログアウトする方法](/docs/ja-jp/logout/guides/logout-auth0)が必要です。デフォルトで、ログアウトが有効になると、Spring + Securityはユーザーをアプリケーションからログアウトし、セッションを消去します。Auth0から正常にログアウトするには、`LogoutHandler`でユーザーを[Auth0ログアウトエンドポイント](https://auth0.com/docs/api/authentication?javascript#logout)(`https://{yourDomain}/v2/logout`)にリダイレクトした直後に、アプリケーションにリダイレクトします。 + + `SecurityConfig`クラスで`LogoutHandler`を指定すると、Auth0ログアウトエンドポイントにリダイレクトされ、ログアウトハンドラを追加するように`HttpSecurity`を構成します。 + + + ##### チェックポイント + + ログアウトリンクをクリックすると、「Settings(設定)」にある[Allowed Logout + URLs(許可されているログアウトURL)]のいずれかに指定されたアドレスにリダイレクトされ、アプリケーションにログインされなくなります。 + +
    + + ## 次のステップ + + 成功です!ここまで来れば、アプリケーションにログイン、ログアウト、ユーザープロファイル情報が備わっているはずです。 + + これでクイックスタートチュートリアルは終了ですが、機能はまだまだたくさんあります。Auth0でできることについて詳しくは、以下をご覧ください。 + + * [Auth0 Dashboard](https://manage.auth0.com/#) - Auth0のテナントやアプリケーションを構成して管理する方法について説明します + * [Okta Spring Boot Starter SDK](https://github.com/okta/okta-spring-boot/) - このチュートリアルで使用されているSDKをより詳しく説明します + * [Auth0 Marketplace](https://marketplace.auth0.com/) - Auth0の機能性を拡張できる各種の統合を見つけられます +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    diff --git a/main/docs/ja-jp/quickstart/webapp/java/interactive.mdx b/main/docs/ja-jp/quickstart/webapp/java/interactive.mdx index 3834e9f1c..ac902b3cc 100644 --- a/main/docs/ja-jp/quickstart/webapp/java/interactive.mdx +++ b/main/docs/ja-jp/quickstart/webapp/java/interactive.mdx @@ -1,305 +1,307 @@ ---- -title: "Java Servletアプリケーションにログインを追加する" -permalink: "interactive" -'description': "このガイドは、新規または既存のJava ServletアプリケーションにAuth0を統合する方法を説明します。" -'og:title': "Java Servletアプリケーションにログインを追加する" -'og:description': "このガイドは、新規または既存のJava ServletアプリケーションにAuth0を統合する方法を説明します。" -'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/java.png" -'twitter:title': "Java Servletアプリケーションにログインを追加する" -'twitter:description': "このガイドは、新規または既存のJava ServletアプリケーションにAuth0を統合する方法を説明します。" -sidebarTitle: Java -mode: wide ---- - - -import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; -import { LoggedInForm } from "/snippets/Login.jsx"; -import Web from "/snippets/quickstart/webapp/java/web.xml.mdx"; -import Authenticationcontrollerprovider from "/snippets/quickstart/webapp/java/AuthenticationControllerProvider.java.mdx"; -import Loginservlet from "/snippets/quickstart/webapp/java/LoginServlet.java.mdx"; -import Callbackservlet from "/snippets/quickstart/webapp/java/CallbackServlet.java.mdx"; -import Homeservlet from "/snippets/quickstart/webapp/java/HomeServlet.java.mdx"; -import Logoutservlet from "/snippets/quickstart/webapp/java/LogoutServlet.java.mdx"; - -export const sections = [ - { id: "auth0を構成する", title: "Auth0を構成する" }, - { id: "auth0をアプリケーションに統合する", title: "Auth0をアプリケーションに統合する" }, - { id: "javaアプリケーションを構成する", title: "Javaアプリケーションを構成する" }, - { id: "authenticationcontrollerを作成する", title: "AuthenticationControllerを作成する" }, - { id: "ログインにリダイレクトする", title: "ログインにリダイレクトする" }, - { id: "トークンの処理", title: "トークンの処理" }, - { id: "ホームページを表示する", title: "ホームページを表示する" }, - { id: "ログアウトを処理する", title: "ログアウトを処理する" }, - { id: "サンプルを実行する", title: "サンプルを実行する" } -] - - - - Auth0を使用すると、アプリケーションに手軽に認証を追加して、ユーザープロファイル情報にアクセスすることができます。このガイドは、新規または既存のJava ServletアプリケーションにAuth0を統合する方法を説明します。 - -
    - Auth0のサービスを利用するには、Auth0 Dashboadに設定済みのアプリケーションがある必要があります。Auth0アプリケーションは、開発中のプロジェクトに対してどのように認証が動作して欲しいかを構成する場所です。 - - ### アプリケーションを構成する - - 対話型のセレクターを使ってAuth0アプリケーションを新規作成するか、統合したいプロジェクトを表す既存のアプリケーションを選択します。Auth0のすべてのアプリケーションには英数字からなる一意のクライアントIDが割り当てられており、アプリケーションのコードがSDKを通じてAuth0 - APIを呼び出す際に使用されます。 - - このクイックスタートを使って構成されたすべての設定は、[Dashboard](https://manage.auth0.com/#/)のアプリケーションを自動更新します。今後、アプリケーションの管理もDashboardで行えます。 - - 完了済みの構成を見てみたい場合は、サンプルアプリケーションをご覧ください。 - - ### Callback URLを構成する - - Callback URLとは、Auth0がユーザーを認証後にリダイレクトするアプリケーション内URLです。設定されていない場合、ユーザーはログイン後にアプリケーションに戻りません。 - - - サンプルプロジェクトに沿って進めている場合は、`http://localhost:3000``/callback`に設定してください。 - - - ### ログアウトURLを構成する - - ログアウトURLとは、Auth0がユーザーをログアウト後にリダイレクトするアプリケーション内URLです。設定されていない場合、ユーザーはアプリケーションからログアウトできず、エラーを受け取ります。 - - - サンプルプロジェクトに沿って進めている場合は、`http://localhost:3000/logout`に設定してください。 - -
    - -
    - ### 依存関係をセットアップする - - Auth0でJavaアプリケーションを統合するには、以下の依存関係を追加します: - - - **javax.servlet-api** - :Java Servletsの作成を許可するライブラリーです。TomcatやGrettyのようなサーバー依存関係を追加する必要があります。どれを追加するかは自己判断です。詳細はサンプルコードをご覧ください。 - - **auth0-java-mvc-commons** :サーバー側のMVC Webアプリ用にJavaでAuth0の使用を許可する[Javaライブラリー](https://github.com/auth0/auth0-java-mvc-common)です。ユーザーを識別する[Auth0トークン](/docs/ja-jp/tokens)を最後に取得する過程で受け取った結果を認証、検証するために呼び出す必要のある認可URLを生成します。 - - Gradleを使用している場合は、`build.gradle`に追加します: - - ```text lines - // build.gradle - compile 'javax.servlet:javax.servlet-api:3.1.0' - compile 'com.auth0:mvc-auth-commons:1.+'W - ``` - - - Mavenを使用している場合は、`pom.xml`に追加します: - - ```xml lines - - - com.auth0 - mvc-auth-commons - [1.0, 2.0) - - - javax.servlet - javax.servlet-api - 3.1.0 - - ``` - -
    - -
    - Javaアプリは、Auth0アカウントに対して認証するために、いくつかの情報を必要とします。サンプルではこの情報をデプロイメント記述子ファイル(`src/main/webapp/WEB-INF/web.xml`)から読み取っていますが、任意の場所に保存できます。 - - この情報は**auth0-java-mvc-commons** ライブラリーを構成するために使用され、ユーザーがアプリケーションにログインすることを可能にします。ライブラリーや各構成オプションの詳細情報については、[ライブラリーのドキュメント](https://github.com/auth0/auth0-java-mvc-common/blob/master/README.md)をご覧ください。 - - ### 入力された属性をチェックする - - このサンプルを**[Download - Sample(サンプルをダウンロード)]**ボタンでダウンロードした場合は、`domain`、`clientId`、`clientSecret`属性が自動的に入力されます。特にアカウントに複数のAuth0アプリケーションがある場合は、値が正しいことを確認してください。 - - ### プロジェクト構造 - - **[Download Sample(サンプルをダウンロード)]** ボタンでダウンロードできるサンプルプロジェクトは以下の構造になっています: - - ```text lines - - src - -- main - ---- java - ------ com - -------- auth0 - ---------- example - ------------ Auth0Filter.java - ------------ AuthenticationControllerProvider.java - ------------ HomeServlet.java - ------------ CallbackServlet.java - ------------ LoginServlet.java - ------------ LogoutServlet.java - ---- webapp - ------ WEB-INF - -------- jsp - ---------- home.jsp - -------- web.xml - - build.gradle - ``` - - - プロジェクトには単一のJSPがあります:`home.jsp`は、ログイン成功後にユーザーに関連付けられたトークンを表示し、ログアウトオプションを提供します。 - - プロジェクトはWebFilterを含みます:`Auth0Filter.java`は、保護された`/portal/*`パスへのユーザーアクセスを付与する前に、既存のトークンを確認します。トークンが存在しない場合、要求は`LoginServlet`へリダイレクトされます。 - - プロジェクトにはサーブレットも4つあります: - - - `LoginServlet.java`:ユーザーがログインしようとした時に発動します。`client_id`パラメーターと`domain`パラメーターを使って有効な認可URLを作成し、ユーザーをリダイレクトします。 - - `CallbackServlet.java`:Callback - URLへの要求をキャッチし、データを処理して資格情報を取得するサーブレットです。資格情報はログイン成功後、要求のHttpSessionに保存されます。 - - `HomeServlet.java`:以前保存されたトークンを読み取り、`home.jsp`リソースで表示するサーブレットです。 - - `LogoutServlet.java`:ユーザーがログアウトリンクをクリックすると発動します。ユーザーセッションを無効化し、`LoginServlet`でハンドリングされたログインページにユーザーをリダイレクトします。 - - `AuthenticationControllerProvider.java`:`AuthenticationController`の単一インスタンスを作成・管理するためのものです。 -
    - -
    - ユーザー認証を可能にするために、`domain`、`clientId`、`clientSecret`を使って`auth0-java-mvc-commons` - SDKから提供された`AuthenticationController`のインスタンスを作成します。サンプルでは、RS256非対称署名アルゴリズムを使って署名したトークンで使用するためのコンポーネントの構成方法が紹介されています。トークンの署名を検証するために使用された公開鍵を取得する`JwkProvider`が指定されています。その他の構成オプションについての詳細は、[jwks-rsa-javaレポジトリ](https://github.com/auth0/jwks-rsa-java)をご覧ください。HS256を使用している場合は、`JwkProvider`を構成する必要はありません。 - - - `AuthenticationController`はコンテキストを一切保存せず、再使用を意図しています。不必要な作成はリソースの追加作成を招き、パフォーマンスに影響が出る可能性があります。 - -
    - -
    - アプリケーションは、ユーザーがログインできるように、ユニバーサルログインページへリダイレクトします。`AuthenticationController`インスタンスを使うと、`buildAuthorizeUrl(HttpServletRequest request`、`HttpServletResponse response`、`String redirectUrl)`メソッドを呼び出すことでリダイレクトURLを生成できます。リダイレクトURLは、Auth0アプリケーションの**[Allowed - Callback URLs(許可されているコールバックURL)]**に追加されたURLである必要があります。 -
    - -
    - ユーザーがログインした後、結果はGET要求またはPOST HTTP要求経由で`CallbackServlet`で受信されます。(初期設定として)Authorization Code - Flowを使用しているため、GET要求が送信されます。ライブラリーを暗黙フロー用に構成している場合は、代わりにPOST要求が送信されます。 - - 認可URLを`AuthenticationController`で生成することにより、要求はライブラリーで以前設定した呼び出しコンテキストを保持します。コントローラーに渡されると、有効な`Tokens`インスタンスまたは不具合を特定するExceptionが返ってきます。呼び出しに成功した場合、後でアクセスするために資格情報をどこかに保存しておく必要があります。ライブラリーに含まれる`SessionsUtils`クラスを使って、要求の`HttpSession`を使用できます。 - - - トークンを要求した時刻と受け取った`expiresIn`値は保存することを推奨します。そうすることで、次回トークンを使用する時に、すでに有効期限が切れているか、または引き続き有効かを確認できます。このサンプルでは検証をスキップします。 - -
    - -
    - ユーザーは認証される(トークンが存在する)と、`Auth0Filter`によって保護されたリソースへのアクセスを許可されます。`HomeServlet`で要求セッションからトークンが取得され、`userId`属性として設定されることで、JSPコードから使用できるようになります。 -
    - -
    - ログアウトを適切に処理するには、セッションを消去し、ユーザーをAuth0からログアウトさせる必要があります。この処理は、サンプルアプリケーションの`LogoutServlet`で行われます。 - - まず、`request.getSession().invalidate()`を呼び出してセッションを消去します。それから、`returnTo`クエリパラメーターを含めることを念頭に置きつつ、ログアウトURLを構築します。ユーザーはログアウト後にこのURLにリダイレクトされます。最後に応答をログアウトURLにリダイレクトします。 -
    - -
    - ターミナルからサンプルを実行するには、ディレクトリをプロジェクトのルートフォルダーに変更して以下のラインを実行します: - - ```text lines - ./gradlew clean app - ``` - - 数秒後、アプリケーションが`http://localhost:3000/`でアクセスできるようになります。保護されたリソース([http://localhost:3000/portal/home](http://localhost:3000/portal/home))にアクセスしてみて、`Auth0Filter`によるAuth0ログインページへのリダイレクト方法を観察します。ウィジェット - が、[Dashboard](https://manage.auth0.com/#/)でこのアプリケーションに定義したソーシャル接続とデータベース接続をすべて表示します。 - - - - - - 認証成功後、ホームページのコンテンツを見られるようになります。 - - - - - - ホームページ右上の**[logout(ログアウト)]** ボタン をクリックしてログアウトします。 -
    - - ## 次のステップ - - 成功です!ここまで来れば、アプリケーションにログイン、ログアウト、ユーザープロファイル情報が備わっているはずです。 - - これでクイックスタートチュートリアルは終了ですが、機能はまだまだたくさんあります。Auth0でできることについて詳しくは、以下をご覧ください。 - - * [Auth0 Dashboard](https://manage.auth0.com/#) - Auth0のテナントやアプリケーションを構成して管理する方法について説明します - * [auth0-java-mvc-common SDK](https://github.com/auth0/auth0-java-mvc-common) - このチュートリアルで使用されているSDKをより詳しく説明します - * [Auth0 Marketplace](https://marketplace.auth0.com/) - Auth0の機能性を拡張できる各種の統合を見つけられます -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    +--- +title: "Java Servletアプリケーションにログインを追加する" +permalink: "interactive" +'description': "このガイドは、新規または既存のJava ServletアプリケーションにAuth0を統合する方法を説明します。" +'og:title': "Java Servletアプリケーションにログインを追加する" +'og:description': "このガイドは、新規または既存のJava ServletアプリケーションにAuth0を統合する方法を説明します。" +'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/java.png" +'twitter:title': "Java Servletアプリケーションにログインを追加する" +'twitter:description': "このガイドは、新規または既存のJava ServletアプリケーションにAuth0を統合する方法を説明します。" +sidebarTitle: Java +mode: wide +--- + + +import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; +import { LoggedInForm } from "/snippets/Login.jsx"; +import Web from "/snippets/quickstart/webapp/java/web.xml.mdx"; +import Authenticationcontrollerprovider from "/snippets/quickstart/webapp/java/AuthenticationControllerProvider.java.mdx"; +import Loginservlet from "/snippets/quickstart/webapp/java/LoginServlet.java.mdx"; +import Callbackservlet from "/snippets/quickstart/webapp/java/CallbackServlet.java.mdx"; +import Homeservlet from "/snippets/quickstart/webapp/java/HomeServlet.java.mdx"; +import Logoutservlet from "/snippets/quickstart/webapp/java/LogoutServlet.java.mdx"; + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + +export const sections = [ + { id: "auth0を構成する", title: "Auth0を構成する" }, + { id: "auth0をアプリケーションに統合する", title: "Auth0をアプリケーションに統合する" }, + { id: "javaアプリケーションを構成する", title: "Javaアプリケーションを構成する" }, + { id: "authenticationcontrollerを作成する", title: "AuthenticationControllerを作成する" }, + { id: "ログインにリダイレクトする", title: "ログインにリダイレクトする" }, + { id: "トークンの処理", title: "トークンの処理" }, + { id: "ホームページを表示する", title: "ホームページを表示する" }, + { id: "ログアウトを処理する", title: "ログアウトを処理する" }, + { id: "サンプルを実行する", title: "サンプルを実行する" } +] + + + + Auth0を使用すると、アプリケーションに手軽に認証を追加して、ユーザープロファイル情報にアクセスすることができます。このガイドは、新規または既存のJava ServletアプリケーションにAuth0を統合する方法を説明します。 + +
    + Auth0のサービスを利用するには、Auth0 Dashboadに設定済みのアプリケーションがある必要があります。Auth0アプリケーションは、開発中のプロジェクトに対してどのように認証が動作して欲しいかを構成する場所です。 + + ### アプリケーションを構成する + + 対話型のセレクターを使ってAuth0アプリケーションを新規作成するか、統合したいプロジェクトを表す既存のアプリケーションを選択します。Auth0のすべてのアプリケーションには英数字からなる一意のクライアントIDが割り当てられており、アプリケーションのコードがSDKを通じてAuth0 + APIを呼び出す際に使用されます。 + + このクイックスタートを使って構成されたすべての設定は、[Dashboard](https://manage.auth0.com/#/)のアプリケーションを自動更新します。今後、アプリケーションの管理もDashboardで行えます。 + + 完了済みの構成を見てみたい場合は、サンプルアプリケーションをご覧ください。 + + ### Callback URLを構成する + + Callback URLとは、Auth0がユーザーを認証後にリダイレクトするアプリケーション内URLです。設定されていない場合、ユーザーはログイン後にアプリケーションに戻りません。 + + + サンプルプロジェクトに沿って進めている場合は、`http://localhost:3000``/callback`に設定してください。 + + + ### ログアウトURLを構成する + + ログアウトURLとは、Auth0がユーザーをログアウト後にリダイレクトするアプリケーション内URLです。設定されていない場合、ユーザーはアプリケーションからログアウトできず、エラーを受け取ります。 + + + サンプルプロジェクトに沿って進めている場合は、`http://localhost:3000/logout`に設定してください。 + +
    + +
    + ### 依存関係をセットアップする + + Auth0でJavaアプリケーションを統合するには、以下の依存関係を追加します: + + - **javax.servlet-api** + :Java Servletsの作成を許可するライブラリーです。TomcatやGrettyのようなサーバー依存関係を追加する必要があります。どれを追加するかは自己判断です。詳細はサンプルコードをご覧ください。 + - **auth0-java-mvc-commons** :サーバー側のMVC Webアプリ用にJavaでAuth0の使用を許可する[Javaライブラリー](https://github.com/auth0/auth0-java-mvc-common)です。ユーザーを識別する[Auth0トークン](/docs/ja-jp/tokens)を最後に取得する過程で受け取った結果を認証、検証するために呼び出す必要のある認可URLを生成します。 + + Gradleを使用している場合は、`build.gradle`に追加します: + + ```text lines + // build.gradle + compile 'javax.servlet:javax.servlet-api:3.1.0' + compile 'com.auth0:mvc-auth-commons:1.+'W + ``` + + + Mavenを使用している場合は、`pom.xml`に追加します: + + ```xml lines + + + com.auth0 + mvc-auth-commons + [1.0, 2.0) + + + javax.servlet + javax.servlet-api + 3.1.0 + + ``` + +
    + +
    + Javaアプリは、Auth0アカウントに対して認証するために、いくつかの情報を必要とします。サンプルではこの情報をデプロイメント記述子ファイル(`src/main/webapp/WEB-INF/web.xml`)から読み取っていますが、任意の場所に保存できます。 + + この情報は**auth0-java-mvc-commons** ライブラリーを構成するために使用され、ユーザーがアプリケーションにログインすることを可能にします。ライブラリーや各構成オプションの詳細情報については、[ライブラリーのドキュメント](https://github.com/auth0/auth0-java-mvc-common/blob/master/README.md)をご覧ください。 + + ### 入力された属性をチェックする + + このサンプルを**[Download + Sample(サンプルをダウンロード)]**ボタンでダウンロードした場合は、`domain`、`clientId`、`clientSecret`属性が自動的に入力されます。特にアカウントに複数のAuth0アプリケーションがある場合は、値が正しいことを確認してください。 + + ### プロジェクト構造 + + **[Download Sample(サンプルをダウンロード)]** ボタンでダウンロードできるサンプルプロジェクトは以下の構造になっています: + + ```text lines + - src + -- main + ---- java + ------ com + -------- auth0 + ---------- example + ------------ Auth0Filter.java + ------------ AuthenticationControllerProvider.java + ------------ HomeServlet.java + ------------ CallbackServlet.java + ------------ LoginServlet.java + ------------ LogoutServlet.java + ---- webapp + ------ WEB-INF + -------- jsp + ---------- home.jsp + -------- web.xml + + build.gradle + ``` + + + プロジェクトには単一のJSPがあります:`home.jsp`は、ログイン成功後にユーザーに関連付けられたトークンを表示し、ログアウトオプションを提供します。 + + プロジェクトはWebFilterを含みます:`Auth0Filter.java`は、保護された`/portal/*`パスへのユーザーアクセスを付与する前に、既存のトークンを確認します。トークンが存在しない場合、要求は`LoginServlet`へリダイレクトされます。 + + プロジェクトにはサーブレットも4つあります: + + - `LoginServlet.java`:ユーザーがログインしようとした時に発動します。`client_id`パラメーターと`domain`パラメーターを使って有効な認可URLを作成し、ユーザーをリダイレクトします。 + - `CallbackServlet.java`:Callback + URLへの要求をキャッチし、データを処理して資格情報を取得するサーブレットです。資格情報はログイン成功後、要求のHttpSessionに保存されます。 + - `HomeServlet.java`:以前保存されたトークンを読み取り、`home.jsp`リソースで表示するサーブレットです。 + - `LogoutServlet.java`:ユーザーがログアウトリンクをクリックすると発動します。ユーザーセッションを無効化し、`LoginServlet`でハンドリングされたログインページにユーザーをリダイレクトします。 + - `AuthenticationControllerProvider.java`:`AuthenticationController`の単一インスタンスを作成・管理するためのものです。 +
    + +
    + ユーザー認証を可能にするために、`domain`、`clientId`、`clientSecret`を使って`auth0-java-mvc-commons` + SDKから提供された`AuthenticationController`のインスタンスを作成します。サンプルでは、RS256非対称署名アルゴリズムを使って署名したトークンで使用するためのコンポーネントの構成方法が紹介されています。トークンの署名を検証するために使用された公開鍵を取得する`JwkProvider`が指定されています。その他の構成オプションについての詳細は、[jwks-rsa-javaレポジトリ](https://github.com/auth0/jwks-rsa-java)をご覧ください。HS256を使用している場合は、`JwkProvider`を構成する必要はありません。 + + + `AuthenticationController`はコンテキストを一切保存せず、再使用を意図しています。不必要な作成はリソースの追加作成を招き、パフォーマンスに影響が出る可能性があります。 + +
    + +
    + アプリケーションは、ユーザーがログインできるように、ユニバーサルログインページへリダイレクトします。`AuthenticationController`インスタンスを使うと、`buildAuthorizeUrl(HttpServletRequest request`、`HttpServletResponse response`、`String redirectUrl)`メソッドを呼び出すことでリダイレクトURLを生成できます。リダイレクトURLは、Auth0アプリケーションの**[Allowed + Callback URLs(許可されているコールバックURL)]**に追加されたURLである必要があります。 +
    + +
    + ユーザーがログインした後、結果はGET要求またはPOST HTTP要求経由で`CallbackServlet`で受信されます。(初期設定として)Authorization Code + Flowを使用しているため、GET要求が送信されます。ライブラリーを暗黙フロー用に構成している場合は、代わりにPOST要求が送信されます。 + + 認可URLを`AuthenticationController`で生成することにより、要求はライブラリーで以前設定した呼び出しコンテキストを保持します。コントローラーに渡されると、有効な`Tokens`インスタンスまたは不具合を特定するExceptionが返ってきます。呼び出しに成功した場合、後でアクセスするために資格情報をどこかに保存しておく必要があります。ライブラリーに含まれる`SessionsUtils`クラスを使って、要求の`HttpSession`を使用できます。 + + + トークンを要求した時刻と受け取った`expiresIn`値は保存することを推奨します。そうすることで、次回トークンを使用する時に、すでに有効期限が切れているか、または引き続き有効かを確認できます。このサンプルでは検証をスキップします。 + +
    + +
    + ユーザーは認証される(トークンが存在する)と、`Auth0Filter`によって保護されたリソースへのアクセスを許可されます。`HomeServlet`で要求セッションからトークンが取得され、`userId`属性として設定されることで、JSPコードから使用できるようになります。 +
    + +
    + ログアウトを適切に処理するには、セッションを消去し、ユーザーをAuth0からログアウトさせる必要があります。この処理は、サンプルアプリケーションの`LogoutServlet`で行われます。 + + まず、`request.getSession().invalidate()`を呼び出してセッションを消去します。それから、`returnTo`クエリパラメーターを含めることを念頭に置きつつ、ログアウトURLを構築します。ユーザーはログアウト後にこのURLにリダイレクトされます。最後に応答をログアウトURLにリダイレクトします。 +
    + +
    + ターミナルからサンプルを実行するには、ディレクトリをプロジェクトのルートフォルダーに変更して以下のラインを実行します: + + ```text lines + ./gradlew clean app + ``` + + 数秒後、アプリケーションが`http://localhost:3000/`でアクセスできるようになります。保護されたリソース([http://localhost:3000/portal/home](http://localhost:3000/portal/home))にアクセスしてみて、`Auth0Filter`によるAuth0ログインページへのリダイレクト方法を観察します。ウィジェット + が、[Dashboard](https://manage.auth0.com/#/)でこのアプリケーションに定義したソーシャル接続とデータベース接続をすべて表示します。 + + + + + + 認証成功後、ホームページのコンテンツを見られるようになります。 + + + + + + ホームページ右上の**[logout(ログアウト)]** ボタン をクリックしてログアウトします。 +
    + + ## 次のステップ + + 成功です!ここまで来れば、アプリケーションにログイン、ログアウト、ユーザープロファイル情報が備わっているはずです。 + + これでクイックスタートチュートリアルは終了ですが、機能はまだまだたくさんあります。Auth0でできることについて詳しくは、以下をご覧ください。 + + * [Auth0 Dashboard](https://manage.auth0.com/#) - Auth0のテナントやアプリケーションを構成して管理する方法について説明します + * [auth0-java-mvc-common SDK](https://github.com/auth0/auth0-java-mvc-common) - このチュートリアルで使用されているSDKをより詳しく説明します + * [Auth0 Marketplace](https://marketplace.auth0.com/) - Auth0の機能性を拡張できる各種の統合を見つけられます +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    diff --git a/main/docs/ja-jp/quickstart/webapp/nextjs/interactive.mdx b/main/docs/ja-jp/quickstart/webapp/nextjs/interactive.mdx index 3cf6fa928..54750643a 100644 --- a/main/docs/ja-jp/quickstart/webapp/nextjs/interactive.mdx +++ b/main/docs/ja-jp/quickstart/webapp/nextjs/interactive.mdx @@ -1,213 +1,215 @@ ---- -title: "Next.jsアプリケーションにログインを追加する" -permalink: "interactive" -'description': "このガイドは、新規または既存のNext.jsアプリケーションにAuth0 Next.js SDKを使ってAuth0を統合する方法を説明します。" -'og:title': "Next.jsアプリケーションにログインを追加する" -'og:description': "このガイドは、新規または既存のNext.jsアプリケーションにAuth0 Next.js SDKを使ってAuth0を統合する方法を説明します。" -'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/nginx-plus.png" -'twitter:title': "Next.jsアプリケーションにログインを追加する" -'twitter:description': "このガイドは、新規または既存のNext.jsアプリケーションにAuth0 Next.js SDKを使ってAuth0を統合する方法を説明します。" -sidebarTitle: Next.js -mode: wide ---- - -import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; -import { LoggedInForm } from "/snippets/Login.jsx"; -import ConfigureSDK from "/snippets/quickstart/webapp/nextjs/configure-the-sdk.mdx" -import CreateAuth0SDKClient from "/snippets/quickstart/webapp/nextjs/create-the-auth0-sdk-client.mdx" -import CreateLoginPage from "/snippets/quickstart/webapp/nextjs/create-a-login-page.mdx" -import AddLandingPageContent from "/snippets/quickstart/webapp/nextjs/add-the-landing-page-content.mdx" - -export const sections = [ - { id: "auth0を構成する", title: "Auth0を構成する" }, - { id: "auth0-next-js-sdkをインストールする", title: "Auth0 Next.js SDKをインストールする" }, - { id: "sdkを構成する", title: "SDKを構成する" }, - { id: "動的ルートハンドラーを追加する", title: "動的ルートハンドラーを追加する" }, - { id: "userproviderコンポーネントを追加する", title: "UserProviderコンポーネントを追加する" }, - { id: "アプリケーションにログインを追加する", title: "アプリケーションにログインを追加する" }, - { id: "アプリケーションにログアウトを追加する", title: "アプリケーションにログアウトを追加する" } -] - - - - このガイドは、新規または既存のNext.jsアプリケーションにAuth0 Next.js SDKを使ってAuth0を統合する方法を説明します。アカウント用に構成された例を参考にして、このクイックスタートに従うことをお勧めします。 - -
    - Auth0のサービスを利用するには、Auth0 Dashboadに設定済みのアプリケーションがある必要があります。Auth0アプリケーションは、開発中のプロジェクトに対してどのように認証が動作して欲しいかを構成する場所です。 - - ### アプリケーションを構成する - - 対話型のセレクターを使ってAuth0アプリケーションを新規作成するか、統合したいプロジェクトを表す既存のアプリケーションを選択します。Auth0のすべてのアプリケーションには英数字からなる一意のクライアントIDが割り当てられており、アプリケーションのコードがSDKを通じてAuth0 - APIを呼び出す際に使用されます。 - - このクイックスタートを使って構成されたすべての設定は、[Dashboard](https://manage.auth0.com/#/)のアプリケーションを自動更新します。今後、アプリケーションの管理もDashboardで行えます。 - - 代わりに完了済みの構成を見てみたい場合は、サンプルアプリケーションをご覧ください。 - - ### Callback URLを構成する - - Callback URLとは、Auth0がユーザーを認証後にリダイレクトするアプリケーション内URLです。設定されていない場合、ユーザーはログイン後にアプリケーションに戻されません。 - - - サンプルプロジェクトに沿って進めている場合は、`http://localhost:3000/auth/callback`に設定してください。 - - - ### ログアウトURLを構成する - - ログアウトURLとは、Auth0がユーザーをログアウト後にリダイレクトするアプリケーション内URLです。設定されていない場合、ユーザーはアプリケーションからログアウトできず、エラーを受け取ります。 - - - サンプルプロジェクトに沿って進めている場合は、`http://localhost:3000`に設定してください。 - -
    - -
    - プロジェクトディレクトリで次のコマンドを実行して、Auth0 Next.js SDKをインストールします: - - ```bash lines - npm install @auth0/nextjs-auth0 - ``` - - SDKは、Auth0をNext.jsアプリケーションに統合するのに役立つメソッドと変数を公開します。この際、バックエンドでは[ルートハンドラー](https://nextjs.org/docs/app/building-your-application/routing/route-handlers)を、フロントエンドでは[Reactフック](https://reactjs.org/docs/hooks-overview.html)が付いた[Reactコンテキスト](https://reactjs.org/docs/context.html)を使用します。 -
    - -
    - プロジェクトのルートディレクトリで、`.env.local`ファイルを追加し、以下の[変数環境](https://nextjs.org/docs/basic-features/environment-variables)を設定します: - - - `AUTH0_SECRET`:セッションクッキーの暗号化に使用する長いシークレット値です。適した文字列は、コマンドラインの`openssl rand -hex 32`で生成できます。 - - `AUTH0_BASE_URL`:アプリケーションのベースURLです。 - - `AUTH0_ISSUER_BASE_URL`:Auth0テナントドメインのURLです。[Auth0を使用したカスタムドメイン](/docs/ja-jp/custom-domains)では、この値を[Settings(設定)]タブに反映された値でなく、カスタムドメインの値に設定します。 - - `AUTH0_CLIENT_ID`:Auth0アプリケーションのクライアントIDです。 - - `AUTH0_CLIENT_SECRET`:Auth0アプリケーションのクライアントシークレットです。 - - SDKは、Node.jsプロセス環境からこれらの値を読み取り、自動構成します。 -
    - -
    - - このクイックスタートは、Next.js[アプリルーター](https://nextjs.org/docs/app)を取り扱います。[ページルーター](https://nextjs.org/docs/pages)を使用している場合は、SDKの[README](https://github.com/auth0/nextjs-auth0#page-router)の例を確認してください。 - - - `app/api/auth/[auth0]/route.js`でファイルを作成します。これは、[動的ルートセグメント](https://nextjs.org/docs/app/building-your-application/routing/route-handlers#dynamic-route-segments)を持つルートハンドラーです。 - - 次に、SDKから`handleAuth`メソッドをインポートし、`GET`エクスポートから呼び出します。これで、以下のルートが作成されます。 - - - `/api/auth/login`:Auth0でログインを実行するために使用されるルートです。 - - `/api/auth/logout`:ユーザーをログアウトするために使用されるルートです。 - - `/api/auth/callback`:ログインに成功した後、Auth0がユーザーをリダイレクトするルートです。 - - `/api/auth/me`:ユーザープロファイルを取得するためのルートです。 -
    - -
    - フロントエンド側では、SDKはReact Contextを使用して、ユーザーの認証状態を管理します。その状態をすべてのページで使用できるようにするには、[Root - Layoutコンポーネント](https://nextjs.org/docs/app/building-your-application/routing/pages-and-layouts#root-layout-required)を上書きし、`app/layout.jsx`ファイルで``タグを`UserProvider`でラップする必要があります。 - - `UserProvider`によって公開された認証状態は、`useUser()`フックを使って任意のクライアントコンポーネントでアクセスすることができます。 - - - ##### チェックポイント - - ルートハンドラーと`UserProvider`を追加したら、アプリケーションを実行してAuth0に関連したエラーを投入していないか確認します。 - -
    - -
    - ユーザーはSDKによって提供された`/api/auth/login`ルートハンドラーを訪れることで、アプリケーションにログインできるようになりました。**アンカータグ** を使ってログインルートを指すリンクをクリックします。クリックするとユーザーはAuth0ユニバーサルログインページにリダイレクトされ、そこで、Auth0はユーザーを認証することができます。認証に成功したら、Auth0はユーザーをアプリケーションにリダイレクトで戻します。 - - - ログアウトの機能性はすでに`src/app/page.tsx`ファイルに含まれています。ユーザーが**[Log - out(ログアウト)]**ボタンを選択すると、Auth0のログアウトエンドポイントにリダイレクトされ、セッションの消去後にアプリにリダイレクトで戻されます。 - - - - ##### チェックポイント - - アプリケーションにログインリンクを追加する - - - ログインリンクをクリックすると、Next.jsアプリケーションによって[Auth0ユニバーサルログイン](https://auth0.com/universal-login)ページにリダイレクトされ、ユーザー名とパスワードまたはソーシャルプロバイダーを使ってログインまたはサインアップできるようになったことを確認します。 - - 完了したら、Auth0がアプリケーションにリダイレクトで戻すことを確認します。 - - - - - - - - Auth0は、Googleソーシャルプロバイダーを新しいテナントでデフォルトで有効にし、[ソーシャルIDプロバイダー](/docs/ja-jp/connections/identity-providers-social)でログインテストを実施するための開発者キーを提供します。ただし、これらの開発者キーにはいくつかの制限が設けられており、これによってアプリケーションが異なる動作をする場合があります。この動作の様子と修正方法については、「[Auth0開発者キーを使ってソーシャル接続をテストする](/docs/ja-jp/connections/social/devkeys#limitations-of-developer-keys)」ドキュメントを参照してください。 - -
    - -
    - Next.jsアプリケーションにログインできるようになったら、[ログアウトする方法](/docs/ja-jp/logout/log-users-out-of-auth0)が必要です。`/api/auth/logout` APIルートを指すリンクを追加します。クリックするとユーザーは、[Auth0ログアウトエンドポイント](https://auth0.com/docs/api/authentication?javascript#logout)(`https://YOUR_DOMAIN/v2/logout`)にリダイレクトされ、即座にアプリケーションにリダイレクトで戻ります。 - - - ##### チェックポイント - - アプリケーションを実行する - - - Next.jsアプリケーションが[Auth0のユニバーサルログイン](https://auth0.com/universal-login)ページにリダイレクトし、ユーザー名とパスワードまたはソーシャルプロバイダーを使ってログインまたはサインアップできるようになったことを確認します。 - - 完了したら、Auth0がアプリケーションにリダイレクトで戻すことを確認します。 - -
    - - ## 次のステップ - - 成功です!ここまで来れば、アプリケーションにログイン、ログアウト、ユーザープロファイル情報が備わっているはずです。 - - これでクイックスタートチュートリアルは終了ですが、機能はまだまだたくさんあります。Auth0でできることについて詳しくは、以下をご覧ください。 - - * [Auth0 Dashboard](https://manage.auth0.com/#) - Auth0のテナントやアプリケーションを構成して管理する方法について説明します - * [nextjs-auth0 SDK](https://github.com/auth0/nextjs-auth0/) - このチュートリアルで使用されているSDKをより詳しく説明します - * [Auth0 Marketplace](https://marketplace.auth0.com/) - Auth0の機能性を拡張できる各種の統合を見つけられます -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    +--- +title: "Next.jsアプリケーションにログインを追加する" +permalink: "interactive" +'description': "このガイドは、新規または既存のNext.jsアプリケーションにAuth0 Next.js SDKを使ってAuth0を統合する方法を説明します。" +'og:title': "Next.jsアプリケーションにログインを追加する" +'og:description': "このガイドは、新規または既存のNext.jsアプリケーションにAuth0 Next.js SDKを使ってAuth0を統合する方法を説明します。" +'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/nginx-plus.png" +'twitter:title': "Next.jsアプリケーションにログインを追加する" +'twitter:description': "このガイドは、新規または既存のNext.jsアプリケーションにAuth0 Next.js SDKを使ってAuth0を統合する方法を説明します。" +sidebarTitle: Next.js +mode: wide +--- + +import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; +import { LoggedInForm } from "/snippets/Login.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + +import ConfigureSDK from "/snippets/quickstart/webapp/nextjs/configure-the-sdk.mdx" +import CreateAuth0SDKClient from "/snippets/quickstart/webapp/nextjs/create-the-auth0-sdk-client.mdx" +import CreateLoginPage from "/snippets/quickstart/webapp/nextjs/create-a-login-page.mdx" +import AddLandingPageContent from "/snippets/quickstart/webapp/nextjs/add-the-landing-page-content.mdx" + +export const sections = [ + { id: "auth0を構成する", title: "Auth0を構成する" }, + { id: "auth0-next-js-sdkをインストールする", title: "Auth0 Next.js SDKをインストールする" }, + { id: "sdkを構成する", title: "SDKを構成する" }, + { id: "動的ルートハンドラーを追加する", title: "動的ルートハンドラーを追加する" }, + { id: "userproviderコンポーネントを追加する", title: "UserProviderコンポーネントを追加する" }, + { id: "アプリケーションにログインを追加する", title: "アプリケーションにログインを追加する" }, + { id: "アプリケーションにログアウトを追加する", title: "アプリケーションにログアウトを追加する" } +] + + + + このガイドは、新規または既存のNext.jsアプリケーションにAuth0 Next.js SDKを使ってAuth0を統合する方法を説明します。アカウント用に構成された例を参考にして、このクイックスタートに従うことをお勧めします。 + +
    + Auth0のサービスを利用するには、Auth0 Dashboadに設定済みのアプリケーションがある必要があります。Auth0アプリケーションは、開発中のプロジェクトに対してどのように認証が動作して欲しいかを構成する場所です。 + + ### アプリケーションを構成する + + 対話型のセレクターを使ってAuth0アプリケーションを新規作成するか、統合したいプロジェクトを表す既存のアプリケーションを選択します。Auth0のすべてのアプリケーションには英数字からなる一意のクライアントIDが割り当てられており、アプリケーションのコードがSDKを通じてAuth0 + APIを呼び出す際に使用されます。 + + このクイックスタートを使って構成されたすべての設定は、[Dashboard](https://manage.auth0.com/#/)のアプリケーションを自動更新します。今後、アプリケーションの管理もDashboardで行えます。 + + 代わりに完了済みの構成を見てみたい場合は、サンプルアプリケーションをご覧ください。 + + ### Callback URLを構成する + + Callback URLとは、Auth0がユーザーを認証後にリダイレクトするアプリケーション内URLです。設定されていない場合、ユーザーはログイン後にアプリケーションに戻されません。 + + + サンプルプロジェクトに沿って進めている場合は、`http://localhost:3000/auth/callback`に設定してください。 + + + ### ログアウトURLを構成する + + ログアウトURLとは、Auth0がユーザーをログアウト後にリダイレクトするアプリケーション内URLです。設定されていない場合、ユーザーはアプリケーションからログアウトできず、エラーを受け取ります。 + + + サンプルプロジェクトに沿って進めている場合は、`http://localhost:3000`に設定してください。 + +
    + +
    + プロジェクトディレクトリで次のコマンドを実行して、Auth0 Next.js SDKをインストールします: + + ```bash lines + npm install @auth0/nextjs-auth0 + ``` + + SDKは、Auth0をNext.jsアプリケーションに統合するのに役立つメソッドと変数を公開します。この際、バックエンドでは[ルートハンドラー](https://nextjs.org/docs/app/building-your-application/routing/route-handlers)を、フロントエンドでは[Reactフック](https://reactjs.org/docs/hooks-overview.html)が付いた[Reactコンテキスト](https://reactjs.org/docs/context.html)を使用します。 +
    + +
    + プロジェクトのルートディレクトリで、`.env.local`ファイルを追加し、以下の[変数環境](https://nextjs.org/docs/basic-features/environment-variables)を設定します: + + - `AUTH0_SECRET`:セッションクッキーの暗号化に使用する長いシークレット値です。適した文字列は、コマンドラインの`openssl rand -hex 32`で生成できます。 + - `AUTH0_BASE_URL`:アプリケーションのベースURLです。 + - `AUTH0_ISSUER_BASE_URL`:Auth0テナントドメインのURLです。[Auth0を使用したカスタムドメイン](/docs/ja-jp/custom-domains)では、この値を[Settings(設定)]タブに反映された値でなく、カスタムドメインの値に設定します。 + - `AUTH0_CLIENT_ID`:Auth0アプリケーションのクライアントIDです。 + - `AUTH0_CLIENT_SECRET`:Auth0アプリケーションのクライアントシークレットです。 + + SDKは、Node.jsプロセス環境からこれらの値を読み取り、自動構成します。 +
    + +
    + + このクイックスタートは、Next.js[アプリルーター](https://nextjs.org/docs/app)を取り扱います。[ページルーター](https://nextjs.org/docs/pages)を使用している場合は、SDKの[README](https://github.com/auth0/nextjs-auth0#page-router)の例を確認してください。 + + + `app/api/auth/[auth0]/route.js`でファイルを作成します。これは、[動的ルートセグメント](https://nextjs.org/docs/app/building-your-application/routing/route-handlers#dynamic-route-segments)を持つルートハンドラーです。 + + 次に、SDKから`handleAuth`メソッドをインポートし、`GET`エクスポートから呼び出します。これで、以下のルートが作成されます。 + + - `/api/auth/login`:Auth0でログインを実行するために使用されるルートです。 + - `/api/auth/logout`:ユーザーをログアウトするために使用されるルートです。 + - `/api/auth/callback`:ログインに成功した後、Auth0がユーザーをリダイレクトするルートです。 + - `/api/auth/me`:ユーザープロファイルを取得するためのルートです。 +
    + +
    + フロントエンド側では、SDKはReact Contextを使用して、ユーザーの認証状態を管理します。その状態をすべてのページで使用できるようにするには、[Root + Layoutコンポーネント](https://nextjs.org/docs/app/building-your-application/routing/pages-and-layouts#root-layout-required)を上書きし、`app/layout.jsx`ファイルで``タグを`UserProvider`でラップする必要があります。 + + `UserProvider`によって公開された認証状態は、`useUser()`フックを使って任意のクライアントコンポーネントでアクセスすることができます。 + + + ##### チェックポイント + + ルートハンドラーと`UserProvider`を追加したら、アプリケーションを実行してAuth0に関連したエラーを投入していないか確認します。 + +
    + +
    + ユーザーはSDKによって提供された`/api/auth/login`ルートハンドラーを訪れることで、アプリケーションにログインできるようになりました。**アンカータグ** を使ってログインルートを指すリンクをクリックします。クリックするとユーザーはAuth0ユニバーサルログインページにリダイレクトされ、そこで、Auth0はユーザーを認証することができます。認証に成功したら、Auth0はユーザーをアプリケーションにリダイレクトで戻します。 + + + ログアウトの機能性はすでに`src/app/page.tsx`ファイルに含まれています。ユーザーが**[Log + out(ログアウト)]**ボタンを選択すると、Auth0のログアウトエンドポイントにリダイレクトされ、セッションの消去後にアプリにリダイレクトで戻されます。 + + + + ##### チェックポイント + + アプリケーションにログインリンクを追加する + + - ログインリンクをクリックすると、Next.jsアプリケーションによって[Auth0ユニバーサルログイン](https://auth0.com/universal-login)ページにリダイレクトされ、ユーザー名とパスワードまたはソーシャルプロバイダーを使ってログインまたはサインアップできるようになったことを確認します。 + - 完了したら、Auth0がアプリケーションにリダイレクトで戻すことを確認します。 + + + + + + + + Auth0は、Googleソーシャルプロバイダーを新しいテナントでデフォルトで有効にし、[ソーシャルIDプロバイダー](/docs/ja-jp/connections/identity-providers-social)でログインテストを実施するための開発者キーを提供します。ただし、これらの開発者キーにはいくつかの制限が設けられており、これによってアプリケーションが異なる動作をする場合があります。この動作の様子と修正方法については、「[Auth0開発者キーを使ってソーシャル接続をテストする](/docs/ja-jp/connections/social/devkeys#limitations-of-developer-keys)」ドキュメントを参照してください。 + +
    + +
    + Next.jsアプリケーションにログインできるようになったら、[ログアウトする方法](/docs/ja-jp/logout/log-users-out-of-auth0)が必要です。`/api/auth/logout` APIルートを指すリンクを追加します。クリックするとユーザーは、[Auth0ログアウトエンドポイント](https://auth0.com/docs/api/authentication?javascript#logout)(`https://YOUR_DOMAIN/v2/logout`)にリダイレクトされ、即座にアプリケーションにリダイレクトで戻ります。 + + + ##### チェックポイント + + アプリケーションを実行する + + - Next.jsアプリケーションが[Auth0のユニバーサルログイン](https://auth0.com/universal-login)ページにリダイレクトし、ユーザー名とパスワードまたはソーシャルプロバイダーを使ってログインまたはサインアップできるようになったことを確認します。 + - 完了したら、Auth0がアプリケーションにリダイレクトで戻すことを確認します。 + +
    + + ## 次のステップ + + 成功です!ここまで来れば、アプリケーションにログイン、ログアウト、ユーザープロファイル情報が備わっているはずです。 + + これでクイックスタートチュートリアルは終了ですが、機能はまだまだたくさんあります。Auth0でできることについて詳しくは、以下をご覧ください。 + + * [Auth0 Dashboard](https://manage.auth0.com/#) - Auth0のテナントやアプリケーションを構成して管理する方法について説明します + * [nextjs-auth0 SDK](https://github.com/auth0/nextjs-auth0/) - このチュートリアルで使用されているSDKをより詳しく説明します + * [Auth0 Marketplace](https://marketplace.auth0.com/) - Auth0の機能性を拡張できる各種の統合を見つけられます +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    diff --git a/main/docs/ja-jp/quickstart/webapp/nginx-plus/interactive.mdx b/main/docs/ja-jp/quickstart/webapp/nginx-plus/interactive.mdx index 2ed42fd19..c0686e523 100644 --- a/main/docs/ja-jp/quickstart/webapp/nginx-plus/interactive.mdx +++ b/main/docs/ja-jp/quickstart/webapp/nginx-plus/interactive.mdx @@ -19,6 +19,8 @@ import OpenidConnectionConfiguration from "/snippets/quickstart/webapp/nginx-plu import OpenidConnect from "/snippets/quickstart/webapp/nginx-plus/openid_connect.server_conf.mdx"; import Frontend from "/snippets/quickstart/webapp/nginx-plus/frontend.conf.mdx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + export const sections = [ { id: "システム要件", title: "システム要件" }, { id: "nginx-plus-module-njsモジュールをインストールして有効にする", title: "nginx-plus-module-njsモジュールをインストールして有効にする" }, @@ -132,12 +134,12 @@ export const codeExample = ` ./configure.sh --auth_jwt_key request \ - + - + @@ -145,21 +147,21 @@ export const codeExample = ` ./configure.sh --auth_jwt_key request \ - + - + - + - + @@ -171,12 +173,12 @@ export const codeExample = ` ./configure.sh --auth_jwt_key request \ - + - + diff --git a/main/docs/ja-jp/quickstart/webapp/php/interactive.mdx b/main/docs/ja-jp/quickstart/webapp/php/interactive.mdx index 49650bc80..d150b4b31 100644 --- a/main/docs/ja-jp/quickstart/webapp/php/interactive.mdx +++ b/main/docs/ja-jp/quickstart/webapp/php/interactive.mdx @@ -1,259 +1,261 @@ ---- -title: "PHPアプリケーションにログインを追加する" -permalink: "interactive" -'description': "このガイドは、PHPアプリケーションにAuth0 PHP SDKを使ってAuth0を統合し、認証の追加とユーザープロファイル情報の表示を行う方法について説明します。" -'og:title': "PHPアプリケーションにログインを追加する" -'og:description': "このガイドは、PHPアプリケーションにAuth0 PHP SDKを使ってAuth0を統合し、認証の追加とユーザープロファイル情報の表示を行う方法について説明します。" -'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/php.png" -'twitter:title': "PHPアプリケーションにログインを追加する" -'twitter:description': "このガイドは、PHPアプリケーションにAuth0 PHP SDKを使ってAuth0を統合し、認証の追加とユーザープロファイル情報の表示を行う方法について説明します。" -sidebarTitle: PHP -mode: wide ---- - -import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; -import { LoggedInForm } from "/snippets/Login.jsx"; -import Index from "/snippets/quickstart/webapp/php/index.php.mdx"; -import Login from "/snippets/quickstart/webapp/php/login.php.mdx"; -import Logout from "/snippets/quickstart/webapp/php/logout.php.mdx"; -import Profile from "/snippets/quickstart/webapp/php/profile.php.mdx"; -import Router from "/snippets/quickstart/webapp/php/router.php.mdx"; -import Callback from "/snippets/quickstart/webapp/php/callback.php.mdx"; - -export const sections = [ - { id: "auth0を構成する", title: "Auth0を構成する" }, - { id: "auth0-php-sdkをインストールする", title: "Auth0 PHP SDKをインストールする" }, - { id: "ルートを作成する", title: "ルートを作成する" }, - { id: "アプリケーションにログインを追加する", title: "アプリケーションにログインを追加する" }, - { id: "アプリケーションにログアウトを追加する", title: "アプリケーションにログアウトを追加する" }, - { id: "ユーザープロファイル情報を表示する", title: "ユーザープロファイル情報を表示する" } -] - - - - Auth0を使用すると、アプリケーションに手軽に認証を追加することができます。このガイドは、PHPアプリケーションにAuth0 PHP - SDKを使ってAuth0を統合し、認証の追加とユーザープロファイル情報の表示を行う方法について説明します。 - - このクイックスタートを使用するには、以下の手順に従います: - -
    - Auth0のサービスを利用するには、Auth0 Dashboadでセットアップしたアプリケーションが必要です。Auth0アプリケーションは、開発中のプロジェクトに対してどのように認証が動作して欲しいかを構成する場所です。 - - ### アプリケーションを構成する - - インタラクティブセレクターを使ってAuth0アプリケーションを新規作成するか、統合したいプロジェクトを表す既存のアプリケーションを選択します。Auth0の全てのアプリケーションには英数字からなる一意のクライアントIDが割り当てられており、アプリケーションのコードがSDKを通じてAuth0 - APIを呼び出す際に使用されます。 - - このクイックスタートを使って構成されたすべての設定は、[Dashboard](https://manage.auth0.com/#/)のアプリケーションに自動更新を行います。今後、アプリケーションの管理はDashboardで行えます。 - - 代わりに完了済みの構成を見てみたい場合は、サンプルアプリケーションをご覧ください。 - - ### Callback URLを構成する - - Callback URLとは、Auth0がユーザーを認証後にリダイレクトするアプリケーション内URLです。設定されていない場合、ユーザーはログイン後にアプリケーションに戻りません。 - - - サンプルプロジェクトに沿って進めている場合は、`http://localhost:3000/callback`に設定してください。 - - - ### ログアウトURLを構成する - - ログアウトURLとは、Auth0がユーザーをログアウト後にリダイレクトするアプリケーション内URLです。設定されていない場合、ユーザーはアプリケーションからログアウトできず、エラーを受け取ります。 - - - サンプルプロジェクトに沿って進めている場合は、`http://localhost:3000`に設定してください。 - - - ### Allowed Web Origins(許可されているWebオリジン)を構成する - - [Allowed Web - Origin(許可されているWebオリジン)]とは、認証フローにアクセスすることを許可して欲しいURLです。これにはプロジェクトのURLが含まれている必要があります。適切に設定されていない場合、プロジェクトが認証トークンを暗黙でリフレッシュできず、ユーザーがアプリケーションを再び訪問した時、またはページを再読み込みした時にログアウトした状態になってしまいます。 - - - サンプルプロジェクトに沿って進めている場合は、`http://localhost:3000`に設定してください。 - -
    - -
    - PHPアプリで、Auth0の認証・認可を手軽に実装できるように、Auth0は[PHP SDK](https://github.com/auth0/auth0-PHP)(Auth0-PHP)を提供しています。 - - Auth0 PHP SDKでは、ネットワーク要求を管理するために、[PSR-17](https://www.php-fig.org/psr/psr-17/)と[PSR-18](https://www.php-fig.org/psr/psr-18/)対応HTTPライブラリーをインストールする必要があります。ライブラリーがない場合は、ターミナルで以下のコマンドを実行して、信頼できる選択肢をインストールすることができます: - - ```text lines - cd - composer require symfony/http-client nyholm/psr7 - ``` - - - - ターミナルで以下のコマンドを実行してAuth0 PHP SDKをインストールします: - - ```text lines - composer require auth0/auth0-php - ``` - - - - ### Auth0 SDKを構成する - - アプリケーションで`index.php`と呼ばれる新しいファイルを作成し、**index.php** タブにある、右のインタラクティブパネルからコードをコピーします。 - - SDKが正しく機能するためには、次のプロパティを初期化中にAuth0 SDKで設定しなければなりません: - - - `domain`:Auth0テナントのドメインです。通常、Auth0 Dashboardにあるアプリケーションの設定の[Domain(ドメイン)]フィールドで確認できます。[カスタムドメイン](/docs/ja-jp/custom-domains)を使用している場合は、その値を代わりに設定してください。 - - `clientId`:このクイックスタートで前にセットアップした、Auth0アプリケーションのIDです。Auth0 - Dashboardにあるアプリケーションの[Settings(設定)]の[Client ID(クライアントID)]フィールドで確認できます。 - - `clientSecret`:このクイックスタートで前にセットアップしたAuth0アプリケーションのシークレットです。Auth0 - Dashboardにあるアプリケーションの[Settings(設定)]の[Client Secret(クライアントシークレット)]フィールドで確認できます。 - - `redirectUri`:ユーザー認証の後、Auth0にユーザーをリダイレクトするアプリケーション内URLです。このクイックスタートで前にセットアップしたCallback - URLと呼応します。Auth0 Dashboardにあるアプリケーションの設定の[Callback - URLs(コールバックURL)]フィールドでもこの値を確認できます。コードに入力した値と前にセットアップした値は必ず一致させてください。異なった場合はユーザーにエラーが表示されます。 - - `cookieSecret`:セッションクッキーの暗号化に使用する長いシークレット値です。ターミナルで`openssl rand -hex 32`を実行すると、適切な文字列を生成することができます。 - - - ##### チェックポイント - - Auth0 SDKが正しく構成されました。アプリケーションを実行して次の点を確認します: - - - SDKが正しく初期化している。 - - アプリケーションがAuth0に関連したエラーを投入していない。 - -
    - -
    - 次に、受信要求をアプリケーションにダイレクトするために、ルーティングライブラリーをインストールします。これは必須手順ではありませんが、本クイックスタートの目的上、アプリケーション構造が簡略化されます。 - - ```text lines - composer require steampixel/simple-php-router - ``` - - - - アプリケーションで`router.php`と呼ばれる新しいファイルを作成してルートを定義し、右のインタラクティブパネルからコードをコピーします。 -
    - -
    - Auth0アプリケーションとAuth0 PHP - SDKの構成が完了したら、プロジェクトのためにログインをセットアップする必要があります。これを実現するには、SDKの`login()`メソッドを使用して、ユーザーをAuth0のユニバーサルログインページにリダイレクトするログインボタンを作成します。ユーザーが認証に成功すると、このクイックスタートで前にセットアップしたCallback - URLへリダイレクトされます。 - - アプリケーションで`login.php`という名前の新規ファイルを作成し、右のインタラクティブパネルからコードをコピーします。これにはログインに必要なロジックが含まれています。 - - - ##### チェックポイント - - ユーザー名とパスワードを使ってログインやサインアップができるようになりました。 - - ログインリンクをクリックして次の点を確認します: - - - アプリケーションによってAuth0ユニバーサルログインページにリダイレクトされる。 - - ログインまたはサインアップできる。 - - Auth0が、SDKを構成するために使った`redirectUri`の値を使用し、アプリケーションへリダイレクトする。 - -
    - -
    - プロジェクトにログインしたユーザーには、ログアウトする方法も必要です。SDKの`logout()`メソッドを使用してログアウトボタンを処理します。ユーザーはログアウトすると、[Auth0ログアウト](https://auth0.com/docs/api/authentication?http#logout)エンドポイントにリダイレクトされてから、即座に、このクイックスタートで先ほどセットアップしたログアウトURLへとリダイレクトで戻されます。 - - アプリケーションで`logout.php`という名前の新規ファイルを作成し、インタラクティブパネルからコードをコピーします。これにはログアウトに必要なロジックが含まれています。それから`index.php`ファイルを更新して新しいログアウトボタンを含めます。 - - - ##### チェックポイント - - アプリケーションを実行してログアウトボタンをクリックし、次の点を確認します: - - - アプリケーションによって、アプリケーションの設定で[Allowed Logout URLs(許可されているログアウトURL)]の1つに指定されているアドレスへリダイレクトされる。 - - アプリケーションにもうログインしていない。 - -
    - -
    - ユーザーがログインやログアウトできるようになったら、認証済のユーザーに関連付けられた[プロファイル情報](/docs/ja-jp/users/concepts/overview-user-profile)を取得できるようにしたいと考えるはずです。たとえば、ログインしたユーザーの名前やプロフィール写真をプロジェクトに表示したいかもしれません。 - - Auth0 PHP - SDKでは`getCredentials()`メソッドからユーザー情報が提供されます。インタラクティブパネルで`profile.php`コードを確認し、使用方法の例をチェックします。 - - このメソッドにはユーザーのアイデンティティに関する機密情報が含まれるため、この方法が使用できるかはユーザーの認証ステータスによります。エラーを防ぐため、`getCredentials()`メソッドが`object`または`null`を返すかを必ず確認し、アプリケーションが結果を使用する前に、Auth0がユーザーを認証したかどうか判定します。 - - - ##### チェックポイント - - 以下の点を確認します: - - - ログイン後、`nickname`やその他のユーザープロパティをすべて正しく表示できる。 - -
    - - ## 次のステップ - - 成功です!ここまで来れば、アプリケーションにログイン、ログアウト、ユーザープロファイル情報が備わっているはずです。 - - これでクイックスタートチュートリアルは終了ですが、機能はまだまだたくさんあります。Auth0でできることについて詳しくは、以下をご覧ください。 - - * [Auth0 Dashboard](https://manage.auth0.com/#) - Auth0のテナントやアプリケーションを構成して管理する方法について説明します - * [Auth0-PHP SDK](https://github.com/auth0/auth0-php) - このチュートリアルで使用されているSDKをより詳しく説明します - * [Auth0 Marketplace](https://marketplace.auth0.com/) - Auth0の機能性を拡張できる各種の統合を見つけられます -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    +--- +title: "PHPアプリケーションにログインを追加する" +permalink: "interactive" +'description': "このガイドは、PHPアプリケーションにAuth0 PHP SDKを使ってAuth0を統合し、認証の追加とユーザープロファイル情報の表示を行う方法について説明します。" +'og:title': "PHPアプリケーションにログインを追加する" +'og:description': "このガイドは、PHPアプリケーションにAuth0 PHP SDKを使ってAuth0を統合し、認証の追加とユーザープロファイル情報の表示を行う方法について説明します。" +'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/php.png" +'twitter:title': "PHPアプリケーションにログインを追加する" +'twitter:description': "このガイドは、PHPアプリケーションにAuth0 PHP SDKを使ってAuth0を統合し、認証の追加とユーザープロファイル情報の表示を行う方法について説明します。" +sidebarTitle: PHP +mode: wide +--- + +import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; +import { LoggedInForm } from "/snippets/Login.jsx"; +import Index from "/snippets/quickstart/webapp/php/index.php.mdx"; +import Login from "/snippets/quickstart/webapp/php/login.php.mdx"; +import Logout from "/snippets/quickstart/webapp/php/logout.php.mdx"; +import Profile from "/snippets/quickstart/webapp/php/profile.php.mdx"; +import Router from "/snippets/quickstart/webapp/php/router.php.mdx"; +import Callback from "/snippets/quickstart/webapp/php/callback.php.mdx"; + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + +export const sections = [ + { id: "auth0を構成する", title: "Auth0を構成する" }, + { id: "auth0-php-sdkをインストールする", title: "Auth0 PHP SDKをインストールする" }, + { id: "ルートを作成する", title: "ルートを作成する" }, + { id: "アプリケーションにログインを追加する", title: "アプリケーションにログインを追加する" }, + { id: "アプリケーションにログアウトを追加する", title: "アプリケーションにログアウトを追加する" }, + { id: "ユーザープロファイル情報を表示する", title: "ユーザープロファイル情報を表示する" } +] + + + + Auth0を使用すると、アプリケーションに手軽に認証を追加することができます。このガイドは、PHPアプリケーションにAuth0 PHP + SDKを使ってAuth0を統合し、認証の追加とユーザープロファイル情報の表示を行う方法について説明します。 + + このクイックスタートを使用するには、以下の手順に従います: + +
    + Auth0のサービスを利用するには、Auth0 Dashboadでセットアップしたアプリケーションが必要です。Auth0アプリケーションは、開発中のプロジェクトに対してどのように認証が動作して欲しいかを構成する場所です。 + + ### アプリケーションを構成する + + インタラクティブセレクターを使ってAuth0アプリケーションを新規作成するか、統合したいプロジェクトを表す既存のアプリケーションを選択します。Auth0の全てのアプリケーションには英数字からなる一意のクライアントIDが割り当てられており、アプリケーションのコードがSDKを通じてAuth0 + APIを呼び出す際に使用されます。 + + このクイックスタートを使って構成されたすべての設定は、[Dashboard](https://manage.auth0.com/#/)のアプリケーションに自動更新を行います。今後、アプリケーションの管理はDashboardで行えます。 + + 代わりに完了済みの構成を見てみたい場合は、サンプルアプリケーションをご覧ください。 + + ### Callback URLを構成する + + Callback URLとは、Auth0がユーザーを認証後にリダイレクトするアプリケーション内URLです。設定されていない場合、ユーザーはログイン後にアプリケーションに戻りません。 + + + サンプルプロジェクトに沿って進めている場合は、`http://localhost:3000/callback`に設定してください。 + + + ### ログアウトURLを構成する + + ログアウトURLとは、Auth0がユーザーをログアウト後にリダイレクトするアプリケーション内URLです。設定されていない場合、ユーザーはアプリケーションからログアウトできず、エラーを受け取ります。 + + + サンプルプロジェクトに沿って進めている場合は、`http://localhost:3000`に設定してください。 + + + ### Allowed Web Origins(許可されているWebオリジン)を構成する + + [Allowed Web + Origin(許可されているWebオリジン)]とは、認証フローにアクセスすることを許可して欲しいURLです。これにはプロジェクトのURLが含まれている必要があります。適切に設定されていない場合、プロジェクトが認証トークンを暗黙でリフレッシュできず、ユーザーがアプリケーションを再び訪問した時、またはページを再読み込みした時にログアウトした状態になってしまいます。 + + + サンプルプロジェクトに沿って進めている場合は、`http://localhost:3000`に設定してください。 + +
    + +
    + PHPアプリで、Auth0の認証・認可を手軽に実装できるように、Auth0は[PHP SDK](https://github.com/auth0/auth0-PHP)(Auth0-PHP)を提供しています。 + + Auth0 PHP SDKでは、ネットワーク要求を管理するために、[PSR-17](https://www.php-fig.org/psr/psr-17/)と[PSR-18](https://www.php-fig.org/psr/psr-18/)対応HTTPライブラリーをインストールする必要があります。ライブラリーがない場合は、ターミナルで以下のコマンドを実行して、信頼できる選択肢をインストールすることができます: + + ```text lines + cd + composer require symfony/http-client nyholm/psr7 + ``` + + + + ターミナルで以下のコマンドを実行してAuth0 PHP SDKをインストールします: + + ```text lines + composer require auth0/auth0-php + ``` + + + + ### Auth0 SDKを構成する + + アプリケーションで`index.php`と呼ばれる新しいファイルを作成し、**index.php** タブにある、右のインタラクティブパネルからコードをコピーします。 + + SDKが正しく機能するためには、次のプロパティを初期化中にAuth0 SDKで設定しなければなりません: + + - `domain`:Auth0テナントのドメインです。通常、Auth0 Dashboardにあるアプリケーションの設定の[Domain(ドメイン)]フィールドで確認できます。[カスタムドメイン](/docs/ja-jp/custom-domains)を使用している場合は、その値を代わりに設定してください。 + - `clientId`:このクイックスタートで前にセットアップした、Auth0アプリケーションのIDです。Auth0 + Dashboardにあるアプリケーションの[Settings(設定)]の[Client ID(クライアントID)]フィールドで確認できます。 + - `clientSecret`:このクイックスタートで前にセットアップしたAuth0アプリケーションのシークレットです。Auth0 + Dashboardにあるアプリケーションの[Settings(設定)]の[Client Secret(クライアントシークレット)]フィールドで確認できます。 + - `redirectUri`:ユーザー認証の後、Auth0にユーザーをリダイレクトするアプリケーション内URLです。このクイックスタートで前にセットアップしたCallback + URLと呼応します。Auth0 Dashboardにあるアプリケーションの設定の[Callback + URLs(コールバックURL)]フィールドでもこの値を確認できます。コードに入力した値と前にセットアップした値は必ず一致させてください。異なった場合はユーザーにエラーが表示されます。 + - `cookieSecret`:セッションクッキーの暗号化に使用する長いシークレット値です。ターミナルで`openssl rand -hex 32`を実行すると、適切な文字列を生成することができます。 + + + ##### チェックポイント + + Auth0 SDKが正しく構成されました。アプリケーションを実行して次の点を確認します: + + - SDKが正しく初期化している。 + - アプリケーションがAuth0に関連したエラーを投入していない。 + +
    + +
    + 次に、受信要求をアプリケーションにダイレクトするために、ルーティングライブラリーをインストールします。これは必須手順ではありませんが、本クイックスタートの目的上、アプリケーション構造が簡略化されます。 + + ```text lines + composer require steampixel/simple-php-router + ``` + + + + アプリケーションで`router.php`と呼ばれる新しいファイルを作成してルートを定義し、右のインタラクティブパネルからコードをコピーします。 +
    + +
    + Auth0アプリケーションとAuth0 PHP + SDKの構成が完了したら、プロジェクトのためにログインをセットアップする必要があります。これを実現するには、SDKの`login()`メソッドを使用して、ユーザーをAuth0のユニバーサルログインページにリダイレクトするログインボタンを作成します。ユーザーが認証に成功すると、このクイックスタートで前にセットアップしたCallback + URLへリダイレクトされます。 + + アプリケーションで`login.php`という名前の新規ファイルを作成し、右のインタラクティブパネルからコードをコピーします。これにはログインに必要なロジックが含まれています。 + + + ##### チェックポイント + + ユーザー名とパスワードを使ってログインやサインアップができるようになりました。 + + ログインリンクをクリックして次の点を確認します: + + - アプリケーションによってAuth0ユニバーサルログインページにリダイレクトされる。 + - ログインまたはサインアップできる。 + - Auth0が、SDKを構成するために使った`redirectUri`の値を使用し、アプリケーションへリダイレクトする。 + +
    + +
    + プロジェクトにログインしたユーザーには、ログアウトする方法も必要です。SDKの`logout()`メソッドを使用してログアウトボタンを処理します。ユーザーはログアウトすると、[Auth0ログアウト](https://auth0.com/docs/api/authentication?http#logout)エンドポイントにリダイレクトされてから、即座に、このクイックスタートで先ほどセットアップしたログアウトURLへとリダイレクトで戻されます。 + + アプリケーションで`logout.php`という名前の新規ファイルを作成し、インタラクティブパネルからコードをコピーします。これにはログアウトに必要なロジックが含まれています。それから`index.php`ファイルを更新して新しいログアウトボタンを含めます。 + + + ##### チェックポイント + + アプリケーションを実行してログアウトボタンをクリックし、次の点を確認します: + + - アプリケーションによって、アプリケーションの設定で[Allowed Logout URLs(許可されているログアウトURL)]の1つに指定されているアドレスへリダイレクトされる。 + - アプリケーションにもうログインしていない。 + +
    + +
    + ユーザーがログインやログアウトできるようになったら、認証済のユーザーに関連付けられた[プロファイル情報](/docs/ja-jp/users/concepts/overview-user-profile)を取得できるようにしたいと考えるはずです。たとえば、ログインしたユーザーの名前やプロフィール写真をプロジェクトに表示したいかもしれません。 + + Auth0 PHP + SDKでは`getCredentials()`メソッドからユーザー情報が提供されます。インタラクティブパネルで`profile.php`コードを確認し、使用方法の例をチェックします。 + + このメソッドにはユーザーのアイデンティティに関する機密情報が含まれるため、この方法が使用できるかはユーザーの認証ステータスによります。エラーを防ぐため、`getCredentials()`メソッドが`object`または`null`を返すかを必ず確認し、アプリケーションが結果を使用する前に、Auth0がユーザーを認証したかどうか判定します。 + + + ##### チェックポイント + + 以下の点を確認します: + + - ログイン後、`nickname`やその他のユーザープロパティをすべて正しく表示できる。 + +
    + + ## 次のステップ + + 成功です!ここまで来れば、アプリケーションにログイン、ログアウト、ユーザープロファイル情報が備わっているはずです。 + + これでクイックスタートチュートリアルは終了ですが、機能はまだまだたくさんあります。Auth0でできることについて詳しくは、以下をご覧ください。 + + * [Auth0 Dashboard](https://manage.auth0.com/#) - Auth0のテナントやアプリケーションを構成して管理する方法について説明します + * [Auth0-PHP SDK](https://github.com/auth0/auth0-php) - このチュートリアルで使用されているSDKをより詳しく説明します + * [Auth0 Marketplace](https://marketplace.auth0.com/) - Auth0の機能性を拡張できる各種の統合を見つけられます +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    diff --git a/main/docs/ja-jp/quickstart/webapp/python/interactive.mdx b/main/docs/ja-jp/quickstart/webapp/python/interactive.mdx index 2cb4dfa64..8c35df07e 100644 --- a/main/docs/ja-jp/quickstart/webapp/python/interactive.mdx +++ b/main/docs/ja-jp/quickstart/webapp/python/interactive.mdx @@ -1,184 +1,186 @@ ---- -title: "Python Flaskアプリケーションにログインを追加する" -permalink: "interactive" -'description': "このガイドでは、Python FlaskアプリケーションにAuthlib SDKを使ってAuth0を統合する方法を説明します。" -'og:title': "Python Flaskアプリケーションにログインを追加する" -'og:description': "このガイドでは、Python FlaskアプリケーションにAuthlib SDKを使ってAuth0を統合する方法を説明します。" -'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/python.png" -'twitter:title': "Python Flaskアプリケーションにログインを追加する" -'twitter:description': "このガイドでは、Python FlaskアプリケーションにAuthlib SDKを使ってAuth0を統合する方法を説明します。" -sidebarTitle: Python -mode: wide ---- - -import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; -import { LoggedInForm } from "/snippets/Login.jsx"; -import Server from "/snippets/quickstart/webapp/python/server.py.mdx"; -import Home from "/snippets/quickstart/webapp/python/home.html.mdx"; - -export const sections = [ - { id: "auth0を構成する", title: "Auth0を構成する" }, - { id: "依存関係をインストールする", title: "依存関係をインストールする" }, - { id: "envファイルを構成する", title: ".envファイルを構成する" }, - { id: "アプリケーションをセットアップする", title: "アプリケーションをセットアップする" }, - { id: "ルートをセットアップする", title: "ルートをセットアップする" }, - { id: "テンプレートを追加する", title: "テンプレートを追加する" }, - { id: "アプリケーションを実行する", title: "アプリケーションを実行する" } -] - - - - Auth0を使用すると、アプリケーションに認証を追加して、ユーザープロファイル情報にアクセスすることができます。このガイドでは、Python [Flask](https://flask.palletsprojects.com/)アプリケーションに[Authlib](https://authlib.org/) SDKを使ってAuth0を統合する方法を説明します。 - -
    - Auth0のサービスを利用するには、Auth0 Dashboadでセットアップしたアプリケーションが必要です。Auth0アプリケーションは、開発中のプロジェクトに対してどのように認証が動作して欲しいかを構成する場所です。 - - ### アプリケーションを構成する - - 対話型のセレクターを使ってAuth0アプリケーションを新規作成するか、統合したいプロジェクトを表す既存のアプリケーションを選択します。Auth0のすべてのアプリケーションには英数字からなる一意のクライアントIDが割り当てられており、アプリケーションのコードがSDKを通じてAuth0 - APIを呼び出す際に使用されます。 - - このクイックスタートを使って構成されたすべての設定は、[Dashboard](https://manage.auth0.com/#/)のアプリケーションを自動更新します。今後、アプリケーションの管理もDashboardで行えます。 - - 代わりに完了済みの構成を見てみたい場合は、サンプルアプリケーションをご覧ください。 - - ### Callback URLを構成する - - Callback URLとは、Auth0がユーザーを認証後にリダイレクトするアプリケーション内URLです。設定されていない場合、ユーザーはログイン後にアプリケーションに戻りません。 - - - サンプルプロジェクトに沿って進めている場合は、`http://localhost:3000/callback`に設定してください。 - - - ### ログアウトURLを構成する - - ログアウトURLとは、Auth0がユーザーをログアウト後にリダイレクトするアプリケーション内URLです。設定されていない場合、ユーザーはアプリケーションからログアウトできず、エラーを受け取ります。 - - - サンプルプロジェクトに沿って進めている場合は、`http://localhost:3000`に設定してください。 - -
    - -
    - プロジェクトディレクトリに`requirements.txt`ファイルを作成します: - - ```txt lines - # 📁 requirements.txt ----- - flask>=2.0.3 - python-dotenv>=0.19.2 - authlib>=1.0 - requests>=2.27.1 - ``` - - シェルから以下のコマンドを実行し、プロジェクトで依存関係が利用できるようにします: - - ```bash lines - pip install -r requirements.txt - ``` - -
    - -
    - 次に、プロジェクトのディレクトリに`.env`ファイルを作成します。このファイルにはクライアントキーやその他の構成情報が含まれます。 - - ```env lines - # 📁 .env ----- - AUTH0_CLIENT_ID=mz9iNEIo2PHu7oeh8QRt19ndTyyCIgai - AUTH0_CLIENT_SECRET=yLTW7npKO4g1HHsCENiZbOaHHXLmhVefJxdNnXcyhOBOomZ2tgjJjSC2pMK7Swvr - AUTH0_DOMAIN=dev-gja8kxz4ndtex3rq.us.auth0.com - APP_SECRET_KEY= - ``` - - - シェルから`openssl rand -hex 32`を使って、`APP_SECRET_KEY`の文字列を生成します。 -
    - -
    - 次に、アプリケーションをセットアップします。プロジェクトディレクトリで`server.py`ファイルを作成します。このファイルにはアプリケーションロジックが含まれます。 - - アプリケーションに必要なすべてのライブラリーをインポートします。 - - 前の手順で作成した構成`.env`ファイルを読み込みます。 - - Auth0でアプリケーションの認証を処理するためにAuthlibを構成します。AuthlibのOAuth `register()`メソッドで使用できる構成オプションの詳細については、[Authlibのドキュメント](https://docs.authlib.org/en/latest/client/frameworks.html#using-oauth-2-0-to-log-in) -
    - -
    - この例では、アプリケーションにlogin、callback、logout、homeの4つのルートを追加します。 - - アプリ訪問者が`/login`ルートにアクセスすると、アプリケーションはユーザーをAuth0ログインページに遷移します。 - - ユーザーがAuth0でログインした後、アプリケーションはユーザーを`/callback`ルートに遷移します。このルートはユーザーのためにセッションを保存し、戻ってきた時に再度ログインする必要性を回避します。 - - `/logout`ルートは、ユーザーをアプリケーションからサインアウトさせます。アプリのユーザーセッションを消去し、Auth0ログアウトエンドポイントにリダイレクトして、セッションがもう保存されていないことを保証します。その後、アプリケーションはユーザーをホームルートにリダイレクトします。 - - `/`ホームルートは認証されたユーザーの詳細を表示したり、訪問者のサインインを許可したりします。 -
    - -
    - 次に、(`render_template()`の呼び出し中に)ホームルートで使用されるテンプレートファイルを作成します。 - - `templates`という名前のプロジェクトフォルダーに新しいサブディレクトリを作成し、ディレクトリに`home.html`を作成します。コンテンツを右から対象ファイルに貼り付けます。 -
    - -
    - アプリケーションを実行するには、プロジェクトディレクトリのルートに移動し、ターミナルを開きます。次のコマンドを実行します: - - ```bash lines - python3 server.py - ``` - - - ##### チェックポイント - - 検証するには[http://localhost:3000](http://localhost:3000/)を訪問します。ログインのためにAuth0へルートするログインボタンがあり、ログイン後アプリケーションに戻るとプロファイル情報を確認できます。 - -
    - - ## 次のステップ - - 成功です!ここまで来れば、アプリケーションにログイン、ログアウト、ユーザープロファイル情報が備わっているはずです。 - - これでクイックスタートチュートリアルは終了ですが、機能はまだまだたくさんあります。Auth0でできることについて詳しくは、以下をご覧ください。 - - * [Auth0 Dashboard](https://manage.auth0.com/#) - Auth0のテナントやアプリケーションを構成して管理する方法について説明します - * [auth0-python SDK](https://github.com/auth0/auth0-python) - このチュートリアルで使用されているSDKをより詳しく説明します - * [Auth0 Marketplace](https://marketplace.auth0.com/) - Auth0の機能性を拡張できる各種の統合を見つけられます -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    +--- +title: "Python Flaskアプリケーションにログインを追加する" +permalink: "interactive" +'description': "このガイドでは、Python FlaskアプリケーションにAuthlib SDKを使ってAuth0を統合する方法を説明します。" +'og:title': "Python Flaskアプリケーションにログインを追加する" +'og:description': "このガイドでは、Python FlaskアプリケーションにAuthlib SDKを使ってAuth0を統合する方法を説明します。" +'og:image': "https://cdn2.auth0.com/docs/1.14567.0/media/platforms/python.png" +'twitter:title': "Python Flaskアプリケーションにログインを追加する" +'twitter:description': "このガイドでは、Python FlaskアプリケーションにAuthlib SDKを使ってAuth0を統合する方法を説明します。" +sidebarTitle: Python +mode: wide +--- + +import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; +import { LoggedInForm } from "/snippets/Login.jsx"; +import Server from "/snippets/quickstart/webapp/python/server.py.mdx"; +import Home from "/snippets/quickstart/webapp/python/home.html.mdx"; + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + +export const sections = [ + { id: "auth0を構成する", title: "Auth0を構成する" }, + { id: "依存関係をインストールする", title: "依存関係をインストールする" }, + { id: "envファイルを構成する", title: ".envファイルを構成する" }, + { id: "アプリケーションをセットアップする", title: "アプリケーションをセットアップする" }, + { id: "ルートをセットアップする", title: "ルートをセットアップする" }, + { id: "テンプレートを追加する", title: "テンプレートを追加する" }, + { id: "アプリケーションを実行する", title: "アプリケーションを実行する" } +] + + + + Auth0を使用すると、アプリケーションに認証を追加して、ユーザープロファイル情報にアクセスすることができます。このガイドでは、Python [Flask](https://flask.palletsprojects.com/)アプリケーションに[Authlib](https://authlib.org/) SDKを使ってAuth0を統合する方法を説明します。 + +
    + Auth0のサービスを利用するには、Auth0 Dashboadでセットアップしたアプリケーションが必要です。Auth0アプリケーションは、開発中のプロジェクトに対してどのように認証が動作して欲しいかを構成する場所です。 + + ### アプリケーションを構成する + + 対話型のセレクターを使ってAuth0アプリケーションを新規作成するか、統合したいプロジェクトを表す既存のアプリケーションを選択します。Auth0のすべてのアプリケーションには英数字からなる一意のクライアントIDが割り当てられており、アプリケーションのコードがSDKを通じてAuth0 + APIを呼び出す際に使用されます。 + + このクイックスタートを使って構成されたすべての設定は、[Dashboard](https://manage.auth0.com/#/)のアプリケーションを自動更新します。今後、アプリケーションの管理もDashboardで行えます。 + + 代わりに完了済みの構成を見てみたい場合は、サンプルアプリケーションをご覧ください。 + + ### Callback URLを構成する + + Callback URLとは、Auth0がユーザーを認証後にリダイレクトするアプリケーション内URLです。設定されていない場合、ユーザーはログイン後にアプリケーションに戻りません。 + + + サンプルプロジェクトに沿って進めている場合は、`http://localhost:3000/callback`に設定してください。 + + + ### ログアウトURLを構成する + + ログアウトURLとは、Auth0がユーザーをログアウト後にリダイレクトするアプリケーション内URLです。設定されていない場合、ユーザーはアプリケーションからログアウトできず、エラーを受け取ります。 + + + サンプルプロジェクトに沿って進めている場合は、`http://localhost:3000`に設定してください。 + +
    + +
    + プロジェクトディレクトリに`requirements.txt`ファイルを作成します: + + ```txt lines + # 📁 requirements.txt ----- + flask>=2.0.3 + python-dotenv>=0.19.2 + authlib>=1.0 + requests>=2.27.1 + ``` + + シェルから以下のコマンドを実行し、プロジェクトで依存関係が利用できるようにします: + + ```bash lines + pip install -r requirements.txt + ``` + +
    + +
    + 次に、プロジェクトのディレクトリに`.env`ファイルを作成します。このファイルにはクライアントキーやその他の構成情報が含まれます。 + + ```env lines + # 📁 .env ----- + AUTH0_CLIENT_ID=mz9iNEIo2PHu7oeh8QRt19ndTyyCIgai + AUTH0_CLIENT_SECRET=yLTW7npKO4g1HHsCENiZbOaHHXLmhVefJxdNnXcyhOBOomZ2tgjJjSC2pMK7Swvr + AUTH0_DOMAIN=dev-gja8kxz4ndtex3rq.us.auth0.com + APP_SECRET_KEY= + ``` + + - シェルから`openssl rand -hex 32`を使って、`APP_SECRET_KEY`の文字列を生成します。 +
    + +
    + 次に、アプリケーションをセットアップします。プロジェクトディレクトリで`server.py`ファイルを作成します。このファイルにはアプリケーションロジックが含まれます。 + + アプリケーションに必要なすべてのライブラリーをインポートします。 + + 前の手順で作成した構成`.env`ファイルを読み込みます。 + + Auth0でアプリケーションの認証を処理するためにAuthlibを構成します。AuthlibのOAuth `register()`メソッドで使用できる構成オプションの詳細については、[Authlibのドキュメント](https://docs.authlib.org/en/latest/client/frameworks.html#using-oauth-2-0-to-log-in) +
    + +
    + この例では、アプリケーションにlogin、callback、logout、homeの4つのルートを追加します。 + + アプリ訪問者が`/login`ルートにアクセスすると、アプリケーションはユーザーをAuth0ログインページに遷移します。 + + ユーザーがAuth0でログインした後、アプリケーションはユーザーを`/callback`ルートに遷移します。このルートはユーザーのためにセッションを保存し、戻ってきた時に再度ログインする必要性を回避します。 + + `/logout`ルートは、ユーザーをアプリケーションからサインアウトさせます。アプリのユーザーセッションを消去し、Auth0ログアウトエンドポイントにリダイレクトして、セッションがもう保存されていないことを保証します。その後、アプリケーションはユーザーをホームルートにリダイレクトします。 + + `/`ホームルートは認証されたユーザーの詳細を表示したり、訪問者のサインインを許可したりします。 +
    + +
    + 次に、(`render_template()`の呼び出し中に)ホームルートで使用されるテンプレートファイルを作成します。 + + `templates`という名前のプロジェクトフォルダーに新しいサブディレクトリを作成し、ディレクトリに`home.html`を作成します。コンテンツを右から対象ファイルに貼り付けます。 +
    + +
    + アプリケーションを実行するには、プロジェクトディレクトリのルートに移動し、ターミナルを開きます。次のコマンドを実行します: + + ```bash lines + python3 server.py + ``` + + + ##### チェックポイント + + 検証するには[http://localhost:3000](http://localhost:3000/)を訪問します。ログインのためにAuth0へルートするログインボタンがあり、ログイン後アプリケーションに戻るとプロファイル情報を確認できます。 + +
    + + ## 次のステップ + + 成功です!ここまで来れば、アプリケーションにログイン、ログアウト、ユーザープロファイル情報が備わっているはずです。 + + これでクイックスタートチュートリアルは終了ですが、機能はまだまだたくさんあります。Auth0でできることについて詳しくは、以下をご覧ください。 + + * [Auth0 Dashboard](https://manage.auth0.com/#) - Auth0のテナントやアプリケーションを構成して管理する方法について説明します + * [auth0-python SDK](https://github.com/auth0/auth0-python) - このチュートリアルで使用されているSDKをより詳しく説明します + * [Auth0 Marketplace](https://marketplace.auth0.com/) - Auth0の機能性を拡張できる各種の統合を見つけられます +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    diff --git a/main/docs/ja-jp/quickstart/webapp/rails/interactive.mdx b/main/docs/ja-jp/quickstart/webapp/rails/interactive.mdx index a0a6418ff..c5e1f9804 100644 --- a/main/docs/ja-jp/quickstart/webapp/rails/interactive.mdx +++ b/main/docs/ja-jp/quickstart/webapp/rails/interactive.mdx @@ -1,269 +1,271 @@ ---- -title: "Ruby on Railsアプリケーションにログインを追加する" -permalink: "interactive" -'description': "このチュートリアルは、Ruby on Railsアプリケーションにユーザーログインを追加する方法について説明します。" -'og:title': "Ruby on Railsアプリケーションにログインを追加する" -'og:description': "このチュートリアルは、Ruby on Railsアプリケーションにユーザーログインを追加する方法について説明します。" -'og:image': "/docs/media/platforms/rails.png" -'twitter:title': "Ruby on Railsアプリケーションにログインを追加する" -'twitter:description': "このチュートリアルは、Ruby on Railsアプリケーションにユーザーログインを追加する方法について説明します。" -sidebarTitle: Ruby on Rails -mode: wide ---- - -import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; -import { LoggedInForm } from "/snippets/Login.jsx"; -import Auth0Yml from "/snippets/quickstart/webapp/rails/auth0.yml.mdx"; -import Auth0 from "/snippets/quickstart/webapp/rails/auth0.rb.mdx"; -import Auth0Controller from "/snippets/quickstart/webapp/rails/auth0_controller.rb.mdx"; -import Routes from "/snippets/quickstart/webapp/rails/routes.rb.mdx"; -import Secured from "/snippets/quickstart/webapp/rails/secured.rb.mdx"; - -export const sections = [ - { id: "auth0を構成する", title: "Auth0を構成する" }, - { id: "依存関係を追加する", title: "依存関係を追加する" }, - { id: "sdkを構成する", title: "SDKを構成する" }, - { id: "omniauthミドルウェアを構成する", title: "OmniAuthミドルウェアを構成する" }, - { id: "auth0コントローラーを追加する", title: "Auth0コントローラーを追加する" }, - { id: "ルートを構成する", title: "ルートを構成する" }, - { id: "アプリケーションにログインを追加する", title: "アプリケーションにログインを追加する" }, - { id: "アプリケーションにログアウトを追加する", title: "アプリケーションにログアウトを追加する" }, - { id: "ユーザープロファイル情報を表示する", title: "ユーザープロファイル情報を表示する" } -] - - - -
    - Auth0のサービスを利用するには、Auth0 Dashboadに設定済みのアプリケーションがある必要があります。Auth0アプリケーションは、開発中のプロジェクトに対してどのように認証が動作して欲しいかを構成する場所です。 - - ### アプリケーションを構成する - - 対話型のセレクターを使ってAuth0アプリケーションを新規作成するか、統合したいプロジェクトを表す既存のアプリケーションを選択します。Auth0のすべてのアプリケーションには英数字からなる一意のクライアントIDが割り当てられており、アプリケーションのコードがSDKを通じてAuth0 - APIを呼び出す際に使用されます。 - - このクイックスタートを使って構成されたすべての設定は、[Dashboard](https://manage.auth0.com/#/)のアプリケーションを自動更新します。今後、アプリケーションの管理もDashboardで行えます。 - - 完了済みの構成を見てみたい場合は、サンプルアプリケーションをご覧ください。 - - ### Callback URLを構成する - - Callback URLとは、Auth0がユーザーを認証後にリダイレクトするアプリケーション内URLです。設定されていない場合、ユーザーはログイン後にアプリケーションに戻りません。 - - - サンプルプロジェクトに沿って進めている場合は、`http://localhost:3000/auth/auth0/callback`に設定してください。 - - - ### ログアウトURLを構成する - - ログアウトURLとは、Auth0がユーザーをログアウト後にリダイレクトするアプリケーション内URLです。設定されていない場合、ユーザーはアプリケーションからログアウトできず、エラーを受け取ります。 - - - サンプルプロジェクトに沿って進めている場合は、`http://localhost:3000`に設定してください。 - - - ### Allowed Web Origins(許可されているWebオリジン)を構成する - - Allowed Web - Origin(許可されているWebオリジン)とは、認証フローへのアクセスを許可されるURLです。これにはプロジェクトのURLが含まれている必要があります。適切に設定されていない場合、プロジェクトが認証トークンを暗黙でリフレッシュできず、ユーザーがアプリケーションを再び訪問した時、またはページを再読み込みした時にログアウトした状態になってしまいます。 - - - サンプルプロジェクトに沿って進めている場合は、`http://localhost:3000`に設定してください。 - -
    - -
    - 認証フローをハンドリングするには、カスタム[OmniAuthストラテジー](https://github.com/intridea/omniauth#omniauth-standardized-multi-provider-authentication)である`omniauth-auth0`を使います。 - - `Gemfile`に次の依存関係を追加します: - - ```gem lines - gem 'omniauth-auth0', '~> 3.0' - gem 'omniauth-rails_csrf_protection', '~> 1.0' # prevents forged authentication requests - ``` - - gemが追加されたら、`bundle install`でインストールします。 -
    - -
    - 構成ファイル`./config/auth0.yml`を作成して、Auth0 - Dashboardにあるアプリケーションの**[Settings(設定)]** で確認できるAuth0ドメイン、クライアントID、クライアントシークレットの値を指定します。 -
    - -
    - `./config/initializers/auth0.rb`という以下のイニシャライザーファイルを作成し、前の手順で作成した構成ファイルで**OmniAuth** ミドルウェアを[構成](https://github.com/auth0/omniauth-auth0/blob/master/EXAMPLES.md#send-additional-authentication-parameters)します。 - - `callback_path`がAuth0アプリケーションの[Allowed Callback URLs(許可されているコールバックURL)]にある値と一致することを確認します。 -
    - -
    - ログアウトURLを構築するために、認証コールバック、`logout`アクション、メソッドをハンドリングするAuth0コントローラーを作成します。 - - 次のコマンドを実行します:`rails generate controller auth0 callback failure logout --skip-assets --skip-helper --skip-routes --skip-template-engine`。 - - コールバックメソッドの内部で、(`request.env['omniauth.auth']`として返された)ユーザー情報のハッシュをアクティブセッションに割り当てます。 - - ログアウトを構築するため、`logout`アクションの内部で`reset_session`メソッドを呼び出し、セッション内に保存されたオブジェクトをすべて消去します。それから、Auth0ログアウトエンドポイントにリダイレクトします。`reset_session`についての詳細は、[「Ruby on Rails ActionController」ドキュメント](http://api.rubyonrails.org/classes/ActionController/Base.html#M000668)をご覧ください。 -
    - -
    - これらのルートを`./config/routes.rb`ファイルに追加します。 - - ルートは所定の位置になければなりません。これにより、RailsはさまざまなAuth0 Callback URLを前の手順で作成したAuth0コントローラーにルートする方法を認識します。 - - - ##### チェックポイント - - アプリケーションを実行して、意図通りに動作し続け、Auth0に関連したエラーを受け取らないことを確認します。 - -
    - -
    - ユーザーが`/auth/auth0`エンドポイントを訪れると、アプリケーションにログインできるようになりました。 - - - [偽の認証要求を防ぐ](https://github.com/cookpad/omniauth-rails_csrf_protection)ためには、`link_to`または`button_to`ヘルパーメソッドを`:post`メソッドと一緒に使います。 - - - ```ruby lines - - <%= button_to 'Login', '/auth/auth0', method: :post %> - ``` - - - ##### チェックポイント - - 選択されるとユーザーを`/auth/auth0`エンドポイントにリダイレクトするボタンを、アプリケーションに追加します。ログインのためAuth0にリダイレクトされ、認証に成功するとアプリに戻されることを確認してください。 - -
    - -
    - Railsアプリケーションにログインできるようになったら、ログアウトする方法が必要です。ユーザーを`auth/logout`アクションにリダイレクトしてログアウトさせると、ユーザーはAuth0ログアウトエンドポイントへリダイレクトされます。 - - - 前の手順の後にこの手順をテストするには、セッションを消去して、ユーザーをAuth0ログアウトエンドポイントへリダイレクトしなければならない可能性があります。 - - - ```ruby lines - - <%= button_to 'Logout', 'auth/logout', method: :get %> - ``` - - - ##### チェックポイント - - 選択されるとユーザーを`/auth/logout`エンドポイントにリダイレクトするボタンを、アプリケーションに追加します。Auth0にリダイレクトされた後即座にアプリケーションに戻り、ログインした状態ではないことを確認します。 - -
    - -
    - ユーザーのプロファイルを表示するには、アプリケーションに保護されたルートがなければなりません。ルートへのアクセスは[Concern](https://guides.rubyonrails.org/getting_started.html#using-concerns)で管理でき、複数のコントローラーで共有できます。Concernはユーザーが認証されていない場合、自動的にAuth0にリダイレクトしなければなりません。そうでない場合は、Concernは現在のユーザープロファイルを返します。 - - Concernができたら、ログインユーザーを必要とするすべてのコントローラーに含めます。その後、次の例のように、`session[:userinfo]`セッションからユーザーにアクセスできます: - - ```ruby lines - class DashboardController < ApplicationController - include Secured - def show - @user = session[:userinfo] - - end - end - ``` - - ユーザーがセッションから読み込まれたら、フロントエンドで情報を表示するために使います: - - ```html lines -
    -

    Normalized User Profile:<%= JSON.pretty_generate(@user[:info])%>

    -

    Full User Profile:<%= JSON.pretty_generate(@user[:extra][:raw_info])%>

    -
    - ``` - - - ##### チェックポイント - - `Secured` concernをアプリに追加してから、認証されたユーザーがアクセスするために必要なコントローラーに含めます。 - 認証されたユーザーがこのコントローラー内でアクションにアクセスでき、認証されていないユーザーは認証のためにAuth0にリダイレクトされることを確認します。 - -
    - - ## 次のステップ - - 成功です!ここまで来れば、アプリケーションにログイン、ログアウト、ユーザープロファイル情報が備わっているはずです。 - - これでクイックスタートチュートリアルは終了ですが、機能はまだまだたくさんあります。Auth0でできることについて詳しくは、以下をご覧ください。 - - * [Auth0 Dashboard](https://manage.auth0.com/#) - Auth0のテナントやアプリケーションを構成して管理する方法について説明します - * [omniauth-auth0 SDK](https://github.com/auth0/omniauth-auth0) - このチュートリアルで使用されているSDKをより詳しく説明します - * [Auth0 Marketplace](https://marketplace.auth0.com/) - Auth0の機能性を拡張できる各種の統合を見つけられます -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    +--- +title: "Ruby on Railsアプリケーションにログインを追加する" +permalink: "interactive" +'description': "このチュートリアルは、Ruby on Railsアプリケーションにユーザーログインを追加する方法について説明します。" +'og:title': "Ruby on Railsアプリケーションにログインを追加する" +'og:description': "このチュートリアルは、Ruby on Railsアプリケーションにユーザーログインを追加する方法について説明します。" +'og:image': "/docs/media/platforms/rails.png" +'twitter:title': "Ruby on Railsアプリケーションにログインを追加する" +'twitter:description': "このチュートリアルは、Ruby on Railsアプリケーションにユーザーログインを追加する方法について説明します。" +sidebarTitle: Ruby on Rails +mode: wide +--- + +import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; +import { LoggedInForm } from "/snippets/Login.jsx"; +import Auth0Yml from "/snippets/quickstart/webapp/rails/auth0.yml.mdx"; +import Auth0 from "/snippets/quickstart/webapp/rails/auth0.rb.mdx"; +import Auth0Controller from "/snippets/quickstart/webapp/rails/auth0_controller.rb.mdx"; +import Routes from "/snippets/quickstart/webapp/rails/routes.rb.mdx"; +import Secured from "/snippets/quickstart/webapp/rails/secured.rb.mdx"; + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + +export const sections = [ + { id: "auth0を構成する", title: "Auth0を構成する" }, + { id: "依存関係を追加する", title: "依存関係を追加する" }, + { id: "sdkを構成する", title: "SDKを構成する" }, + { id: "omniauthミドルウェアを構成する", title: "OmniAuthミドルウェアを構成する" }, + { id: "auth0コントローラーを追加する", title: "Auth0コントローラーを追加する" }, + { id: "ルートを構成する", title: "ルートを構成する" }, + { id: "アプリケーションにログインを追加する", title: "アプリケーションにログインを追加する" }, + { id: "アプリケーションにログアウトを追加する", title: "アプリケーションにログアウトを追加する" }, + { id: "ユーザープロファイル情報を表示する", title: "ユーザープロファイル情報を表示する" } +] + + + +
    + Auth0のサービスを利用するには、Auth0 Dashboadに設定済みのアプリケーションがある必要があります。Auth0アプリケーションは、開発中のプロジェクトに対してどのように認証が動作して欲しいかを構成する場所です。 + + ### アプリケーションを構成する + + 対話型のセレクターを使ってAuth0アプリケーションを新規作成するか、統合したいプロジェクトを表す既存のアプリケーションを選択します。Auth0のすべてのアプリケーションには英数字からなる一意のクライアントIDが割り当てられており、アプリケーションのコードがSDKを通じてAuth0 + APIを呼び出す際に使用されます。 + + このクイックスタートを使って構成されたすべての設定は、[Dashboard](https://manage.auth0.com/#/)のアプリケーションを自動更新します。今後、アプリケーションの管理もDashboardで行えます。 + + 完了済みの構成を見てみたい場合は、サンプルアプリケーションをご覧ください。 + + ### Callback URLを構成する + + Callback URLとは、Auth0がユーザーを認証後にリダイレクトするアプリケーション内URLです。設定されていない場合、ユーザーはログイン後にアプリケーションに戻りません。 + + + サンプルプロジェクトに沿って進めている場合は、`http://localhost:3000/auth/auth0/callback`に設定してください。 + + + ### ログアウトURLを構成する + + ログアウトURLとは、Auth0がユーザーをログアウト後にリダイレクトするアプリケーション内URLです。設定されていない場合、ユーザーはアプリケーションからログアウトできず、エラーを受け取ります。 + + + サンプルプロジェクトに沿って進めている場合は、`http://localhost:3000`に設定してください。 + + + ### Allowed Web Origins(許可されているWebオリジン)を構成する + + Allowed Web + Origin(許可されているWebオリジン)とは、認証フローへのアクセスを許可されるURLです。これにはプロジェクトのURLが含まれている必要があります。適切に設定されていない場合、プロジェクトが認証トークンを暗黙でリフレッシュできず、ユーザーがアプリケーションを再び訪問した時、またはページを再読み込みした時にログアウトした状態になってしまいます。 + + + サンプルプロジェクトに沿って進めている場合は、`http://localhost:3000`に設定してください。 + +
    + +
    + 認証フローをハンドリングするには、カスタム[OmniAuthストラテジー](https://github.com/intridea/omniauth#omniauth-standardized-multi-provider-authentication)である`omniauth-auth0`を使います。 + + `Gemfile`に次の依存関係を追加します: + + ```gem lines + gem 'omniauth-auth0', '~> 3.0' + gem 'omniauth-rails_csrf_protection', '~> 1.0' # prevents forged authentication requests + ``` + + gemが追加されたら、`bundle install`でインストールします。 +
    + +
    + 構成ファイル`./config/auth0.yml`を作成して、Auth0 + Dashboardにあるアプリケーションの**[Settings(設定)]** で確認できるAuth0ドメイン、クライアントID、クライアントシークレットの値を指定します。 +
    + +
    + `./config/initializers/auth0.rb`という以下のイニシャライザーファイルを作成し、前の手順で作成した構成ファイルで**OmniAuth** ミドルウェアを[構成](https://github.com/auth0/omniauth-auth0/blob/master/EXAMPLES.md#send-additional-authentication-parameters)します。 + + `callback_path`がAuth0アプリケーションの[Allowed Callback URLs(許可されているコールバックURL)]にある値と一致することを確認します。 +
    + +
    + ログアウトURLを構築するために、認証コールバック、`logout`アクション、メソッドをハンドリングするAuth0コントローラーを作成します。 + + 次のコマンドを実行します:`rails generate controller auth0 callback failure logout --skip-assets --skip-helper --skip-routes --skip-template-engine`。 + + コールバックメソッドの内部で、(`request.env['omniauth.auth']`として返された)ユーザー情報のハッシュをアクティブセッションに割り当てます。 + + ログアウトを構築するため、`logout`アクションの内部で`reset_session`メソッドを呼び出し、セッション内に保存されたオブジェクトをすべて消去します。それから、Auth0ログアウトエンドポイントにリダイレクトします。`reset_session`についての詳細は、[「Ruby on Rails ActionController」ドキュメント](http://api.rubyonrails.org/classes/ActionController/Base.html#M000668)をご覧ください。 +
    + +
    + これらのルートを`./config/routes.rb`ファイルに追加します。 + + ルートは所定の位置になければなりません。これにより、RailsはさまざまなAuth0 Callback URLを前の手順で作成したAuth0コントローラーにルートする方法を認識します。 + + + ##### チェックポイント + + アプリケーションを実行して、意図通りに動作し続け、Auth0に関連したエラーを受け取らないことを確認します。 + +
    + +
    + ユーザーが`/auth/auth0`エンドポイントを訪れると、アプリケーションにログインできるようになりました。 + + + [偽の認証要求を防ぐ](https://github.com/cookpad/omniauth-rails_csrf_protection)ためには、`link_to`または`button_to`ヘルパーメソッドを`:post`メソッドと一緒に使います。 + + + ```ruby lines + + <%= button_to 'Login', '/auth/auth0', method: :post %> + ``` + + + ##### チェックポイント + + 選択されるとユーザーを`/auth/auth0`エンドポイントにリダイレクトするボタンを、アプリケーションに追加します。ログインのためAuth0にリダイレクトされ、認証に成功するとアプリに戻されることを確認してください。 + +
    + +
    + Railsアプリケーションにログインできるようになったら、ログアウトする方法が必要です。ユーザーを`auth/logout`アクションにリダイレクトしてログアウトさせると、ユーザーはAuth0ログアウトエンドポイントへリダイレクトされます。 + + + 前の手順の後にこの手順をテストするには、セッションを消去して、ユーザーをAuth0ログアウトエンドポイントへリダイレクトしなければならない可能性があります。 + + + ```ruby lines + + <%= button_to 'Logout', 'auth/logout', method: :get %> + ``` + + + ##### チェックポイント + + 選択されるとユーザーを`/auth/logout`エンドポイントにリダイレクトするボタンを、アプリケーションに追加します。Auth0にリダイレクトされた後即座にアプリケーションに戻り、ログインした状態ではないことを確認します。 + +
    + +
    + ユーザーのプロファイルを表示するには、アプリケーションに保護されたルートがなければなりません。ルートへのアクセスは[Concern](https://guides.rubyonrails.org/getting_started.html#using-concerns)で管理でき、複数のコントローラーで共有できます。Concernはユーザーが認証されていない場合、自動的にAuth0にリダイレクトしなければなりません。そうでない場合は、Concernは現在のユーザープロファイルを返します。 + + Concernができたら、ログインユーザーを必要とするすべてのコントローラーに含めます。その後、次の例のように、`session[:userinfo]`セッションからユーザーにアクセスできます: + + ```ruby lines + class DashboardController < ApplicationController + include Secured + def show + @user = session[:userinfo] + + end + end + ``` + + ユーザーがセッションから読み込まれたら、フロントエンドで情報を表示するために使います: + + ```html lines +
    +

    Normalized User Profile:<%= JSON.pretty_generate(@user[:info])%>

    +

    Full User Profile:<%= JSON.pretty_generate(@user[:extra][:raw_info])%>

    +
    + ``` + + + ##### チェックポイント + + `Secured` concernをアプリに追加してから、認証されたユーザーがアクセスするために必要なコントローラーに含めます。 + 認証されたユーザーがこのコントローラー内でアクションにアクセスでき、認証されていないユーザーは認証のためにAuth0にリダイレクトされることを確認します。 + +
    + + ## 次のステップ + + 成功です!ここまで来れば、アプリケーションにログイン、ログアウト、ユーザープロファイル情報が備わっているはずです。 + + これでクイックスタートチュートリアルは終了ですが、機能はまだまだたくさんあります。Auth0でできることについて詳しくは、以下をご覧ください。 + + * [Auth0 Dashboard](https://manage.auth0.com/#) - Auth0のテナントやアプリケーションを構成して管理する方法について説明します + * [omniauth-auth0 SDK](https://github.com/auth0/omniauth-auth0) - このチュートリアルで使用されているSDKをより詳しく説明します + * [Auth0 Marketplace](https://marketplace.auth0.com/) - Auth0の機能性を拡張できる各種の統合を見つけられます +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    diff --git a/main/docs/ja-jp/secure/data-privacy-and-compliance/gdpr/gdpr-conditions-for-consent.mdx b/main/docs/ja-jp/secure/data-privacy-and-compliance/gdpr/gdpr-conditions-for-consent.mdx index 40a0237b4..a6bf39ad9 100644 --- a/main/docs/ja-jp/secure/data-privacy-and-compliance/gdpr/gdpr-conditions-for-consent.mdx +++ b/main/docs/ja-jp/secure/data-privacy-and-compliance/gdpr/gdpr-conditions-for-consent.mdx @@ -10,6 +10,7 @@ permalink: "gdpr-conditions-for-consent" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; GDPRの第7条によると、明確かつ利用しやすい方法で、ユーザーの個人データの処理についてユーザーに同意を求める必要があります。また、ユーザーが同意したことを示さなければならず、いつでも同意を取り消すことができる簡単な方法を提供しなければなりません。 @@ -80,14 +81,20 @@ Management APIにアクセスするには、アクセストークンが必要で 要求例: -export const codeExample1 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/users-by-email?email=USER_EMAIL_ADDRESS&fields=user_metadata' \ ---header 'authorization: Bearer YOUR_MGMT_API_ACCESS_TOKEN'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/users-by-email?email=USER_EMAIL_ADDRESS&fields=user_metadata"); +--header 'authorization: Bearer YOUR_MGMT_API_ACCESS_TOKEN' +``` lines +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users-by-email?email=USER_EMAIL_ADDRESS&fields=user_metadata"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer YOUR_MGMT_API_ACCESS_TOKEN"); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" "net/http" @@ -102,11 +109,15 @@ defer res.Body.Close() body, _ := ioutil.ReadAll(res.Body) fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/users-by-email?email=USER_EMAIL_ADDRESS&fields=user_metadata") +} +``` lines +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/users-by-email?email=USER_EMAIL_ADDRESS&fields=user_metadata") .header("authorization", "Bearer YOUR_MGMT_API_ACCESS_TOKEN") -.asString();`; -export const codeExample5 = `var axios = require("axios").default; +.asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', url: 'https://{yourDomain}/api/v2/users-by-email', @@ -117,8 +128,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` lines +```obj-c Obj-C +#import NSDictionary \*headers = @{ @"authorization": @"Bearer YOUR_MGMT_API_ACCESS_TOKEN" }; NSMutableURLRequest \*request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://{yourDomain}/api/v2/users-by-email?email=USER_EMAIL_ADDRESS&fields=user_metadata"] cachePolicy:NSURLRequestUseProtocolCachePolicy @@ -135,8 +148,10 @@ NSHTTPURLResponse \*httpResponse = (NSHTTPURLResponse \*) response; NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users-by-email?email=USER_EMAIL_ADDRESS&fields=user_metadata", CURLOPT_RETURNTRANSFER => true, @@ -156,15 +171,19 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` lines +```python Python +import http.client conn = http.client.HTTPSConnection("") headers = { 'authorization': "Bearer YOUR_MGMT_API_ACCESS_TOKEN" } conn.request("GET", "/{yourDomain}/api/v2/users-by-email?email=USER_EMAIL_ADDRESS&fields=user_metadata", headers=headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' url = URI("https://{yourDomain}/api/v2/users-by-email?email=USER_EMAIL_ADDRESS&fields=user_metadata") @@ -174,8 +193,10 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer YOUR_MGMT_API_ACCESS_TOKEN' response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` lines +```swift Swift +import Foundation let headers = ["authorization": "Bearer YOUR_MGMT_API_ACCESS_TOKEN"] let request = NSMutableURLRequest(url: NSURL(string: "https://{yourDomain}/api/v2/users-by-email?email=USER_EMAIL_ADDRESS&fields=user_metadata")! as URL, cachePolicy: .useProtocolCachePolicy, @@ -191,20 +212,9 @@ let httpResponse = response as? HTTPURLResponse print(httpResponse) } }) -dataTask.resume()`; - - - lines - - lines - - lines - - lines - - lines - - +dataTask.resume() +``` + 応答例 @@ -231,14 +241,20 @@ IDを使用してユーザーを検索するには、[**Get a User(ユーザ 要求例: -export const codeExample11 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/users/%7ByourUserID%7D?fields=user_metadata' \ ---header 'authorization: Bearer {yourMgmtApiAccessToken}'`; -export const codeExample12 = `var client = new RestClient("https://{yourDomain}/api/v2/users/%7ByourUserID%7D?fields=user_metadata"); +--header 'authorization: Bearer {yourMgmtApiAccessToken}' +``` lines +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users/%7ByourUserID%7D?fields=user_metadata"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer {yourMgmtApiAccessToken}"); -IRestResponse response = client.Execute(request);`; -export const codeExample13 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" "net/http" @@ -253,11 +269,15 @@ defer res.Body.Close() body, _ := ioutil.ReadAll(res.Body) fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample14 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/users/%7ByourUserID%7D?fields=user_metadata") +} +``` lines +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/users/%7ByourUserID%7D?fields=user_metadata") .header("authorization", "Bearer {yourMgmtApiAccessToken}") -.asString();`; -export const codeExample15 = `var axios = require("axios").default; +.asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', url: 'https://{yourDomain}/api/v2/users/%7ByourUserID%7D', @@ -268,8 +288,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample16 = `#import +}); +``` lines +```obj-c Obj-C +#import NSDictionary \*headers = @{ @"authorization": @"Bearer {yourMgmtApiAccessToken}" }; NSMutableURLRequest \*request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://{yourDomain}/api/v2/users/%7ByourUserID%7D?fields=user_metadata"] cachePolicy:NSURLRequestUseProtocolCachePolicy @@ -286,8 +308,10 @@ NSHTTPURLResponse \*httpResponse = (NSHTTPURLResponse \*) response; NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users/%7ByourUserID%7D?fields=user_metadata", CURLOPT_RETURNTRANSFER => true, @@ -307,15 +331,19 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `import http.client +} +``` lines +```python Python +import http.client conn = http.client.HTTPSConnection("") headers = { 'authorization': "Bearer {yourMgmtApiAccessToken}" } conn.request("GET", "/{yourDomain}/api/v2/users/%7ByourUserID%7D?fields=user_metadata", headers=headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' url = URI("https://{yourDomain}/api/v2/users/%7ByourUserID%7D?fields=user_metadata") @@ -325,8 +353,10 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer {yourMgmtApiAccessToken}' response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` lines +```swift Swift +import Foundation let headers = ["authorization": "Bearer {yourMgmtApiAccessToken}"] let request = NSMutableURLRequest(url: NSURL(string: "https://{yourDomain}/api/v2/users/%7ByourUserID%7D?fields=user_metadata")! as URL, cachePolicy: .useProtocolCachePolicy, @@ -342,20 +372,9 @@ let httpResponse = response as? HTTPURLResponse print(httpResponse) } }) -dataTask.resume()`; - - - lines - - lines - - lines - - lines - - lines - - +dataTask.resume() +``` + 応答例 @@ -401,18 +420,24 @@ dataTask.resume()`; ルートレベルのプロパティの更新はマージされるため、更新したいフィールドの値を送信するだけです。たとえば、同意日を追加して、`01/23/2018`に設定したいとします。 -export const codeExample21 = `curl --request PATCH \ + +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/users/USER_ID' \ --header 'authorization: Bearer YOUR_MGMT_API_ACCESS_TOKEN' \ --header 'content-type: application/json' \ ---data '{"user_metadata":{"consentDate":"01/24/2018"}}'`; -export const codeExample22 = `var client = new RestClient("https://{yourDomain}/api/v2/users/USER_ID"); +--data '{"user_metadata":{"consentDate":"01/24/2018"}}' +``` lines +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users/USER_ID"); var request = new RestRequest(Method.PATCH); request.AddHeader("authorization", "Bearer YOUR_MGMT_API_ACCESS_TOKEN"); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\"user_metadata\":{\"consentDate\":\"01/24/2018\"}}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample23 = `package main +request.AddParameter("application/json", "{"user_metadata":{"consentDate":"01/24/2018"}}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" "strings" @@ -421,7 +446,7 @@ import ( ) func main() { url := "https://{yourDomain}/api/v2/users/USER_ID" -payload := strings.NewReader("{\"user_metadata\":{\"consentDate\":\"01/24/2018\"}}") +payload := strings.NewReader("{"user_metadata":{"consentDate":"01/24/2018"}}") req, _ := http.NewRequest("PATCH", url, payload) req.Header.Add("authorization", "Bearer YOUR_MGMT_API_ACCESS_TOKEN") req.Header.Add("content-type", "application/json") @@ -430,13 +455,17 @@ defer res.Body.Close() body, _ := ioutil.ReadAll(res.Body) fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample24 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/users/USER_ID") +} +``` lines +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/users/USER_ID") .header("authorization", "Bearer YOUR_MGMT_API_ACCESS_TOKEN") .header("content-type", "application/json") -.body("{\"user_metadata\":{\"consentDate\":\"01/24/2018\"}}") -.asString();`; -export const codeExample25 = `var axios = require("axios").default; +.body("{"user_metadata":{"consentDate":"01/24/2018"}}") +.asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', url: 'https://{yourDomain}/api/v2/users/USER_ID', @@ -450,8 +479,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample26 = `#import +}); +``` lines +```obj-c Obj-C +#import NSDictionary \*headers = @{ @"authorization": @"Bearer YOUR_MGMT_API_ACCESS_TOKEN", @"content-type": @"application/json" }; NSDictionary \*parameters = @{ @"user_metadata": @{ @"consentDate": @"01/24/2018" } }; @@ -472,8 +503,10 @@ NSHTTPURLResponse \*httpResponse = (NSHTTPURLResponse \*) response; NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample27 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users/USER_ID", CURLOPT_RETURNTRANSFER => true, @@ -482,7 +515,7 @@ CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", -CURLOPT_POSTFIELDS => "{\"user_metadata\":{\"consentDate\":\"01/24/2018\"}}", +CURLOPT_POSTFIELDS => "{"user_metadata":{"consentDate":"01/24/2018"}}", CURLOPT_HTTPHEADER => [ "authorization: Bearer YOUR_MGMT_API_ACCESS_TOKEN", "content-type: application/json" @@ -495,10 +528,12 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample28 = `import http.client +} +``` lines +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"user_metadata\":{\"consentDate\":\"01/24/2018\"}}" +payload = "{"user_metadata":{"consentDate":"01/24/2018"}}" headers = { 'authorization': "Bearer YOUR_MGMT_API_ACCESS_TOKEN", 'content-type': "application/json" @@ -506,8 +541,10 @@ headers = { conn.request("PATCH", "/{yourDomain}/api/v2/users/USER_ID", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample29 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' url = URI("https://{yourDomain}/api/v2/users/USER_ID") @@ -517,10 +554,12 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Patch.new(url) request["authorization"] = 'Bearer YOUR_MGMT_API_ACCESS_TOKEN' request["content-type"] = 'application/json' -request.body = "{\"user_metadata\":{\"consentDate\":\"01/24/2018\"}}" +request.body = "{"user_metadata":{"consentDate":"01/24/2018"}}" response = http.request(request) -puts response.read_body`; -export const codeExample30 = `import Foundation +puts response.read_body +``` lines +```swift Swift +import Foundation let headers = [ "authorization": "Bearer YOUR_MGMT_API_ACCESS_TOKEN", "content-type": "application/json" @@ -542,20 +581,9 @@ let httpResponse = response as? HTTPURLResponse print(httpResponse) } }) -dataTask.resume()`; - - - lines - - lines - - lines - - lines - - lines - - +dataTask.resume() +``` + これにより、ユーザープロファイルに新しいプロパティ**user_metadata.consentDate**が追加され、 顧客が同意した日を保持します。応答は完全なユーザープロファイルです。更新されたメタデータは以下のようになります。 @@ -573,18 +601,24 @@ dataTask.resume()`; 同意日の内部プロパティを追加し、`01/23/2018`に設定しましょう。 -export const codeExample31 = `curl --request PATCH \ + +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/users/USER_ID' \ --header 'authorization: Bearer YOUR_MGMT_API_ACCESS_TOKEN' \ --header 'content-type: application/json' \ ---data '{"user_metadata":{"consent": {"given":true, "date":"01/23/2018", "text_details":"some-url"}}}'`; -export const codeExample32 = `var client = new RestClient("https://{yourDomain}/api/v2/users/USER_ID"); +--data '{"user_metadata":{"consent": {"given":true, "date":"01/23/2018", "text_details":"some-url"}}}' +``` lines +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users/USER_ID"); var request = new RestRequest(Method.PATCH); request.AddHeader("authorization", "Bearer YOUR_MGMT_API_ACCESS_TOKEN"); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\"user_metadata\":{\"consent\": {\"given\":true, \"date\":\"01/23/2018\", \"text_details\":\"some-url\"}}}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample33 = `package main +request.AddParameter("application/json", "{"user_metadata":{"consent": {"given":true, "date":"01/23/2018", "text_details":"some-url"}}}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" "strings" @@ -593,7 +627,7 @@ import ( ) func main() { url := "https://{yourDomain}/api/v2/users/USER_ID" -payload := strings.NewReader("{\"user_metadata\":{\"consent\": {\"given\":true, \"date\":\"01/23/2018\", \"text_details\":\"some-url\"}}}") +payload := strings.NewReader("{"user_metadata":{"consent": {"given":true, "date":"01/23/2018", "text_details":"some-url"}}}") req, _ := http.NewRequest("PATCH", url, payload) req.Header.Add("authorization", "Bearer YOUR_MGMT_API_ACCESS_TOKEN") req.Header.Add("content-type", "application/json") @@ -602,13 +636,17 @@ defer res.Body.Close() body, _ := ioutil.ReadAll(res.Body) fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample34 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/users/USER_ID") +} +``` lines +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/users/USER_ID") .header("authorization", "Bearer YOUR_MGMT_API_ACCESS_TOKEN") .header("content-type", "application/json") -.body("{\"user_metadata\":{\"consent\": {\"given\":true, \"date\":\"01/23/2018\", \"text_details\":\"some-url\"}}}") -.asString();`; -export const codeExample35 = `var axios = require("axios").default; +.body("{"user_metadata":{"consent": {"given":true, "date":"01/23/2018", "text_details":"some-url"}}}") +.asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', url: 'https://{yourDomain}/api/v2/users/USER_ID', @@ -624,8 +662,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample36 = `#import +}); +``` lines +```obj-c Obj-C +#import NSDictionary \*headers = @{ @"authorization": @"Bearer YOUR_MGMT_API_ACCESS_TOKEN", @"content-type": @"application/json" }; NSDictionary \*parameters = @{ @"user_metadata": @{ @"consent": @{ @"given": @YES, @"date": @"01/23/2018", @"text_details": @"some-url" } } }; @@ -646,8 +686,10 @@ NSHTTPURLResponse \*httpResponse = (NSHTTPURLResponse \*) response; NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample37 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users/USER_ID", CURLOPT_RETURNTRANSFER => true, @@ -656,7 +698,7 @@ CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", -CURLOPT_POSTFIELDS => "{\"user_metadata\":{\"consent\": {\"given\":true, \"date\":\"01/23/2018\", \"text_details\":\"some-url\"}}}", +CURLOPT_POSTFIELDS => "{"user_metadata":{"consent": {"given":true, "date":"01/23/2018", "text_details":"some-url"}}}", CURLOPT_HTTPHEADER => [ "authorization: Bearer YOUR_MGMT_API_ACCESS_TOKEN", "content-type: application/json" @@ -669,10 +711,12 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample38 = `import http.client +} +``` lines +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"user_metadata\":{\"consent\": {\"given\":true, \"date\":\"01/23/2018\", \"text_details\":\"some-url\"}}}" +payload = "{"user_metadata":{"consent": {"given":true, "date":"01/23/2018", "text_details":"some-url"}}}" headers = { 'authorization': "Bearer YOUR_MGMT_API_ACCESS_TOKEN", 'content-type': "application/json" @@ -680,8 +724,10 @@ headers = { conn.request("PATCH", "/{yourDomain}/api/v2/users/USER_ID", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample39 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' url = URI("https://{yourDomain}/api/v2/users/USER_ID") @@ -691,10 +737,12 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Patch.new(url) request["authorization"] = 'Bearer YOUR_MGMT_API_ACCESS_TOKEN' request["content-type"] = 'application/json' -request.body = "{\"user_metadata\":{\"consent\": {\"given\":true, \"date\":\"01/23/2018\", \"text_details\":\"some-url\"}}}" +request.body = "{"user_metadata":{"consent": {"given":true, "date":"01/23/2018", "text_details":"some-url"}}}" response = http.request(request) -puts response.read_body`; -export const codeExample40 = `import Foundation +puts response.read_body +``` lines +```swift Swift +import Foundation let headers = [ "authorization": "Bearer YOUR_MGMT_API_ACCESS_TOKEN", "content-type": "application/json" @@ -720,20 +768,9 @@ let httpResponse = response as? HTTPURLResponse print(httpResponse) } }) -dataTask.resume()`; - - - lines - - lines - - lines - - lines - - lines - - +dataTask.resume() +``` + これにより、ユーザープロファイルに新しいプロパティ**user_metadata.consentDate**が追加され、 顧客が同意した日を保持します。応答は完全なユーザープロファイルです。更新されたメタデータは以下のようになります。 @@ -770,14 +807,20 @@ Management APIを使用してユーザーのリストをエクスポートする ユーザーを削除するには、[**Delete a User(ユーザーの削除)**エンドポイント](/docs/api/management/v2#!/Users/delete_users_by_id)を使用します。 -export const codeExample41 = `curl --request DELETE \ + +```bash cURL +curl --request DELETE \ --url 'https://{yourDomain}/api/v2/users/USER_ID' \ ---header 'authorization: Bearer YOUR_MGMT_API_ACCESS_TOKEN'`; -export const codeExample42 = `var client = new RestClient("https://{yourDomain}/api/v2/users/USER_ID"); +--header 'authorization: Bearer YOUR_MGMT_API_ACCESS_TOKEN' +``` lines +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users/USER_ID"); var request = new RestRequest(Method.DELETE); request.AddHeader("authorization", "Bearer YOUR_MGMT_API_ACCESS_TOKEN"); -IRestResponse response = client.Execute(request);`; -export const codeExample43 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" "net/http" @@ -792,11 +835,15 @@ defer res.Body.Close() body, _ := ioutil.ReadAll(res.Body) fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample44 = `HttpResponse response = Unirest.delete("https://{yourDomain}/api/v2/users/USER_ID") +} +``` lines +```java Java +HttpResponse response = Unirest.delete("https://{yourDomain}/api/v2/users/USER_ID") .header("authorization", "Bearer YOUR_MGMT_API_ACCESS_TOKEN") -.asString();`; -export const codeExample45 = `var axios = require("axios").default; +.asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'DELETE', url: 'https://{yourDomain}/api/v2/users/USER_ID', @@ -806,8 +853,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample46 = `#import +}); +``` lines +```obj-c Obj-C +#import NSDictionary \*headers = @{ @"authorization": @"Bearer YOUR_MGMT_API_ACCESS_TOKEN" }; NSMutableURLRequest \*request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://{yourDomain}/api/v2/users/USER_ID"] cachePolicy:NSURLRequestUseProtocolCachePolicy @@ -824,8 +873,10 @@ NSHTTPURLResponse \*httpResponse = (NSHTTPURLResponse \*) response; NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample47 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users/USER_ID", CURLOPT_RETURNTRANSFER => true, @@ -845,15 +896,19 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample48 = `import http.client +} +``` lines +```python Python +import http.client conn = http.client.HTTPSConnection("") headers = { 'authorization': "Bearer YOUR_MGMT_API_ACCESS_TOKEN" } conn.request("DELETE", "/{yourDomain}/api/v2/users/USER_ID", headers=headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample49 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' url = URI("https://{yourDomain}/api/v2/users/USER_ID") @@ -863,8 +918,10 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Delete.new(url) request["authorization"] = 'Bearer YOUR_MGMT_API_ACCESS_TOKEN' response = http.request(request) -puts response.read_body`; -export const codeExample50 = `import Foundation +puts response.read_body +``` lines +```swift Swift +import Foundation let headers = ["authorization": "Bearer YOUR_MGMT_API_ACCESS_TOKEN"] let request = NSMutableURLRequest(url: NSURL(string: "https://{yourDomain}/api/v2/users/USER_ID")! as URL, cachePolicy: .useProtocolCachePolicy, @@ -880,20 +937,9 @@ let httpResponse = response as? HTTPURLResponse print(httpResponse) } }) -dataTask.resume()`; - - - lines - - lines - - lines - - lines - - lines - - +dataTask.resume() +``` + このエンドポイントの応答本文は空白のため、ユーザーが正常に削除されたことを確認したい場合は、メールアドレスを使用してユーザーの取得を試みます。エンドポイントがエラーを返したら、ユーザーの削除が成功したことを意味します。 @@ -909,18 +955,24 @@ dataTask.resume()`; ユーザーのメタデータを更新するには、[**Update a User(ユーザーの更新)**エンドポイント](/docs/api/management/v2#!/Users/patch_users_by_id)を使用します。 -export const codeExample51 = `curl --request PATCH \ + +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/users/USER_ID' \ --header 'authorization: Bearer YOUR_MGMT_API_ACCESS_TOKEN' \ --header 'content-type: application/json' \ ---data '{"app_metadata":{"deleted":true}}'`; -export const codeExample52 = `var client = new RestClient("https://{yourDomain}/api/v2/users/USER_ID"); +--data '{"app_metadata":{"deleted":true}}' +``` lines +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users/USER_ID"); var request = new RestRequest(Method.PATCH); request.AddHeader("authorization", "Bearer YOUR_MGMT_API_ACCESS_TOKEN"); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\"app_metadata\":{\"deleted\":true}}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample53 = `package main +request.AddParameter("application/json", "{"app_metadata":{"deleted":true}}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" "strings" @@ -929,7 +981,7 @@ import ( ) func main() { url := "https://{yourDomain}/api/v2/users/USER_ID" -payload := strings.NewReader("{\"app_metadata\":{\"deleted\":true}}") +payload := strings.NewReader("{"app_metadata":{"deleted":true}}") req, _ := http.NewRequest("PATCH", url, payload) req.Header.Add("authorization", "Bearer YOUR_MGMT_API_ACCESS_TOKEN") req.Header.Add("content-type", "application/json") @@ -938,13 +990,17 @@ defer res.Body.Close() body, _ := ioutil.ReadAll(res.Body) fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample54 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/users/USER_ID") +} +``` lines +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/users/USER_ID") .header("authorization", "Bearer YOUR_MGMT_API_ACCESS_TOKEN") .header("content-type", "application/json") -.body("{\"app_metadata\":{\"deleted\":true}}") -.asString();`; -export const codeExample55 = `var axios = require("axios").default; +.body("{"app_metadata":{"deleted":true}}") +.asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', url: 'https://{yourDomain}/api/v2/users/USER_ID', @@ -958,8 +1014,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample56 = `#import +}); +``` lines +```obj-c Obj-C +#import NSDictionary \*headers = @{ @"authorization": @"Bearer YOUR_MGMT_API_ACCESS_TOKEN", @"content-type": @"application/json" }; NSDictionary \*parameters = @{ @"app_metadata": @{ @"deleted": @YES } }; @@ -980,8 +1038,10 @@ NSHTTPURLResponse \*httpResponse = (NSHTTPURLResponse \*) response; NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample57 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users/USER_ID", CURLOPT_RETURNTRANSFER => true, @@ -990,7 +1050,7 @@ CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", -CURLOPT_POSTFIELDS => "{\"app_metadata\":{\"deleted\":true}}", +CURLOPT_POSTFIELDS => "{"app_metadata":{"deleted":true}}", CURLOPT_HTTPHEADER => [ "authorization: Bearer YOUR_MGMT_API_ACCESS_TOKEN", "content-type: application/json" @@ -1003,10 +1063,12 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample58 = `import http.client +} +``` lines +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"app_metadata\":{\"deleted\":true}}" +payload = "{"app_metadata":{"deleted":true}}" headers = { 'authorization': "Bearer YOUR_MGMT_API_ACCESS_TOKEN", 'content-type': "application/json" @@ -1014,8 +1076,10 @@ headers = { conn.request("PATCH", "/{yourDomain}/api/v2/users/USER_ID", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample59 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' url = URI("https://{yourDomain}/api/v2/users/USER_ID") @@ -1025,10 +1089,12 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Patch.new(url) request["authorization"] = 'Bearer YOUR_MGMT_API_ACCESS_TOKEN' request["content-type"] = 'application/json' -request.body = "{\"app_metadata\":{\"deleted\":true}}" +request.body = "{"app_metadata":{"deleted":true}}" response = http.request(request) -puts response.read_body`; -export const codeExample60 = `import Foundation +puts response.read_body +``` lines +```swift Swift +import Foundation let headers = [ "authorization": "Bearer YOUR_MGMT_API_ACCESS_TOKEN", "content-type": "application/json" @@ -1050,20 +1116,9 @@ let httpResponse = response as? HTTPURLResponse print(httpResponse) } }) -dataTask.resume()`; - - - lines - - lines - - lines - - lines - - lines - - +dataTask.resume() +``` + #### フラグ付けされたユーザーのログインを無効にする diff --git a/main/docs/ja-jp/secure/data-privacy-and-compliance/gdpr/gdpr-track-consent-with-custom-ui.mdx b/main/docs/ja-jp/secure/data-privacy-and-compliance/gdpr/gdpr-track-consent-with-custom-ui.mdx index ab603b8b2..9d4a2ff62 100644 --- a/main/docs/ja-jp/secure/data-privacy-and-compliance/gdpr/gdpr-track-consent-with-custom-ui.mdx +++ b/main/docs/ja-jp/secure/data-privacy-and-compliance/gdpr/gdpr-track-consent-with-custom-ui.mdx @@ -10,6 +10,7 @@ permalink: "gdpr-track-consent-with-custom-ui" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; チュートリアルでは、auth0.jsまたはAuth0 APIを使用して同意情報を要求し、入力内容をユーザーのメタデータに保存する方法を説明します。詳細については、「[ユーザープロファイルでのメタデータの使い方](/docs/ja-jp/manage-users/user-accounts/metadata)」をお読みください。 @@ -121,16 +122,22 @@ Lockを使用して同意を追跡する場合は、[GDPR:Lockで同意を追 これまで説明してきたのと同じシナリオで、新しいユーザーをサインアップすると、次のスニペットを使用してAuth0でユーザーを作成し、メタデータを設定できます。必ず、`consentTimestamp`要求パラメータの値を、ユーザーが同意したときのタイムスタンプに置き換えてください。 -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/dbconnections/signup' \ --header 'content-type: application/json' \ - --data '{"client_id": "{yourClientId}","email": "YOUR_USER_EMAIL","password": "YOUR_USER_PASSWORD","user_metadata": {"consentGiven": "true", "consentTimestamp": "1525101183" }}'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/dbconnections/signup"); + --data '{"client_id": "{yourClientId}","email": "YOUR_USER_EMAIL","password": "YOUR_USER_PASSWORD","user_metadata": {"consentGiven": "true", "consentTimestamp": "1525101183" }}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/dbconnections/signup"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\"client_id\": \"{yourClientId}\",\"email\": \"YOUR_USER_EMAIL\",\"password\": \"YOUR_USER_PASSWORD\",\"user_metadata\": {\"consentGiven\": \"true\", \"consentTimestamp\": \"1525101183\" }}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{"client_id": "{yourClientId}","email": "YOUR_USER_EMAIL","password": "YOUR_USER_PASSWORD","user_metadata": {"consentGiven": "true", "consentTimestamp": "1525101183" }}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -143,7 +150,7 @@ func main() { url := "https://{yourDomain}/dbconnections/signup" - payload := strings.NewReader("{\"client_id\": \"{yourClientId}\",\"email\": \"YOUR_USER_EMAIL\",\"password\": \"YOUR_USER_PASSWORD\",\"user_metadata\": {\"consentGiven\": \"true\", \"consentTimestamp\": \"1525101183\" }}") + payload := strings.NewReader("{"client_id": "{yourClientId}","email": "YOUR_USER_EMAIL","password": "YOUR_USER_PASSWORD","user_metadata": {"consentGiven": "true", "consentTimestamp": "1525101183" }}") req, _ := http.NewRequest("POST", url, payload) @@ -157,12 +164,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/dbconnections/signup") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/dbconnections/signup") .header("content-type", "application/json") - .body("{\"client_id\": \"{yourClientId}\",\"email\": \"YOUR_USER_EMAIL\",\"password\": \"YOUR_USER_PASSWORD\",\"user_metadata\": {\"consentGiven\": \"true\", \"consentTimestamp\": \"1525101183\" }}") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{"client_id": "{yourClientId}","email": "YOUR_USER_EMAIL","password": "YOUR_USER_PASSWORD","user_metadata": {"consentGiven": "true", "consentTimestamp": "1525101183" }}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -180,8 +191,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json" }; NSDictionary *parameters = @{ @"client_id": @"{yourClientId}", @@ -208,8 +221,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/dbconnections/signup", @@ -219,7 +234,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{\"client_id\": \"{yourClientId}\",\"email\": \"YOUR_USER_EMAIL\",\"password\": \"YOUR_USER_PASSWORD\",\"user_metadata\": {\"consentGiven\": \"true\", \"consentTimestamp\": \"1525101183\" }}", + CURLOPT_POSTFIELDS => "{"client_id": "{yourClientId}","email": "YOUR_USER_EMAIL","password": "YOUR_USER_PASSWORD","user_metadata": {"consentGiven": "true", "consentTimestamp": "1525101183" }}", CURLOPT_HTTPHEADER => [ "content-type: application/json" ], @@ -234,12 +249,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"client_id\": \"{yourClientId}\",\"email\": \"YOUR_USER_EMAIL\",\"password\": \"YOUR_USER_PASSWORD\",\"user_metadata\": {\"consentGiven\": \"true\", \"consentTimestamp\": \"1525101183\" }}" +payload = "{"client_id": "{yourClientId}","email": "YOUR_USER_EMAIL","password": "YOUR_USER_PASSWORD","user_metadata": {"consentGiven": "true", "consentTimestamp": "1525101183" }}" headers = { 'content-type': "application/json" } @@ -248,8 +265,10 @@ conn.request("POST", "/{yourDomain}/dbconnections/signup", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -261,11 +280,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["content-type"] = 'application/json' -request.body = "{\"client_id\": \"{yourClientId}\",\"email\": \"YOUR_USER_EMAIL\",\"password\": \"YOUR_USER_PASSWORD\",\"user_metadata\": {\"consentGiven\": \"true\", \"consentTimestamp\": \"1525101183\" }}" +request.body = "{"client_id": "{yourClientId}","email": "YOUR_USER_EMAIL","password": "YOUR_USER_PASSWORD","user_metadata": {"consentGiven": "true", "consentTimestamp": "1525101183" }}" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/json"] let parameters = [ @@ -297,20 +318,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + メタデータの値は、ブール値ではなく文字列を値として受け入れるというAPI制限により、ブール値ではなく、値が`true`の文字列に設定されていることに注意してください。 @@ -330,18 +340,24 @@ Management APIを呼び出す前に、有効なトークンを取得する必要 有効なトークンを取得したら、次のスニペットを使用してユーザーのメタデータを更新します。 -export const codeExample11 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/api/v2/users/%7BUSER_ID%7D' \ --header 'authorization: Bearer YOUR_ACCESS_TOKEN' \ --header 'content-type: application/json' \ - --data '{"user_metadata": {"consentGiven":true, "consentTimestamp": "1525101183"}}'`; -export const codeExample12 = `var client = new RestClient("https://{yourDomain}/api/v2/users/%7BUSER_ID%7D"); + --data '{"user_metadata": {"consentGiven":true, "consentTimestamp": "1525101183"}}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users/%7BUSER_ID%7D"); var request = new RestRequest(Method.POST); request.AddHeader("authorization", "Bearer YOUR_ACCESS_TOKEN"); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\"user_metadata\": {\"consentGiven\":true, \"consentTimestamp\": \"1525101183\"}}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample13 = `package main +request.AddParameter("application/json", "{"user_metadata": {"consentGiven":true, "consentTimestamp": "1525101183"}}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -354,7 +370,7 @@ func main() { url := "https://{yourDomain}/api/v2/users/%7BUSER_ID%7D" - payload := strings.NewReader("{\"user_metadata\": {\"consentGiven\":true, \"consentTimestamp\": \"1525101183\"}}") + payload := strings.NewReader("{"user_metadata": {"consentGiven":true, "consentTimestamp": "1525101183"}}") req, _ := http.NewRequest("POST", url, payload) @@ -369,13 +385,17 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample14 = `HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/users/%7BUSER_ID%7D") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/users/%7BUSER_ID%7D") .header("authorization", "Bearer YOUR_ACCESS_TOKEN") .header("content-type", "application/json") - .body("{\"user_metadata\": {\"consentGiven\":true, \"consentTimestamp\": \"1525101183\"}}") - .asString();`; -export const codeExample15 = `var axios = require("axios").default; + .body("{"user_metadata": {"consentGiven":true, "consentTimestamp": "1525101183"}}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -388,8 +408,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample16 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer YOUR_ACCESS_TOKEN", @"content-type": @"application/json" }; @@ -414,8 +436,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users/%7BUSER_ID%7D", @@ -425,7 +449,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{\"user_metadata\": {\"consentGiven\":true, \"consentTimestamp\": \"1525101183\"}}", + CURLOPT_POSTFIELDS => "{"user_metadata": {"consentGiven":true, "consentTimestamp": "1525101183"}}", CURLOPT_HTTPHEADER => [ "authorization: Bearer YOUR_ACCESS_TOKEN", "content-type: application/json" @@ -441,12 +465,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"user_metadata\": {\"consentGiven\":true, \"consentTimestamp\": \"1525101183\"}}" +payload = "{"user_metadata": {"consentGiven":true, "consentTimestamp": "1525101183"}}" headers = { 'authorization': "Bearer YOUR_ACCESS_TOKEN", @@ -458,8 +484,10 @@ conn.request("POST", "/{yourDomain}/api/v2/users/%7BUSER_ID%7D", payload, header res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -472,11 +500,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["authorization"] = 'Bearer YOUR_ACCESS_TOKEN' request["content-type"] = 'application/json' -request.body = "{\"user_metadata\": {\"consentGiven\":true, \"consentTimestamp\": \"1525101183\"}}" +request.body = "{"user_metadata": {"consentGiven":true, "consentTimestamp": "1525101183"}}" response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "authorization": "Bearer YOUR_ACCESS_TOKEN", @@ -506,20 +536,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + この呼び出しを行うには、一意の`user_id`を知っている必要があることに注意してください。応答からIDトークンを取得した場合、IDトークンの`sub`クレームからこれを取得できます。詳細については、「[IDトークン](/docs/ja-jp/secure/tokens/id-tokens)」をお読みください。または、メールしかない場合は、Management APIの別のエンドポイントを呼び出してIDを取得できます。詳細については、「[ユーザー検索のベストプラクティス](/docs/ja-jp/manage-users/user-search/user-search-best-practices)」をお読みください。 diff --git a/main/docs/ja-jp/secure/mdl-verification/create-mdl-api.mdx b/main/docs/ja-jp/secure/mdl-verification/create-mdl-api.mdx index 809e171e3..88cf05fb7 100644 --- a/main/docs/ja-jp/secure/mdl-verification/create-mdl-api.mdx +++ b/main/docs/ja-jp/secure/mdl-verification/create-mdl-api.mdx @@ -10,6 +10,7 @@ permalink: "create-mdl-api" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; @@ -56,18 +57,24 @@ Once you've been approved to join the EA, you can create the mDL Verification AP 1. Make a `POST` call to the [Create a Resource Server](https://auth0.com/docs/api/management/v2/resource-servers/post-resource-servers) endpoint. -export const codeExample1 = ` curl --request POST \ + +```bash cURL + curl --request POST \ --url 'https://{yourDomain}/api/v2/resource-servers/post-resource-servers' \ --header 'content-type: application/json' \ --data '{"name"}' -`; -export const codeExample2 = ` var client = new RestClient("https://{yourDomain}/api/v2/resource-servers/post-resource-servers"); + +``` +```csharp C# + var client = new RestClient("https://{yourDomain}/api/v2/resource-servers/post-resource-servers"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\"name\"}", ParameterType.RequestBody); +request.AddParameter("application/json", "{"name"}", ParameterType.RequestBody); IRestResponse response = client.Execute(request); -`; -export const codeExample3 = ` package main + +``` +```go Go + package main import ( "fmt" @@ -80,7 +87,7 @@ func main() { url := "https://{yourDomain}/api/v2/resource-servers/post-resource-servers" - payload := strings.NewReader("{\"name\"}") + payload := strings.NewReader("{"name"}") req, _ := http.NewRequest("POST", url, payload) @@ -95,13 +102,17 @@ func main() { fmt.Println(string(body)) } -`; -export const codeExample4 = ` HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/resource-servers/post-resource-servers") + +``` +```java Java + HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/resource-servers/post-resource-servers") .header("content-type", "application/json") - .body("{\"name\"}") + .body("{"name"}") .asString(); -`; -export const codeExample5 = ` var axios = require("axios").default; + +``` +```javascript Node.JS + var axios = require("axios").default; var options = { method: 'POST', @@ -115,8 +126,10 @@ axios.request(options).then(function (response) { }).catch(function (error) { console.error(error); }); -`; -export const codeExample6 = ` #import + +``` +```obj-c Obj-C + #import NSDictionary *headers = @{ @"content-type": @"application/json" }; @@ -140,8 +153,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request } }]; [dataTask resume]; -`; -export const codeExample7 = ` $curl = curl_init(); + +``` +```php PHP + $curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/resource-servers/post-resource-servers", @@ -151,7 +166,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{\"name\"}", + CURLOPT_POSTFIELDS => "{"name"}", CURLOPT_HTTPHEADER => [ "content-type: application/json" ], @@ -167,12 +182,14 @@ if ($err) { } else { echo $response; } -`; -export const codeExample8 = ` import http.client + +``` +```python Python + import http.client conn = http.client.HTTPSConnection("") -payload = "{\"name\"}" +payload = "{"name"}" headers = { 'content-type': "application/json" } @@ -182,12 +199,14 @@ res = conn.getresponse() data = res.read() print(data.decode("utf-8")) -`; -export const codeExample9 = ` import http.client + +``` +```ruby Ruby + import http.client conn = http.client.HTTPSConnection("") -payload = "{\"name\"}" +payload = "{"name"}" headers = { 'content-type': "application/json" } @@ -197,8 +216,10 @@ res = conn.getresponse() data = res.read() print(data.decode("utf-8")) -`; -export const codeExample10 = ` import Foundation + +``` +```swift Swift + import Foundation let headers = ["content-type": "application/json"] @@ -220,20 +241,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: print(httpResponse) } }) -`; - - - - - - - - - - - - - + +``` + 2. Enable the permissions by following instructions for [Management API](https://auth0.com/docs/get-started/apis/add-api-permissions#use-the-management-api). diff --git a/main/docs/ja-jp/secure/multi-factor-authentication/authenticate-using-ropg-flow-with-mfa.mdx b/main/docs/ja-jp/secure/multi-factor-authentication/authenticate-using-ropg-flow-with-mfa.mdx index c984201ea..8402b0b9a 100644 --- a/main/docs/ja-jp/secure/multi-factor-authentication/authenticate-using-ropg-flow-with-mfa.mdx +++ b/main/docs/ja-jp/secure/multi-factor-authentication/authenticate-using-ropg-flow-with-mfa.mdx @@ -10,6 +10,7 @@ permalink: "authenticate-using-ropg-flow-with-mfa" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; MFAが有効な場合、[Auth0のMFA API](/docs/ja-jp/api/authentication#multi-factor-authentication)は[リソース所有者のパスワードフロー](/docs/ja-jp/get-started/authentication-and-authorization-flow/resource-owner-password-flow)(ROPG:リソース所有者パスワード付与とも呼ばれる)を用いた認証フローで利用することができます。 @@ -21,7 +22,9 @@ MFA APIを使用するには、事前にアプリケーションに対してMFA リソース所有者のパスワードフローを用いた認証では、ユーザー名とパスワードを使用して`/oauth/token`エンドポイントを呼び出します。 -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=password \ @@ -30,13 +33,17 @@ export const codeExample1 = `curl --request POST \ --data 'client_id={yourClientId}' \ --data 'client_secret={yourClientSecret}' \ --data audience=https://someapi.com/api \ - --data 'scope=openid profile read:sample'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data 'scope=openid profile read:sample' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=password&username=user%40example.com&password=pwd&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&audience=https%3A%2F%2Fsomeapi.com%2Fapi&scope=openid%20profile%20read%3Asample", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -63,12 +70,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=password&username=user%40example.com&password=pwd&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&audience=https%3A%2F%2Fsomeapi.com%2Fapi&scope=openid%20profile%20read%3Asample") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -89,8 +100,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -119,8 +132,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -145,8 +160,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -159,8 +176,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -175,8 +194,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=password&username=user%40example.com&password=pwd&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&audience=https%3A%2F%2Fsomeapi.com%2Fapi&scope=openid%20profile%20read%3Asample" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -205,20 +226,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + MFAが有効な場合には、`mfa_required`エラーと`mfa_token`が返されます。 @@ -234,16 +244,22 @@ MFAが有効な場合には、`mfa_required`エラーと`mfa_token`が返され ## 登録されているオーセンティケーターを取得する -export const codeExample11 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/mfa/authenticators' \ --header 'authorization: Bearer MFA_TOKEN' \ - --header 'content-type: application/json'`; -export const codeExample12 = `var client = new RestClient("https://{yourDomain}/mfa/authenticators"); + --header 'content-type: application/json' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/mfa/authenticators"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer MFA_TOKEN"); request.AddHeader("content-type", "application/json"); -IRestResponse response = client.Execute(request);`; -export const codeExample13 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -268,12 +284,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample14 = `HttpResponse response = Unirest.get("https://{yourDomain}/mfa/authenticators") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/mfa/authenticators") .header("authorization", "Bearer MFA_TOKEN") .header("content-type", "application/json") - .asString();`; -export const codeExample15 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -285,8 +305,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample16 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MFA_TOKEN", @"content-type": @"application/json" }; @@ -307,8 +329,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/mfa/authenticators", @@ -333,8 +357,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -348,8 +374,10 @@ conn.request("GET", "/{yourDomain}/mfa/authenticators", headers=headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -364,8 +392,10 @@ request["authorization"] = 'Bearer MFA_TOKEN' request["content-type"] = 'application/json' response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "authorization": "Bearer MFA_TOKEN", @@ -388,20 +418,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + 使用可能なオーセンティケーターの配列が取得できます。ユーザーが要素を登録しなかった場合、配列は空になります。 diff --git a/main/docs/ja-jp/secure/multi-factor-authentication/authenticate-using-ropg-flow-with-mfa/challenge-with-recovery-codes.mdx b/main/docs/ja-jp/secure/multi-factor-authentication/authenticate-using-ropg-flow-with-mfa/challenge-with-recovery-codes.mdx index 335a5e93c..c471325dc 100644 --- a/main/docs/ja-jp/secure/multi-factor-authentication/authenticate-using-ropg-flow-with-mfa/challenge-with-recovery-codes.mdx +++ b/main/docs/ja-jp/secure/multi-factor-authentication/authenticate-using-ropg-flow-with-mfa/challenge-with-recovery-codes.mdx @@ -10,6 +10,7 @@ permalink: "challenge-with-recovery-codes" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; テナントに対する[回復コードが有効](/docs/ja-jp/secure/multi-factor-authentication/configure-recovery-codes-for-mfa)になると、Auth0は、ユーザーが多要素認証(MFA)に登録したときに自動的に回復コードを生成します。ユーザーは回復コードを保存する必要があります。このコードは後で、ユーザーがMFAに使用されるデバイスまたはアカウントへのアクセスを失った場合に使用されます。 @@ -45,7 +46,9 @@ MFA APIを使用して回復コードでユーザーが認証できるように
    -export const codeExample1 = ` curl --request POST \ + +```bash cURL + curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=http://auth0.com/oauth/grant-type/mfa-recovery-code \ @@ -53,14 +56,18 @@ export const codeExample1 = ` curl --request POST \ --data 'client_secret={yourClientSecret}' \ --data 'mfa_token={mfaToken}' \ --data 'recovery_code={recoveryCode}' -`; -export const codeExample2 = ` var client = new RestClient("https://{yourDomain}/oauth/token"); + +``` +```csharp C# + var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=http%3A%2F%2Fauth0.com%2Foauth%2Fgrant-type%2Fmfa-recovery-code&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&mfa_token=%7BmfaToken%7D&recovery_code=%7BrecoveryCode%7D", ParameterType.RequestBody); IRestResponse response = client.Execute(request); -`; -export const codeExample3 = ` package main + +``` +```go Go + package main import ( "fmt" @@ -88,13 +95,17 @@ func main() { fmt.Println(string(body)) } -`; -export const codeExample4 = ` HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") + +``` +```java Java + HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=http%3A%2F%2Fauth0.com%2Foauth%2Fgrant-type%2Fmfa-recovery-code&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&mfa_token=%7BmfaToken%7D&recovery_code=%7BrecoveryCode%7D") .asString(); -`; -export const codeExample5 = ` var axios = require("axios").default; + +``` +```javascript Node.JS + var axios = require("axios").default; var options = { method: 'POST', @@ -114,8 +125,10 @@ console.log(response.data); }).catch(function (error) { console.error(error); }); -`; -export const codeExample6 = ` #import + +``` +```obj-c Obj-C + #import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -143,8 +156,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request } }]; [dataTask resume]; -`; -export const codeExample7 = ` $curl = curl_init(); + +``` +```php PHP + $curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -170,8 +185,10 @@ echo "cURL Error #:" . $err; } else { echo $response; } -`; -export const codeExample8 = ` import http.client + +``` +```python Python + import http.client conn = http.client.HTTPSConnection("") @@ -185,8 +202,10 @@ res = conn.getresponse() data = res.read() print(data.decode("utf-8")) -`; -export const codeExample9 = ` require 'uri' + +``` +```ruby Ruby + require 'uri' require 'net/http' require 'openssl' @@ -202,8 +221,10 @@ request.body = "grant_type=http%3A%2F%2Fauth0.com%2Foauth%2Fgrant-type%2Fmfa-rec response = http.request(request) puts response.read_body -`; -export const codeExample10 = ` import Foundation + +``` +```swift Swift + import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -231,20 +252,9 @@ if (error != nil) { }) dataTask.resume() -`; - - - - - - - - - - - - - + +``` + 3. 回復コードを保存するようにユーザーに求めます。呼び出しに成功した場合は、認証トークンと新しい回復コードを受け取ります。 diff --git a/main/docs/ja-jp/secure/multi-factor-authentication/authenticate-using-ropg-flow-with-mfa/enroll-and-challenge-email-authenticators.mdx b/main/docs/ja-jp/secure/multi-factor-authentication/authenticate-using-ropg-flow-with-mfa/enroll-and-challenge-email-authenticators.mdx index ceba873d0..8263f9dbc 100644 --- a/main/docs/ja-jp/secure/multi-factor-authentication/authenticate-using-ropg-flow-with-mfa/enroll-and-challenge-email-authenticators.mdx +++ b/main/docs/ja-jp/secure/multi-factor-authentication/authenticate-using-ropg-flow-with-mfa/enroll-and-challenge-email-authenticators.mdx @@ -10,6 +10,7 @@ permalink: "enroll-and-challenge-email-authenticators" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Auth0は、[ユニバーサルログイン](/docs/ja-jp/authenticate/login/auth0-universal-login)を使用した組み込みのMFA登録と認証フローを提供します。ただし、独自のインターフェイスを作成したい場合は、[MFA API](/docs/ja-jp/secure/multi-factor-authentication/multi-factor-authentication-developer-resources/mfa-api)を使用することもできます。 @@ -66,18 +67,24 @@ MFA APIを使用するには、事前にアプリケーションに対してMFA -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/mfa/associate' \ --header 'authorization: Bearer MFA_TOKEN' \ --header 'content-type: application/json' \ - --data '{ "authenticator_types": ["oob"], "oob_channels": ["email"], "email" : "email@address.com" }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/mfa/associate"); + --data '{ "authenticator_types": ["oob"], "oob_channels": ["email"], "email" : "email@address.com" }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/mfa/associate"); var request = new RestRequest(Method.POST); request.AddHeader("authorization", "Bearer MFA_TOKEN"); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{ \"authenticator_types\": [\"oob\"], \"oob_channels\": [\"email\"], \"email\" : \"email@address.com\" }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "authenticator_types": ["oob"], "oob_channels": ["email"], "email" : "email@address.com" }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -90,7 +97,7 @@ func main() { url := "https://{yourDomain}/mfa/associate" - payload := strings.NewReader("{ \"authenticator_types\": [\"oob\"], \"oob_channels\": [\"email\"], \"email\" : \"email@address.com\" }") + payload := strings.NewReader("{ "authenticator_types": ["oob"], "oob_channels": ["email"], "email" : "email@address.com" }") req, _ := http.NewRequest("POST", url, payload) @@ -105,13 +112,17 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/mfa/associate") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/mfa/associate") .header("authorization", "Bearer MFA_TOKEN") .header("content-type", "application/json") - .body("{ \"authenticator_types\": [\"oob\"], \"oob_channels\": [\"email\"], \"email\" : \"email@address.com\" }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "authenticator_types": ["oob"], "oob_channels": ["email"], "email" : "email@address.com" }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -128,8 +139,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MFA_TOKEN", @"content-type": @"application/json" }; @@ -156,8 +169,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/mfa/associate", @@ -167,7 +182,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{ \"authenticator_types\": [\"oob\"], \"oob_channels\": [\"email\"], \"email\" : \"email@address.com\" }", + CURLOPT_POSTFIELDS => "{ "authenticator_types": ["oob"], "oob_channels": ["email"], "email" : "email@address.com" }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MFA_TOKEN", "content-type: application/json" @@ -183,12 +198,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"authenticator_types\": [\"oob\"], \"oob_channels\": [\"email\"], \"email\" : \"email@address.com\" }" +payload = "{ "authenticator_types": ["oob"], "oob_channels": ["email"], "email" : "email@address.com" }" headers = { 'authorization': "Bearer MFA_TOKEN", @@ -200,8 +217,10 @@ conn.request("POST", "/{yourDomain}/mfa/associate", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -214,11 +233,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["authorization"] = 'Bearer MFA_TOKEN' request["content-type"] = 'application/json' -request.body = "{ \"authenticator_types\": [\"oob\"], \"oob_channels\": [\"email\"], \"email\" : \"email@address.com\" }" +request.body = "{ "authenticator_types": ["oob"], "oob_channels": ["email"], "email" : "email@address.com" }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "authorization": "Bearer MFA_TOKEN", @@ -249,20 +270,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + 成功すると、次のような応答を受け取ります: @@ -286,19 +296,25 @@ dataTask.resume()`; 登録を完了するには、[**`/oath/token`** ](https://auth0.com/docs/api/authentication#get-token)エンドポイントに`POST`要求を行います。メールに記載された値とともに、前の応答で返された`oob_code`と`binding_code`を入れます。 -export const codeExample11 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --data grant_type=http://auth0.com/oauth/grant-type/mfa-oob \ --data 'mfa_token={mfaToken}' \ --data 'oob_code={oobCode}' \ --data 'binding_code={userEmailOtpCode}' \ --data 'client_id={yourClientId}' \ - --data 'client_secret={yourClientSecret}'`; -export const codeExample12 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data 'client_secret={yourClientSecret}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddParameter("undefined", "grant_type=http%3A%2F%2Fauth0.com%2Foauth%2Fgrant-type%2Fmfa-oob&mfa_token=%7BmfaToken%7D&oob_code=%7BoobCode%7D&binding_code=%7BuserEmailOtpCode%7D&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample13 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -323,11 +339,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample14 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .body("grant_type=http%3A%2F%2Fauth0.com%2Foauth%2Fgrant-type%2Fmfa-oob&mfa_token=%7BmfaToken%7D&oob_code=%7BoobCode%7D&binding_code=%7BuserEmailOtpCode%7D&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D") - .asString();`; -export const codeExample15 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -346,8 +366,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample16 = `#import +}); +``` +```obj-c Obj-C +#import NSMutableData *postData = [[NSMutableData alloc] initWithData:[@"grant_type=http://auth0.com/oauth/grant-type/mfa-oob" dataUsingEncoding:NSUTF8StringEncoding]]; [postData appendData:[@"&mfa_token={mfaToken}" dataUsingEncoding:NSUTF8StringEncoding]]; @@ -372,8 +394,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -395,8 +419,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -407,8 +433,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -422,8 +450,10 @@ request = Net::HTTP::Post.new(url) request.body = "grant_type=http%3A%2F%2Fauth0.com%2Foauth%2Fgrant-type%2Fmfa-oob&mfa_token=%7BmfaToken%7D&oob_code=%7BoobCode%7D&binding_code=%7BuserEmailOtpCode%7D&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D" response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let postData = NSMutableData(data: "grant_type=http://auth0.com/oauth/grant-type/mfa-oob".data(using: String.Encoding.utf8)!) postData.append("&mfa_token={mfaToken}".data(using: String.Encoding.utf8)!) @@ -448,20 +478,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + 呼び出しが成功すると、アクセストークンを含む応答が以下のフォーマットで返されます。 @@ -491,16 +510,22 @@ MFA Authenticatorエンドポイントを呼び出すことで、Authenticator ユーザーにチャレンジするには、チャレンジしたい要素の`authenticator_id`が必要です。登録された全Authenticatorの一覧は、MFA Authenticatorエンドポイントを使って表示できます: -export const codeExample21 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/mfa/authenticators' \ --header 'authorization: Bearer MFA_TOKEN' \ - --header 'content-type: application/json'`; -export const codeExample22 = `var client = new RestClient("https://{yourDomain}/mfa/authenticators"); + --header 'content-type: application/json' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/mfa/authenticators"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer MFA_TOKEN"); request.AddHeader("content-type", "application/json"); -IRestResponse response = client.Execute(request);`; -export const codeExample23 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -525,12 +550,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample24 = `HttpResponse response = Unirest.get("https://{yourDomain}/mfa/authenticators") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/mfa/authenticators") .header("authorization", "Bearer MFA_TOKEN") .header("content-type", "application/json") - .asString();`; -export const codeExample25 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -542,8 +571,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample26 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MFA_TOKEN", @"content-type": @"application/json" }; @@ -564,8 +595,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample27 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/mfa/authenticators", @@ -590,8 +623,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample28 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -605,8 +640,10 @@ conn.request("GET", "/{yourDomain}/mfa/authenticators", headers=headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample29 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -621,8 +658,10 @@ request["authorization"] = 'Bearer MFA_TOKEN' request["content-type"] = 'application/json' response = http.request(request) -puts response.read_body`; -export const codeExample30 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "authorization": "Bearer MFA_TOKEN", @@ -645,33 +684,28 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ### OTPを使ってユーザーにチャレンジする メールチャレンジをトリガーするには、対応する`authenticator_id`と`mfa_token`を使ってMFAチャレンジエンドポイントへ`POST`を送ります。 -export const codeExample31 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/mfa/challenge' \ - --data '{ "client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "challenge_type": "oob", "authenticator_id": "email|dev_NU1Ofuw3Cw0XCt5x", "mfa_token": "{mfaToken}" }'`; -export const codeExample32 = `var client = new RestClient("https://{yourDomain}/mfa/challenge"); + --data '{ "client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "challenge_type": "oob", "authenticator_id": "email|dev_NU1Ofuw3Cw0XCt5x", "mfa_token": "{mfaToken}" }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/mfa/challenge"); var request = new RestRequest(Method.POST); -request.AddParameter("undefined", "{ \"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"challenge_type\": \"oob\", \"authenticator_id\": \"email|dev_NU1Ofuw3Cw0XCt5x\", \"mfa_token\": \"{mfaToken}\" }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample33 = `package main +request.AddParameter("undefined", "{ "client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "challenge_type": "oob", "authenticator_id": "email|dev_NU1Ofuw3Cw0XCt5x", "mfa_token": "{mfaToken}" }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -684,7 +718,7 @@ func main() { url := "https://{yourDomain}/mfa/challenge" - payload := strings.NewReader("{ \"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"challenge_type\": \"oob\", \"authenticator_id\": \"email|dev_NU1Ofuw3Cw0XCt5x\", \"mfa_token\": \"{mfaToken}\" }") + payload := strings.NewReader("{ "client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "challenge_type": "oob", "authenticator_id": "email|dev_NU1Ofuw3Cw0XCt5x", "mfa_token": "{mfaToken}" }") req, _ := http.NewRequest("POST", url, payload) @@ -696,11 +730,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample34 = `HttpResponse response = Unirest.post("https://{yourDomain}/mfa/challenge") - .body("{ \"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"challenge_type\": \"oob\", \"authenticator_id\": \"email|dev_NU1Ofuw3Cw0XCt5x\", \"mfa_token\": \"{mfaToken}\" }") - .asString();`; -export const codeExample35 = `var axios = require("axios").default; +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/mfa/challenge") + .body("{ "client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "challenge_type": "oob", "authenticator_id": "email|dev_NU1Ofuw3Cw0XCt5x", "mfa_token": "{mfaToken}" }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -718,8 +756,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample36 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *parameters = @{ @"client_id": @"{yourClientId}", @"client_secret": @"{yourClientSecret}", @"challenge_type": @"oob", @@ -744,8 +784,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample37 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/mfa/challenge", @@ -755,7 +797,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{ \"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"challenge_type\": \"oob\", \"authenticator_id\": \"email|dev_NU1Ofuw3Cw0XCt5x\", \"mfa_token\": \"{mfaToken}\" }", + CURLOPT_POSTFIELDS => "{ "client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "challenge_type": "oob", "authenticator_id": "email|dev_NU1Ofuw3Cw0XCt5x", "mfa_token": "{mfaToken}" }", ]); $response = curl_exec($curl); @@ -767,20 +809,24 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample38 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"challenge_type\": \"oob\", \"authenticator_id\": \"email|dev_NU1Ofuw3Cw0XCt5x\", \"mfa_token\": \"{mfaToken}\" }" +payload = "{ "client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "challenge_type": "oob", "authenticator_id": "email|dev_NU1Ofuw3Cw0XCt5x", "mfa_token": "{mfaToken}" }" conn.request("POST", "/{yourDomain}/mfa/challenge", payload) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample39 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -791,11 +837,13 @@ http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) -request.body = "{ \"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"challenge_type\": \"oob\", \"authenticator_id\": \"email|dev_NU1Ofuw3Cw0XCt5x\", \"mfa_token\": \"{mfaToken}\" }" +request.body = "{ "client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "challenge_type": "oob", "authenticator_id": "email|dev_NU1Ofuw3Cw0XCt5x", "mfa_token": "{mfaToken}" }" response = http.request(request) -puts response.read_body`; -export const codeExample40 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let parameters = [ "client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", @@ -822,20 +870,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ### 受信したコードを使って認証を完了します。 @@ -851,7 +888,9 @@ dataTask.resume()`; アプリケーションがユーザーに対してコード入力画面を表示し、`oauth``/token`エンドポイントへの以下の呼び出しの中で`binding_code`パラメーターの要求の一部として送信します。 -export const codeExample41 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=http://auth0.com/oauth/grant-type/mfa-oob \ @@ -859,13 +898,17 @@ export const codeExample41 = `curl --request POST \ --data 'client_secret={yourClientSecret}' \ --data 'mfa_token={mfaToken}' \ --data 'oob_code={oobCode}' \ - --data 'binding_code={userEmailOtpCode}'`; -export const codeExample42 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data 'binding_code={userEmailOtpCode}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=http%3A%2F%2Fauth0.com%2Foauth%2Fgrant-type%2Fmfa-oob&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&mfa_token=%7BmfaToken%7D&oob_code=%7BoobCode%7D&binding_code=%7BuserEmailOtpCode%7D", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample43 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -892,12 +935,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample44 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=http%3A%2F%2Fauth0.com%2Foauth%2Fgrant-type%2Fmfa-oob&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&mfa_token=%7BmfaToken%7D&oob_code=%7BoobCode%7D&binding_code=%7BuserEmailOtpCode%7D") - .asString();`; -export const codeExample45 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -917,8 +964,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample46 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -946,8 +995,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample47 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -972,8 +1023,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample48 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -986,8 +1039,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample49 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -1002,8 +1057,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=http%3A%2F%2Fauth0.com%2Foauth%2Fgrant-type%2Fmfa-oob&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&mfa_token=%7BmfaToken%7D&oob_code=%7BoobCode%7D&binding_code=%7BuserEmailOtpCode%7D" response = http.request(request) -puts response.read_body`; -export const codeExample50 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -1031,20 +1088,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + 呼び出しが成功すると、アクセストークンを含む応答が以下のフォーマットで返されます: diff --git a/main/docs/ja-jp/secure/multi-factor-authentication/authenticate-using-ropg-flow-with-mfa/enroll-and-challenge-otp-authenticators.mdx b/main/docs/ja-jp/secure/multi-factor-authentication/authenticate-using-ropg-flow-with-mfa/enroll-and-challenge-otp-authenticators.mdx index f4d93761c..8cba6fbaa 100644 --- a/main/docs/ja-jp/secure/multi-factor-authentication/authenticate-using-ropg-flow-with-mfa/enroll-and-challenge-otp-authenticators.mdx +++ b/main/docs/ja-jp/secure/multi-factor-authentication/authenticate-using-ropg-flow-with-mfa/enroll-and-challenge-otp-authenticators.mdx @@ -10,6 +10,7 @@ permalink: "enroll-and-challenge-otp-authenticators" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Auth0は、[ユニバーサルログイン](/docs/ja-jp/authenticate/login/auth0-universal-login)を使用した組み込みのMFA登録と認証フローを提供します。ただし、独自のインターフェイスを作成したい場合は、[MFA API](/docs/ja-jp/secure/multi-factor-authentication/multi-factor-authentication-developer-resources/mfa-api)を使用することもできます。 @@ -34,18 +35,24 @@ MFA APIを使用するには、事前にアプリケーションに対してMFA OTPで登録するには、`authenticator_types`パラメーターを`[otp]`に設定します。 -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/mfa/associate' \ --header 'authorization: Bearer MFA_TOKEN' \ --header 'content-type: application/json' \ - --data '{ "authenticator_types": ["otp"] }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/mfa/associate"); + --data '{ "authenticator_types": ["otp"] }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/mfa/associate"); var request = new RestRequest(Method.POST); request.AddHeader("authorization", "Bearer MFA_TOKEN"); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{ \"authenticator_types\": [\"otp\"] }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "authenticator_types": ["otp"] }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -58,7 +65,7 @@ func main() { url := "https://{yourDomain}/mfa/associate" - payload := strings.NewReader("{ \"authenticator_types\": [\"otp\"] }") + payload := strings.NewReader("{ "authenticator_types": ["otp"] }") req, _ := http.NewRequest("POST", url, payload) @@ -73,13 +80,17 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/mfa/associate") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/mfa/associate") .header("authorization", "Bearer MFA_TOKEN") .header("content-type", "application/json") - .body("{ \"authenticator_types\": [\"otp\"] }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "authenticator_types": ["otp"] }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -92,8 +103,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MFA_TOKEN", @"content-type": @"application/json" }; @@ -118,8 +131,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/mfa/associate", @@ -129,7 +144,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{ \"authenticator_types\": [\"otp\"] }", + CURLOPT_POSTFIELDS => "{ "authenticator_types": ["otp"] }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MFA_TOKEN", "content-type: application/json" @@ -146,12 +161,14 @@ if ($err) { } else { echo $response; } -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"authenticator_types\": [\"otp\"] }" +payload = "{ "authenticator_types": ["otp"] }" headers = { 'authorization': "Bearer MFA_TOKEN", @@ -163,8 +180,10 @@ conn.request("POST", "/{yourDomain}/mfa/associate", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -177,11 +196,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["authorization"] = 'Bearer MFA_TOKEN' request["content-type"] = 'application/json' -request.body = "{ \"authenticator_types\": [\"otp\"] }" +request.body = "{ "authenticator_types": ["otp"] }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "authorization": "Bearer MFA_TOKEN", @@ -208,20 +229,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + 成功すると、次のような応答を受け取ります: @@ -244,20 +254,26 @@ dataTask.resume()`; ユーザーがシークレットを入力したら、OTPアプリケーションが6桁のコードを表示し、これをユーザーがアプリケーションに入力します。そうすると、アプリケーションは`POST`要求をOAuthトークンエンドポイントに対して実行し、これに`otp`値を含めます。 -export const codeExample11 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=http://auth0.com/oauth/grant-type/mfa-otp \ --data 'client_id={yourClientId}' \ --data 'mfa_token={mfaToken}' \ --data 'client_secret={yourClientSecret}' \ - --data 'otp={userOtpCode}'`; -export const codeExample12 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data 'otp={userOtpCode}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=http%3A%2F%2Fauth0.com%2Foauth%2Fgrant-type%2Fmfa-otp&client_id={yourClientId}&mfa_token=%7BmfaToken%7D&client_secret=%7ByourClientSecret%7D&otp=%7BuserOtpCode%7D", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample13 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -284,12 +300,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample14 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=http%3A%2F%2Fauth0.com%2Foauth%2Fgrant-type%2Fmfa-otp&client_id={yourClientId}&mfa_token=%7BmfaToken%7D&client_secret=%7ByourClientSecret%7D&otp=%7BuserOtpCode%7D") - .asString();`; -export const codeExample15 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -308,8 +328,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample16 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -336,8 +358,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -362,8 +386,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -376,8 +402,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -392,8 +420,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=http%3A%2F%2Fauth0.com%2Foauth%2Fgrant-type%2Fmfa-otp&client_id={yourClientId}&mfa_token=%7BmfaToken%7D&client_secret=%7ByourClientSecret%7D&otp=%7BuserOtpCode%7D" response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -420,20 +450,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + 呼び出しが成功すると、アクセストークンを含む応答が以下のフォーマットで返されます。 @@ -461,16 +480,22 @@ MFA Authenticatorエンドポイントを呼び出すことで、Authenticator 登録された全Authenticatorの一覧は、MFA Authenticatorエンドポイントを使って表示できます: -export const codeExample21 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/mfa/authenticators' \ --header 'authorization: Bearer MFA_TOKEN' \ - --header 'content-type: application/json'`; -export const codeExample22 = `var client = new RestClient("https://{yourDomain}/mfa/authenticators"); + --header 'content-type: application/json' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/mfa/authenticators"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer MFA_TOKEN"); request.AddHeader("content-type", "application/json"); -IRestResponse response = client.Execute(request);`; -export const codeExample23 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -495,12 +520,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample24 = `HttpResponse response = Unirest.get("https://{yourDomain}/mfa/authenticators") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/mfa/authenticators") .header("authorization", "Bearer MFA_TOKEN") .header("content-type", "application/json") - .asString();`; -export const codeExample25 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -512,8 +541,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample26 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MFA_TOKEN", @"content-type": @"application/json" }; @@ -534,8 +565,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample27 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/mfa/authenticators", @@ -560,8 +593,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample28 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -575,8 +610,10 @@ conn.request("GET", "/{yourDomain}/mfa/authenticators", headers=headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample29 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -591,8 +628,10 @@ request["authorization"] = 'Bearer MFA_TOKEN' request["content-type"] = 'application/json' response = http.request(request) -puts response.read_body`; -export const codeExample30 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "authorization": "Bearer MFA_TOKEN", @@ -615,20 +654,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + 以下の形式でAuthenticatorのリストを取得できます。 @@ -653,20 +681,26 @@ dataTask.resume()`; OAuth0トークンエンドポイントを使用して、`otp`パラメーターにワンタイムパスワードを指定し、コードを検証して認証トークンを取得します。 -export const codeExample31 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=http://auth0.com/oauth/grant-type/mfa-otp \ --data 'client_id={yourClientId}' \ --data 'client_secret={yourClientSecret}' \ --data 'mfa_token={mfaToken}' \ - --data 'otp={userOtpCode}'`; -export const codeExample32 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data 'otp={userOtpCode}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=http%3A%2F%2Fauth0.com%2Foauth%2Fgrant-type%2Fmfa-otp&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&mfa_token=%7BmfaToken%7D&otp=%7BuserOtpCode%7D", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample33 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -693,12 +727,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample34 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=http%3A%2F%2Fauth0.com%2Foauth%2Fgrant-type%2Fmfa-otp&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&mfa_token=%7BmfaToken%7D&otp=%7BuserOtpCode%7D") - .asString();`; -export const codeExample35 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -717,8 +755,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample36 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -745,8 +785,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample37 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -771,8 +813,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample38 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -785,8 +829,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample39 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -801,8 +847,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=http%3A%2F%2Fauth0.com%2Foauth%2Fgrant-type%2Fmfa-otp&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&mfa_token=%7BmfaToken%7D&otp=%7BuserOtpCode%7D" response = http.request(request) -puts response.read_body`; -export const codeExample40 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -829,20 +877,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + 呼び出しが成功すると、アクセストークンを含む応答が以下のフォーマットで返されます: diff --git a/main/docs/ja-jp/secure/multi-factor-authentication/authenticate-using-ropg-flow-with-mfa/enroll-and-challenge-push-authenticators.mdx b/main/docs/ja-jp/secure/multi-factor-authentication/authenticate-using-ropg-flow-with-mfa/enroll-and-challenge-push-authenticators.mdx index 628835765..d82694df0 100644 --- a/main/docs/ja-jp/secure/multi-factor-authentication/authenticate-using-ropg-flow-with-mfa/enroll-and-challenge-push-authenticators.mdx +++ b/main/docs/ja-jp/secure/multi-factor-authentication/authenticate-using-ropg-flow-with-mfa/enroll-and-challenge-push-authenticators.mdx @@ -10,6 +10,7 @@ permalink: "enroll-and-challenge-push-authenticators" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Auth0は、[ユニバーサルログイン](/docs/ja-jp/authenticate/login/auth0-universal-login)を使用した組み込みのMFA登録と認証フローを提供します。ただし、独自のインターフェイスを作成したい場合は、[MFA API](/docs/ja-jp/secure/multi-factor-authentication/multi-factor-authentication-developer-resources/mfa-api)を使用することもできます。 @@ -36,18 +37,24 @@ MFA APIを使用するには、事前にアプリケーションに対してMFA プッシュで登録するには、`authenticator_types`パラメーターを`[oob]`、`oob_channels`パラメーターを`[auth0]`に設定します。 -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/mfa/associate' \ --header 'authorization: Bearer MFA_TOKEN' \ --header 'content-type: application/json' \ - --data '{ "authenticator_types": ["oob"], "oob_channels": ["auth0"] }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/mfa/associate"); + --data '{ "authenticator_types": ["oob"], "oob_channels": ["auth0"] }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/mfa/associate"); var request = new RestRequest(Method.POST); request.AddHeader("authorization", "Bearer MFA_TOKEN"); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{ \"authenticator_types\": [\"oob\"], \"oob_channels\": [\"auth0\"] }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "authenticator_types": ["oob"], "oob_channels": ["auth0"] }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -60,7 +67,7 @@ func main() { url := "https://{yourDomain}/mfa/associate" - payload := strings.NewReader("{ \"authenticator_types\": [\"oob\"], \"oob_channels\": [\"auth0\"] }") + payload := strings.NewReader("{ "authenticator_types": ["oob"], "oob_channels": ["auth0"] }") req, _ := http.NewRequest("POST", url, payload) @@ -75,13 +82,17 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/mfa/associate") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/mfa/associate") .header("authorization", "Bearer MFA_TOKEN") .header("content-type", "application/json") - .body("{ \"authenticator_types\": [\"oob\"], \"oob_channels\": [\"auth0\"] }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "authenticator_types": ["oob"], "oob_channels": ["auth0"] }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -94,8 +105,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MFA_TOKEN", @"content-type": @"application/json" }; @@ -121,8 +134,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/mfa/associate", @@ -132,7 +147,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{ \"authenticator_types\": [\"oob\"], \"oob_channels\": [\"auth0\"] }", + CURLOPT_POSTFIELDS => "{ "authenticator_types": ["oob"], "oob_channels": ["auth0"] }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MFA_TOKEN", "content-type: application/json" @@ -148,12 +163,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"authenticator_types\": [\"oob\"], \"oob_channels\": [\"auth0\"] }" +payload = "{ "authenticator_types": ["oob"], "oob_channels": ["auth0"] }" headers = { 'authorization': "Bearer MFA_TOKEN", @@ -165,8 +182,10 @@ conn.request("POST", "/{yourDomain}/mfa/associate", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -179,11 +198,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["authorization"] = 'Bearer MFA_TOKEN' request["content-type"] = 'application/json' -request.body = "{ \"authenticator_types\": [\"oob\"], \"oob_channels\": [\"auth0\"] }" +request.body = "{ "authenticator_types": ["oob"], "oob_channels": ["auth0"] }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "authorization": "Bearer MFA_TOKEN", @@ -213,20 +234,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + 成功すると、次のような応答を受け取ります: @@ -252,7 +262,9 @@ dataTask.resume()`; 完了すると、ユーザーが正常に登録されたことをGuardianアプリケーションがAuth0に通知します。スキャンされたかを知るためには、MFA Associateエンドポイントの呼び出しで返された`oob_code`を使用して、Auth0トークンエンドポイントをポーリングします。 -export const codeExample11 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'authorization: Bearer {mfaToken}' \ --header 'content-type: application/x-www-form-urlencoded' \ @@ -260,14 +272,18 @@ export const codeExample11 = `curl --request POST \ --data 'client_id={yourClientId}' \ --data 'client_secret={yourClientSecret}' \ --data 'mfa_token={mfaToken}' \ - --data 'oob_code={oobCode}'`; -export const codeExample12 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data 'oob_code={oobCode}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("authorization", "Bearer {mfaToken}"); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=http%3A%2F%2Fauth0.com%2Foauth%2Fgrant-type%2Fmfa-oob&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&mfa_token=%7BmfaToken%7D&oob_code=%7BoobCode%7D", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample13 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -295,13 +311,17 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample14 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("authorization", "Bearer {mfaToken}") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=http%3A%2F%2Fauth0.com%2Foauth%2Fgrant-type%2Fmfa-oob&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&mfa_token=%7BmfaToken%7D&oob_code=%7BoobCode%7D") - .asString();`; -export const codeExample15 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -323,8 +343,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample16 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer {mfaToken}", @"content-type": @"application/x-www-form-urlencoded" }; @@ -352,8 +374,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -379,8 +403,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -396,8 +422,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -413,8 +441,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=http%3A%2F%2Fauth0.com%2Foauth%2Fgrant-type%2Fmfa-oob&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&mfa_token=%7BmfaToken%7D&oob_code=%7BoobCode%7D" response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "authorization": "Bearer {mfaToken}", @@ -444,20 +474,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ユーザーがコードをスキャンしなかった場合には、`authorization_pending`応答が返され、数秒以内に`oauth_token`をもう一度呼び出す必要があることが分かります。 @@ -494,16 +513,22 @@ MFA Authenticatorエンドポイントを呼び出すことで、Authenticator ユーザーにチャレンジするには、チャレンジしたい要素の`authenticator_id`が必要です。登録された全Authenticatorの一覧は、MFA Authenticatorエンドポイントを使って表示できます: -export const codeExample21 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/mfa/authenticators' \ --header 'authorization: Bearer MFA_TOKEN' \ - --header 'content-type: application/json'`; -export const codeExample22 = `var client = new RestClient("https://{yourDomain}/mfa/authenticators"); + --header 'content-type: application/json' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/mfa/authenticators"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer MFA_TOKEN"); request.AddHeader("content-type", "application/json"); -IRestResponse response = client.Execute(request);`; -export const codeExample23 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -528,12 +553,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample24 = `HttpResponse response = Unirest.get("https://{yourDomain}/mfa/authenticators") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/mfa/authenticators") .header("authorization", "Bearer MFA_TOKEN") .header("content-type", "application/json") - .asString();`; -export const codeExample25 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -545,8 +574,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample26 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MFA_TOKEN", @"content-type": @"application/json" }; @@ -567,8 +598,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample27 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/mfa/authenticators", @@ -593,8 +626,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample28 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -608,8 +643,10 @@ conn.request("GET", "/{yourDomain}/mfa/authenticators", headers=headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample29 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -624,8 +661,10 @@ request["authorization"] = 'Bearer MFA_TOKEN' request["content-type"] = 'application/json' response = http.request(request) -puts response.read_body`; -export const codeExample30 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "authorization": "Bearer MFA_TOKEN", @@ -648,20 +687,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + Authenticatorのリストは以下の形式で取得されます。 @@ -693,14 +721,20 @@ Authenticatorのリストは以下の形式で取得されます。 プッシュチャレンジをトリガーするには、対応する`authenticator_id`と`mfa_token`を使ってMFAチャレンジエンドポイントに`POST`を行います。 -export const codeExample31 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/mfa/challenge' \ - --data '{ "client_id": "{yourClientId}", "client_secret": "{yourClientSecret", "challenge_type": "oob", "authenticator_id": "push|dev_ZUla9SQ6tAIHSz6y", "mfa_token": "{mfaToken}" }'`; -export const codeExample32 = `var client = new RestClient("https://{yourDomain}/mfa/challenge"); + --data '{ "client_id": "{yourClientId}", "client_secret": "{yourClientSecret", "challenge_type": "oob", "authenticator_id": "push|dev_ZUla9SQ6tAIHSz6y", "mfa_token": "{mfaToken}" }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/mfa/challenge"); var request = new RestRequest(Method.POST); -request.AddParameter("undefined", "{ \"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret\", \"challenge_type\": \"oob\", \"authenticator_id\": \"push|dev_ZUla9SQ6tAIHSz6y\", \"mfa_token\": \"{mfaToken}\" }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample33 = `package main +request.AddParameter("undefined", "{ "client_id": "{yourClientId}", "client_secret": "{yourClientSecret", "challenge_type": "oob", "authenticator_id": "push|dev_ZUla9SQ6tAIHSz6y", "mfa_token": "{mfaToken}" }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -713,7 +747,7 @@ func main() { url := "https://{yourDomain}/mfa/challenge" - payload := strings.NewReader("{ \"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret\", \"challenge_type\": \"oob\", \"authenticator_id\": \"push|dev_ZUla9SQ6tAIHSz6y\", \"mfa_token\": \"{mfaToken}\" }") + payload := strings.NewReader("{ "client_id": "{yourClientId}", "client_secret": "{yourClientSecret", "challenge_type": "oob", "authenticator_id": "push|dev_ZUla9SQ6tAIHSz6y", "mfa_token": "{mfaToken}" }") req, _ := http.NewRequest("POST", url, payload) @@ -725,11 +759,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample34 = `HttpResponse response = Unirest.post("https://{yourDomain}/mfa/challenge") - .body("{ \"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret\", \"challenge_type\": \"oob\", \"authenticator_id\": \"push|dev_ZUla9SQ6tAIHSz6y\", \"mfa_token\": \"{mfaToken}\" }") - .asString();`; -export const codeExample35 = `var axios = require("axios").default; +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/mfa/challenge") + .body("{ "client_id": "{yourClientId}", "client_secret": "{yourClientSecret", "challenge_type": "oob", "authenticator_id": "push|dev_ZUla9SQ6tAIHSz6y", "mfa_token": "{mfaToken}" }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -747,8 +785,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample36 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *parameters = @{ @"client_id": @"{yourClientId}", @"client_secret": @"{yourClientSecret", @"challenge_type": @"oob", @@ -773,8 +813,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample37 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/mfa/challenge", @@ -784,7 +826,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{ \"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret\", \"challenge_type\": \"oob\", \"authenticator_id\": \"push|dev_ZUla9SQ6tAIHSz6y\", \"mfa_token\": \"{mfaToken}\" }", + CURLOPT_POSTFIELDS => "{ "client_id": "{yourClientId}", "client_secret": "{yourClientSecret", "challenge_type": "oob", "authenticator_id": "push|dev_ZUla9SQ6tAIHSz6y", "mfa_token": "{mfaToken}" }", ]); $response = curl_exec($curl); @@ -796,20 +838,24 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample38 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret\", \"challenge_type\": \"oob\", \"authenticator_id\": \"push|dev_ZUla9SQ6tAIHSz6y\", \"mfa_token\": \"{mfaToken}\" }" +payload = "{ "client_id": "{yourClientId}", "client_secret": "{yourClientSecret", "challenge_type": "oob", "authenticator_id": "push|dev_ZUla9SQ6tAIHSz6y", "mfa_token": "{mfaToken}" }" conn.request("POST", "/{yourDomain}/mfa/challenge", payload) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample39 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -820,11 +866,13 @@ http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) -request.body = "{ \"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret\", \"challenge_type\": \"oob\", \"authenticator_id\": \"push|dev_ZUla9SQ6tAIHSz6y\", \"mfa_token\": \"{mfaToken}\" }" +request.body = "{ "client_id": "{yourClientId}", "client_secret": "{yourClientSecret", "challenge_type": "oob", "authenticator_id": "push|dev_ZUla9SQ6tAIHSz6y", "mfa_token": "{mfaToken}" }" response = http.request(request) -puts response.read_body`; -export const codeExample40 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let parameters = [ "client_id": "{yourClientId}", "client_secret": "{yourClientSecret", @@ -851,20 +899,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ### 受信したコードを使って認証を完了します。 @@ -879,20 +916,26 @@ dataTask.resume()`; アプリケーションは、ユーザーがプッシュ通知を受領するまで、OAuth0トークンエンドポイントをポーリングしなければなりません。 -export const codeExample41 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=http://auth0.com/oauth/grant-type/mfa-oob \ --data 'client_id={yourClientId}' \ --data 'client_secret={yourClientSecret}' \ --data 'mfa_token={mfaToken}' \ - --data 'oob_code={oobCode}'`; -export const codeExample42 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data 'oob_code={oobCode}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=http%3A%2F%2Fauth0.com%2Foauth%2Fgrant-type%2Fmfa-oob&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&mfa_token=%7BmfaToken%7D&oob_code=%7BoobCode%7D", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample43 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -919,12 +962,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample44 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=http%3A%2F%2Fauth0.com%2Foauth%2Fgrant-type%2Fmfa-oob&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&mfa_token=%7BmfaToken%7D&oob_code=%7BoobCode%7D") - .asString();`; -export const codeExample45 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -943,8 +990,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample46 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -971,8 +1020,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample47 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -997,8 +1048,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample48 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -1011,8 +1064,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample49 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -1027,8 +1082,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=http%3A%2F%2Fauth0.com%2Foauth%2Fgrant-type%2Fmfa-oob&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&mfa_token=%7BmfaToken%7D&oob_code=%7BoobCode%7D" response = http.request(request) -puts response.read_body`; -export const codeExample50 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -1055,20 +1112,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + 呼び出しでは、以下の結果のうち1つが返されます。 diff --git a/main/docs/ja-jp/secure/multi-factor-authentication/authenticate-using-ropg-flow-with-mfa/enroll-challenge-sms-voice-authenticators.mdx b/main/docs/ja-jp/secure/multi-factor-authentication/authenticate-using-ropg-flow-with-mfa/enroll-challenge-sms-voice-authenticators.mdx index 3a69cbefb..fe040b9ac 100644 --- a/main/docs/ja-jp/secure/multi-factor-authentication/authenticate-using-ropg-flow-with-mfa/enroll-challenge-sms-voice-authenticators.mdx +++ b/main/docs/ja-jp/secure/multi-factor-authentication/authenticate-using-ropg-flow-with-mfa/enroll-challenge-sms-voice-authenticators.mdx @@ -10,6 +10,7 @@ permalink: "enroll-challenge-sms-voice-authenticators" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Auth0は、[ユニバーサルログイン](/docs/ja-jp/authenticate/login/auth0-universal-login)を使用した組み込みのMFA登録と認証フローを提供します。ただし、独自のインターフェイスを作成したい場合は、[MFA API](/docs/ja-jp/secure/multi-factor-authentication/multi-factor-authentication-developer-resources/mfa-api)を使用することもできます。 @@ -34,18 +35,24 @@ MFA APIを使用するには、事前にアプリケーションに対してMFA SMSや音声で登録するには、SMSまたは音声でチャレンジできる電話番号を使って登録します。以下のパラメーターを指定してエンドポイントを呼び出します。`oob_channels`パラメーターは、ユーザーにコードを送信する方法(SMSまたは音声)を指定します。 -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/mfa/associate' \ --header 'authorization: Bearer {mfaToken}' \ --header 'content-type: application/json' \ ---data '{ "authenticator_types": ["oob"], "oob_channels": ["sms"], "phone_number": "+11...9" }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/mfa/associate"); +--data '{ "authenticator_types": ["oob"], "oob_channels": ["sms"], "phone_number": "+11...9" }' +``` lines +```csharp C# +var client = new RestClient("https://{yourDomain}/mfa/associate"); var request = new RestRequest(Method.POST); request.AddHeader("authorization", "Bearer {mfaToken}"); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{ \"authenticator_types\": [\"oob\"], \"oob_channels\": [\"sms\"], \"phone_number\": \"+11...9\" }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "authenticator_types": ["oob"], "oob_channels": ["sms"], "phone_number": "+11...9" }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" "strings" @@ -54,7 +61,7 @@ import ( ) func main() { url := "https://{yourDomain}/mfa/associate" -payload := strings.NewReader("{ \"authenticator_types\": [\"oob\"], \"oob_channels\": [\"sms\"], \"phone_number\": \"+11...9\" }") +payload := strings.NewReader("{ "authenticator_types": ["oob"], "oob_channels": ["sms"], "phone_number": "+11...9" }") req, _ := http.NewRequest("POST", url, payload) req.Header.Add("authorization", "Bearer {mfaToken}") req.Header.Add("content-type", "application/json") @@ -63,13 +70,17 @@ defer res.Body.Close() body, _ := ioutil.ReadAll(res.Body) fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/mfa/associate") +} +``` lines +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/mfa/associate") .header("authorization", "Bearer {mfaToken}") .header("content-type", "application/json") -.body("{ \"authenticator_types\": [\"oob\"], \"oob_channels\": [\"sms\"], \"phone_number\": \"+11...9\" }") -.asString();`; -export const codeExample5 = `var axios = require("axios").default; +.body("{ "authenticator_types": ["oob"], "oob_channels": ["sms"], "phone_number": "+11...9" }") +.asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', url: 'https://{yourDomain}/mfa/associate', @@ -80,8 +91,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` lines +```obj-c Obj-C +#import NSDictionary \*headers = @{ @"authorization": @"Bearer {mfaToken}", @"content-type": @"application/json" }; NSDictionary \*parameters = @{ @"authenticator_types": @[ @"oob" ], @@ -104,8 +117,10 @@ NSHTTPURLResponse \*httpResponse = (NSHTTPURLResponse \*) response; NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/mfa/associate", CURLOPT_RETURNTRANSFER => true, @@ -114,7 +129,7 @@ CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", -CURLOPT_POSTFIELDS => "{ \"authenticator_types\": [\"oob\"], \"oob_channels\": [\"sms\"], \"phone_number\": \"+11...9\" }", +CURLOPT_POSTFIELDS => "{ "authenticator_types": ["oob"], "oob_channels": ["sms"], "phone_number": "+11...9" }", CURLOPT_HTTPHEADER => [ "authorization: Bearer {mfaToken}", "content-type: application/json" @@ -127,10 +142,12 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` lines +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"authenticator_types\": [\"oob\"], \"oob_channels\": [\"sms\"], \"phone_number\": \"+11...9\" }" +payload = "{ "authenticator_types": ["oob"], "oob_channels": ["sms"], "phone_number": "+11...9" }" headers = { 'authorization': "Bearer {mfaToken}", 'content-type': "application/json" @@ -138,8 +155,10 @@ headers = { conn.request("POST", "/{yourDomain}/mfa/associate", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' url = URI("https://{yourDomain}/mfa/associate") @@ -149,10 +168,12 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["authorization"] = 'Bearer {mfaToken}' request["content-type"] = 'application/json' -request.body = "{ \"authenticator_types\": [\"oob\"], \"oob_channels\": [\"sms\"], \"phone_number\": \"+11...9\" }" +request.body = "{ "authenticator_types": ["oob"], "oob_channels": ["sms"], "phone_number": "+11...9" }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` lines +```swift Swift +import Foundation let headers = [ "authorization": "Bearer {mfaToken}", "content-type": "application/json" @@ -178,20 +199,9 @@ let httpResponse = response as? HTTPURLResponse print(httpResponse) } }) -dataTask.resume()`; - - - lines - - lines - - lines - - lines - - lines - - +dataTask.resume() +``` + @@ -238,7 +248,9 @@ dataTask.resume()`; 登録を完了するには、OAuthトークンエンドポイントに`POST`要求を行います。メッセージで受け取った値とともに、前の応答で返された`oob_code`と`binding_code`を含める必要があります。 -export const codeExample11 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'authorization: Bearer {mfaToken}' \ --header 'content-type: application/x-www-form-urlencoded' \ @@ -247,14 +259,18 @@ export const codeExample11 = `curl --request POST \ --data 'client_secret={yourClientSecret}' \ --data 'mfa_token={mfaToken}' \ --data 'oob_code={oobCode}' \ ---data 'binding_code={userOtpCode}'`; -export const codeExample12 = `var client = new RestClient("https://{yourDomain}/oauth/token"); +--data 'binding_code={userOtpCode}' +``` lines +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("authorization", "Bearer {mfaToken}"); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=http%3A%2F%2Fauth0.com%2Foauth%2Fgrant-type%2Fmfa-oob&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&mfa_token=%7BmfaToken%7D&oob_code=%7BoobCode%7D&binding_code=%7BuserOtpCode%7D", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample13 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" "strings" @@ -272,13 +288,17 @@ defer res.Body.Close() body, _ := ioutil.ReadAll(res.Body) fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample14 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` lines +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("authorization", "Bearer {mfaToken}") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=http%3A%2F%2Fauth0.com%2Foauth%2Fgrant-type%2Fmfa-oob&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&mfa_token=%7BmfaToken%7D&oob_code=%7BoobCode%7D&binding_code=%7BuserOtpCode%7D") -.asString();`; -export const codeExample15 = `var axios = require("axios").default; +.asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', url: 'https://{yourDomain}/oauth/token', @@ -299,8 +319,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample16 = `#import +}); +``` lines +```obj-c Obj-C +#import NSDictionary \*headers = @{ @"authorization": @"Bearer {mfaToken}", @"content-type": @"application/x-www-form-urlencoded" }; NSMutableData \*postData = [[NSMutableData alloc] initWithData:[@"grant_type=http://auth0.com/oauth/grant-type/mfa-oob" dataUsingEncoding:NSUTF8StringEncoding]]; @@ -325,8 +347,10 @@ NSHTTPURLResponse \*httpResponse = (NSHTTPURLResponse \*) response; NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", CURLOPT_RETURNTRANSFER => true, @@ -348,8 +372,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `import http.client +} +``` lines +```python Python +import http.client conn = http.client.HTTPSConnection("") payload = "grant_type=http%3A%2F%2Fauth0.com%2Foauth%2Fgrant-type%2Fmfa-oob&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&mfa_token=%7BmfaToken%7D&oob_code=%7BoobCode%7D&binding_code=%7BuserOtpCode%7D" headers = { @@ -359,8 +385,10 @@ headers = { conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' url = URI("https://{yourDomain}/oauth/token") @@ -372,8 +400,10 @@ request["authorization"] = 'Bearer {mfaToken}' request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=http%3A%2F%2Fauth0.com%2Foauth%2Fgrant-type%2Fmfa-oob&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&mfa_token=%7BmfaToken%7D&oob_code=%7BoobCode%7D&binding_code=%7BuserOtpCode%7D" response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` lines +```swift Swift +import Foundation let headers = [ "authorization": "Bearer {mfaToken}", "content-type": "application/x-www-form-urlencoded" @@ -399,20 +429,9 @@ let httpResponse = response as? HTTPURLResponse print(httpResponse) } }) -dataTask.resume()`; - - - lines - - lines - - lines - - lines - - lines - - +dataTask.resume() +``` + 呼び出しが成功すると、アクセストークンを含む応答が以下の形式で返されます。 @@ -436,16 +455,22 @@ dataTask.resume()`; ユーザーにチャレンジするには、チャレンジしたい要素の`authenticator_id`が必要です。登録された全Authenticatorの一覧は、MFA Authenticatorエンドポイントを使って表示できます: -export const codeExample21 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/mfa/authenticators' \ --header 'authorization: Bearer MFA_TOKEN' \ ---header 'content-type: application/json'`; -export const codeExample22 = `var client = new RestClient("https://{yourDomain}/mfa/authenticators"); +--header 'content-type: application/json' +``` lines +```csharp C# +var client = new RestClient("https://{yourDomain}/mfa/authenticators"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer MFA_TOKEN"); request.AddHeader("content-type", "application/json"); -IRestResponse response = client.Execute(request);`; -export const codeExample23 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" "net/http" @@ -461,12 +486,16 @@ defer res.Body.Close() body, _ := ioutil.ReadAll(res.Body) fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample24 = `HttpResponse response = Unirest.get("https://{yourDomain}/mfa/authenticators") +} +``` lines +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/mfa/authenticators") .header("authorization", "Bearer MFA_TOKEN") .header("content-type", "application/json") -.asString();`; -export const codeExample25 = `var axios = require("axios").default; +.asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', url: 'https://{yourDomain}/mfa/authenticators', @@ -476,8 +505,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample26 = `#import +}); +``` lines +```obj-c Obj-C +#import NSDictionary \*headers = @{ @"authorization": @"Bearer MFA_TOKEN", @"content-type": @"application/json" }; NSMutableURLRequest \*request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://{yourDomain}/mfa/authenticators"] @@ -495,8 +526,10 @@ NSHTTPURLResponse \*httpResponse = (NSHTTPURLResponse \*) response; NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample27 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/mfa/authenticators", CURLOPT_RETURNTRANSFER => true, @@ -517,8 +550,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample28 = `import http.client +} +``` lines +```python Python +import http.client conn = http.client.HTTPSConnection("") headers = { 'authorization': "Bearer MFA_TOKEN", @@ -527,8 +562,10 @@ headers = { conn.request("GET", "/{yourDomain}/mfa/authenticators", headers=headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample29 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' url = URI("https://{yourDomain}/mfa/authenticators") @@ -539,8 +576,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer MFA_TOKEN' request["content-type"] = 'application/json' response = http.request(request) -puts response.read_body`; -export const codeExample30 = `import Foundation +puts response.read_body +``` lines +```swift Swift +import Foundation let headers = [ "authorization": "Bearer MFA_TOKEN", "content-type": "application/json" @@ -559,20 +598,9 @@ let httpResponse = response as? HTTPURLResponse print(httpResponse) } }) -dataTask.resume()`; - - - lines - - lines - - lines - - lines - - lines - - +dataTask.resume() +``` + Authenticatorのリストが以下の形式で返されます。 @@ -604,16 +632,22 @@ Authenticatorのリストが以下の形式で返されます。 メールチャレンジをトリガーするには、対応する`authenticator_id`と`mfa_token`を使ってMFAチャレンジエンドポイントを`POST`します。 -export const codeExample31 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/mfa/challenge' \ --header 'content-type: application/json' \ ---data '{ "client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "challenge_type": "oob", "authenticator_id": "sms|dev_NU1Ofuw3Cw0XCt5x", "mfa_token": "{mfaToken}" }'`; -export const codeExample32 = `var client = new RestClient("https://{yourDomain}/mfa/challenge"); +--data '{ "client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "challenge_type": "oob", "authenticator_id": "sms|dev_NU1Ofuw3Cw0XCt5x", "mfa_token": "{mfaToken}" }' +``` lines +```csharp C# +var client = new RestClient("https://{yourDomain}/mfa/challenge"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{ \"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"challenge_type\": \"oob\", \"authenticator_id\": \"sms|dev_NU1Ofuw3Cw0XCt5x\", \"mfa_token\": \"{mfaToken}\" }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample33 = `package main +request.AddParameter("application/json", "{ "client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "challenge_type": "oob", "authenticator_id": "sms|dev_NU1Ofuw3Cw0XCt5x", "mfa_token": "{mfaToken}" }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" "strings" @@ -622,7 +656,7 @@ import ( ) func main() { url := "https://{yourDomain}/mfa/challenge" -payload := strings.NewReader("{ \"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"challenge_type\": \"oob\", \"authenticator_id\": \"sms|dev_NU1Ofuw3Cw0XCt5x\", \"mfa_token\": \"{mfaToken}\" }") +payload := strings.NewReader("{ "client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "challenge_type": "oob", "authenticator_id": "sms|dev_NU1Ofuw3Cw0XCt5x", "mfa_token": "{mfaToken}" }") req, _ := http.NewRequest("POST", url, payload) req.Header.Add("content-type", "application/json") res, _ := http.DefaultClient.Do(req) @@ -630,12 +664,16 @@ defer res.Body.Close() body, _ := ioutil.ReadAll(res.Body) fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample34 = `HttpResponse response = Unirest.post("https://{yourDomain}/mfa/challenge") +} +``` lines +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/mfa/challenge") .header("content-type", "application/json") -.body("{ \"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"challenge_type\": \"oob\", \"authenticator_id\": \"sms|dev_NU1Ofuw3Cw0XCt5x\", \"mfa_token\": \"{mfaToken}\" }") -.asString();`; -export const codeExample35 = `var axios = require("axios").default; +.body("{ "client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "challenge_type": "oob", "authenticator_id": "sms|dev_NU1Ofuw3Cw0XCt5x", "mfa_token": "{mfaToken}" }") +.asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', url: 'https://{yourDomain}/mfa/challenge', @@ -652,8 +690,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample36 = `#import +}); +``` lines +```obj-c Obj-C +#import NSDictionary \*headers = @{ @"content-type": @"application/json" }; NSDictionary \*parameters = @{ @"client_id": @"{yourClientId}", @"client_secret": @"{yourClientSecret}", @@ -677,8 +717,10 @@ NSHTTPURLResponse \*httpResponse = (NSHTTPURLResponse \*) response; NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample37 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/mfa/challenge", CURLOPT_RETURNTRANSFER => true, @@ -687,7 +729,7 @@ CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", -CURLOPT_POSTFIELDS => "{ \"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"challenge_type\": \"oob\", \"authenticator_id\": \"sms|dev_NU1Ofuw3Cw0XCt5x\", \"mfa_token\": \"{mfaToken}\" }", +CURLOPT_POSTFIELDS => "{ "client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "challenge_type": "oob", "authenticator_id": "sms|dev_NU1Ofuw3Cw0XCt5x", "mfa_token": "{mfaToken}" }", CURLOPT_HTTPHEADER => [ "content-type: application/json" ], @@ -699,16 +741,20 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample38 = `import http.client +} +``` lines +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"challenge_type\": \"oob\", \"authenticator_id\": \"sms|dev_NU1Ofuw3Cw0XCt5x\", \"mfa_token\": \"{mfaToken}\" }" +payload = "{ "client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "challenge_type": "oob", "authenticator_id": "sms|dev_NU1Ofuw3Cw0XCt5x", "mfa_token": "{mfaToken}" }" headers = { 'content-type': "application/json" } conn.request("POST", "/{yourDomain}/mfa/challenge", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample39 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' url = URI("https://{yourDomain}/mfa/challenge") @@ -717,10 +763,12 @@ http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["content-type"] = 'application/json' -request.body = "{ \"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"challenge_type\": \"oob\", \"authenticator_id\": \"sms|dev_NU1Ofuw3Cw0XCt5x\", \"mfa_token\": \"{mfaToken}\" }" +request.body = "{ "client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "challenge_type": "oob", "authenticator_id": "sms|dev_NU1Ofuw3Cw0XCt5x", "mfa_token": "{mfaToken}" }" response = http.request(request) -puts response.read_body`; -export const codeExample40 = `import Foundation +puts response.read_body +``` lines +```swift Swift +import Foundation let headers = ["content-type": "application/json"] let parameters = [ "client_id": "{yourClientId}", @@ -745,20 +793,9 @@ let httpResponse = response as? HTTPURLResponse print(httpResponse) } }) -dataTask.resume()`; - - - lines - - lines - - lines - - lines - - lines - - +dataTask.resume() +``` + ### 受信したコードを使って認証を完了する @@ -774,7 +811,9 @@ dataTask.resume()`; アプリケーションは、メッセージで送信した6桁のコードをユーザーに求めて、`binding_code`パラメーター内に設定する必要があります。前の呼び出しで返された`binding_code`と`oob_code`を指定して、OAuth0トークンエンドポイントでコードを検証し、トークンを取得することができます。 -export const codeExample41 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=http://auth0.com/oauth/grant-type/mfa-oob \ @@ -782,13 +821,17 @@ export const codeExample41 = `curl --request POST \ --data 'client_secret={yourClientSecret}' \ --data 'mfa_token={mfaToken}' \ --data 'oob_code={oobCode}' \ ---data binding_code=USER_OTP_CODE`; -export const codeExample42 = `var client = new RestClient("https://{yourDomain}/oauth/token"); +--data binding_code=USER_OTP_CODE +``` lines +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=http%3A%2F%2Fauth0.com%2Foauth%2Fgrant-type%2Fmfa-oob&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&mfa_token=%7BmfaToken%7D&oob_code=%7BoobCode%7D&binding_code=USER_OTP_CODE", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample43 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" "strings" @@ -805,12 +848,16 @@ defer res.Body.Close() body, _ := ioutil.ReadAll(res.Body) fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample44 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` lines +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=http%3A%2F%2Fauth0.com%2Foauth%2Fgrant-type%2Fmfa-oob&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&mfa_token=%7BmfaToken%7D&oob_code=%7BoobCode%7D&binding_code=USER_OTP_CODE") -.asString();`; -export const codeExample45 = `var axios = require("axios").default; +.asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', url: 'https://{yourDomain}/oauth/token', @@ -828,8 +875,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample46 = `#import +}); +``` lines +```obj-c Obj-C +#import NSDictionary \*headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; NSMutableData \*postData = [[NSMutableData alloc] initWithData:[@"grant_type=http://auth0.com/oauth/grant-type/mfa-oob" dataUsingEncoding:NSUTF8StringEncoding]]; [postData appendData:[@"&client_id={yourClientId}" dataUsingEncoding:NSUTF8StringEncoding]]; @@ -853,8 +902,10 @@ NSHTTPURLResponse \*httpResponse = (NSHTTPURLResponse \*) response; NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample47 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", CURLOPT_RETURNTRANSFER => true, @@ -875,16 +926,20 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample48 = `import http.client +} +``` lines +```python Python +import http.client conn = http.client.HTTPSConnection("") payload = "grant_type=http%3A%2F%2Fauth0.com%2Foauth%2Fgrant-type%2Fmfa-oob&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&mfa_token=%7BmfaToken%7D&oob_code=%7BoobCode%7D&binding_code=USER_OTP_CODE" headers = { 'content-type': "application/x-www-form-urlencoded" } conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample49 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' url = URI("https://{yourDomain}/oauth/token") @@ -895,8 +950,10 @@ request = Net::HTTP::Post.new(url) request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=http%3A%2F%2Fauth0.com%2Foauth%2Fgrant-type%2Fmfa-oob&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&mfa_token=%7BmfaToken%7D&oob_code=%7BoobCode%7D&binding_code=USER_OTP_CODE" response = http.request(request) -puts response.read_body`; -export const codeExample50 = `import Foundation +puts response.read_body +``` lines +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] let postData = NSMutableData(data: "grant_type=http://auth0.com/oauth/grant-type/mfa-oob".data(using: String.Encoding.utf8)!) postData.append("&client_id={yourClientId}".data(using: String.Encoding.utf8)!) @@ -919,20 +976,9 @@ let httpResponse = response as? HTTPURLResponse print(httpResponse) } }) -dataTask.resume()`; - - - lines - - lines - - lines - - lines - - lines - - +dataTask.resume() +``` + 呼び出しが成功すると、アクセストークンを含む応答が以下の形式で返されます: diff --git a/main/docs/ja-jp/secure/multi-factor-authentication/manage-mfa-auth0-apis/manage-authentication-methods-with-management-api.mdx b/main/docs/ja-jp/secure/multi-factor-authentication/manage-mfa-auth0-apis/manage-authentication-methods-with-management-api.mdx index 1b45c7852..5fd0f3e50 100644 --- a/main/docs/ja-jp/secure/multi-factor-authentication/manage-mfa-auth0-apis/manage-authentication-methods-with-management-api.mdx +++ b/main/docs/ja-jp/secure/multi-factor-authentication/manage-mfa-auth0-apis/manage-authentication-methods-with-management-api.mdx @@ -10,6 +10,7 @@ permalink: "manage-authentication-methods-with-management-api" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; @@ -36,7 +37,7 @@ import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; 以下の要求は特定のユーザーについて、すべての認証方法のリストを返します。 - + ```bash cURL lines curl --request GET \ --url https://%7ByourDomain%7D/api/v2/users/%7BuserId%7D/authentication-methods \ @@ -203,7 +204,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + ### 応答 @@ -231,7 +232,7 @@ dataTask.resume() 以下の要求は、指定された認証方法のIDに基づいて、ユーザーの1つの認証方法を返します。 - + ```bash cURL lines curl --request GET \ --url https://%7ByourDomain%7D/api/v2/users/%7BuserId%7D/authentication-methods/%7BauthenticationMethodId%7D \ @@ -398,7 +399,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + ### 応答 @@ -434,7 +435,7 @@ SMSでユーザーにワンタイムパスワード(OTP)を送信します 以下の要求はユーザーのSMS認証方法を作成します。 - + ```bash cURL lines curl --request POST \ --url https://%7ByourDomain%7D/api/v2/users/%7BuserId%7D/authentication-methods \ @@ -626,7 +627,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + #### 応答 @@ -650,7 +651,7 @@ Management APIは、有効な各要求に対して、JSON形式の応答を返 以下の要求はユーザーのメール認証方法を作成します。 - + ```bash cURL lines curl --request POST \ --url https://%7ByourDomain%7D/api/v2/users/%7BuserId%7D/authentication-methods \ @@ -842,7 +843,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + #### 応答 @@ -866,16 +867,22 @@ Management APIは、有効な各要求に対して、JSON形式の応答を返 以下の要求はユーザーのOTP認証方法を作成します。 -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url https://%7ByourDomain%7D/api/v2/users/%7BuserId%7D/authentication-methods \ --header 'authorization: Bearer {yourMgmtApiAccessToken}' \ - --data '{ "type": "totp", "name": "OTP Application", "totp_secret": "{yourSecret}" }'`; -export const codeExample2 = `var client = new RestClient("https://%7ByourDomain%7D/api/v2/users/%7BuserId%7D/authentication-methods"); + --data '{ "type": "totp", "name": "OTP Application", "totp_secret": "{yourSecret}" }' +``` +```csharp C# +var client = new RestClient("https://%7ByourDomain%7D/api/v2/users/%7BuserId%7D/authentication-methods"); var request = new RestRequest(Method.POST); request.AddHeader("authorization", "Bearer {yourMgmtApiAccessToken}"); -request.AddParameter("undefined", "{ \"type\": \"totp\", \"name\": \"OTP Application\", \"totp_secret\": \"{yourSecret}\" }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("undefined", "{ "type": "totp", "name": "OTP Application", "totp_secret": "{yourSecret}" }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -888,7 +895,7 @@ func main() { url := "https://%7ByourDomain%7D/api/v2/users/%7BuserId%7D/authentication-methods" - payload := strings.NewReader("{ \"type\": \"totp\", \"name\": \"OTP Application\", \"totp_secret\": \"{yourSecret}\" }") + payload := strings.NewReader("{ "type": "totp", "name": "OTP Application", "totp_secret": "{yourSecret}" }") req, _ := http.NewRequest("POST", url, payload) @@ -902,12 +909,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://%7ByourDomain%7D/api/v2/users/%7BuserId%7D/authentication-methods") +} +``` +```java Java +HttpResponse response = Unirest.post("https://%7ByourDomain%7D/api/v2/users/%7BuserId%7D/authentication-methods") .header("authorization", "Bearer {yourMgmtApiAccessToken}") - .body("{ \"type\": \"totp\", \"name\": \"OTP Application\", \"totp_secret\": \"{yourSecret}\" }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "type": "totp", "name": "OTP Application", "totp_secret": "{yourSecret}" }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -920,8 +931,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer {yourMgmtApiAccessToken}" }; NSDictionary *parameters = @{ @"type": @"totp", @@ -947,8 +960,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://%7ByourDomain%7D/api/v2/users/%7BuserId%7D/authentication-methods", @@ -958,7 +973,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{ \"type\": \"totp\", \"name\": \"OTP Application\", \"totp_secret\": \"{yourSecret}\" }", + CURLOPT_POSTFIELDS => "{ "type": "totp", "name": "OTP Application", "totp_secret": "{yourSecret}" }", CURLOPT_HTTPHEADER => [ "authorization: Bearer {yourMgmtApiAccessToken}" ], @@ -973,12 +988,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"type\": \"totp\", \"name\": \"OTP Application\", \"totp_secret\": \"{yourSecret}\" }" +payload = "{ "type": "totp", "name": "OTP Application", "totp_secret": "{yourSecret}" }" headers = { 'authorization': "Bearer {yourMgmtApiAccessToken}" } @@ -987,8 +1004,10 @@ conn.request("POST", "%7ByourDomain%7D/api/v2/users/%7BuserId%7D/authentication- res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -1000,11 +1019,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["authorization"] = 'Bearer {yourMgmtApiAccessToken}' -request.body = "{ \"type\": \"totp\", \"name\": \"OTP Application\", \"totp_secret\": \"{yourSecret}\" }" +request.body = "{ "type": "totp", "name": "OTP Application", "totp_secret": "{yourSecret}" }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer {yourMgmtApiAccessToken}"] let parameters = [ @@ -1032,20 +1053,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + #### 応答 @@ -1069,16 +1079,22 @@ Management APIは、有効な各要求に対して、JSON形式の応答を返 以下の要求はユーザーについて、セキュリティキーを使ったWebAuthn認証方法を作成します。 -export const codeExample11 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url https://%7ByourDomain%7D/api/v2/users/%7BuserId%7D/authentication-methods \ --header 'authorization: Bearer {yourMgmtApiAccessToken}' \ - --data '{ "type": "webauthn_roaming", "name": "WebAuthn with security keys", "public_key": "{yourPublicKey}", "key_id": "{yourKeyId}", "relying_party_identifier": "{yourDomain}" }'`; -export const codeExample12 = `var client = new RestClient("https://%7ByourDomain%7D/api/v2/users/%7BuserId%7D/authentication-methods"); + --data '{ "type": "webauthn_roaming", "name": "WebAuthn with security keys", "public_key": "{yourPublicKey}", "key_id": "{yourKeyId}", "relying_party_identifier": "{yourDomain}" }' +``` +```csharp C# +var client = new RestClient("https://%7ByourDomain%7D/api/v2/users/%7BuserId%7D/authentication-methods"); var request = new RestRequest(Method.POST); request.AddHeader("authorization", "Bearer {yourMgmtApiAccessToken}"); -request.AddParameter("undefined", "{ \"type\": \"webauthn_roaming\", \"name\": \"WebAuthn with security keys\", \"public_key\": \"{yourPublicKey}\", \"key_id\": \"{yourKeyId}\", \"relying_party_identifier\": \"{yourDomain}\" }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample13 = `package main +request.AddParameter("undefined", "{ "type": "webauthn_roaming", "name": "WebAuthn with security keys", "public_key": "{yourPublicKey}", "key_id": "{yourKeyId}", "relying_party_identifier": "{yourDomain}" }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -1091,7 +1107,7 @@ func main() { url := "https://%7ByourDomain%7D/api/v2/users/%7BuserId%7D/authentication-methods" - payload := strings.NewReader("{ \"type\": \"webauthn_roaming\", \"name\": \"WebAuthn with security keys\", \"public_key\": \"{yourPublicKey}\", \"key_id\": \"{yourKeyId}\", \"relying_party_identifier\": \"{yourDomain}\" }") + payload := strings.NewReader("{ "type": "webauthn_roaming", "name": "WebAuthn with security keys", "public_key": "{yourPublicKey}", "key_id": "{yourKeyId}", "relying_party_identifier": "{yourDomain}" }") req, _ := http.NewRequest("POST", url, payload) @@ -1105,12 +1121,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample14 = `HttpResponse response = Unirest.post("https://%7ByourDomain%7D/api/v2/users/%7BuserId%7D/authentication-methods") +} +``` +```java Java +HttpResponse response = Unirest.post("https://%7ByourDomain%7D/api/v2/users/%7BuserId%7D/authentication-methods") .header("authorization", "Bearer {yourMgmtApiAccessToken}") - .body("{ \"type\": \"webauthn_roaming\", \"name\": \"WebAuthn with security keys\", \"public_key\": \"{yourPublicKey}\", \"key_id\": \"{yourKeyId}\", \"relying_party_identifier\": \"{yourDomain}\" }") - .asString();`; -export const codeExample15 = `var axios = require("axios").default; + .body("{ "type": "webauthn_roaming", "name": "WebAuthn with security keys", "public_key": "{yourPublicKey}", "key_id": "{yourKeyId}", "relying_party_identifier": "{yourDomain}" }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -1129,8 +1149,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample16 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer {yourMgmtApiAccessToken}" }; NSDictionary *parameters = @{ @"type": @"webauthn_roaming", @@ -1158,8 +1180,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://%7ByourDomain%7D/api/v2/users/%7BuserId%7D/authentication-methods", @@ -1169,7 +1193,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{ \"type\": \"webauthn_roaming\", \"name\": \"WebAuthn with security keys\", \"public_key\": \"{yourPublicKey}\", \"key_id\": \"{yourKeyId}\", \"relying_party_identifier\": \"{yourDomain}\" }", + CURLOPT_POSTFIELDS => "{ "type": "webauthn_roaming", "name": "WebAuthn with security keys", "public_key": "{yourPublicKey}", "key_id": "{yourKeyId}", "relying_party_identifier": "{yourDomain}" }", CURLOPT_HTTPHEADER => [ "authorization: Bearer {yourMgmtApiAccessToken}" ], @@ -1184,12 +1208,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"type\": \"webauthn_roaming\", \"name\": \"WebAuthn with security keys\", \"public_key\": \"{yourPublicKey}\", \"key_id\": \"{yourKeyId}\", \"relying_party_identifier\": \"{yourDomain}\" }" +payload = "{ "type": "webauthn_roaming", "name": "WebAuthn with security keys", "public_key": "{yourPublicKey}", "key_id": "{yourKeyId}", "relying_party_identifier": "{yourDomain}" }" headers = { 'authorization': "Bearer {yourMgmtApiAccessToken}" } @@ -1198,8 +1224,10 @@ conn.request("POST", "%7ByourDomain%7D/api/v2/users/%7BuserId%7D/authentication- res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -1211,11 +1239,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["authorization"] = 'Bearer {yourMgmtApiAccessToken}' -request.body = "{ \"type\": \"webauthn_roaming\", \"name\": \"WebAuthn with security keys\", \"public_key\": \"{yourPublicKey}\", \"key_id\": \"{yourKeyId}\", \"relying_party_identifier\": \"{yourDomain}\" }" +request.body = "{ "type": "webauthn_roaming", "name": "WebAuthn with security keys", "public_key": "{yourPublicKey}", "key_id": "{yourKeyId}", "relying_party_identifier": "{yourDomain}" }" response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer {yourMgmtApiAccessToken}"] let parameters = [ @@ -1245,20 +1275,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + #### 応答 @@ -1286,7 +1305,7 @@ Management APIは、有効な各要求に対して、JSON形式の応答を返 以下の要求はユーザーについて、既存のすべての認証方法を置き換えます。 - + ```bash cURL lines curl --request PUT \ --url https://%7ByourDomain%7D/api/v2/users/%7BuserId%7D/authentication-methods \ @@ -1486,7 +1505,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + ### 応答 @@ -1521,7 +1540,7 @@ Management APIは、有効な各要求に対して、JSON形式の応答を返 以下の要求は、特定の認証方法のIDに基づいて、ユーザーの1つの認証方法を更新します。 - + ```bash cURL lines curl --request PATCH \ --url https://%7ByourDomain%7D/api/v2/users/%7BuserId%7D/authentication-methods/%7BauthenticationMethodId%7D \ @@ -1707,7 +1726,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + ### 応答 @@ -1741,7 +1760,7 @@ Management APIは、有効な各要求に対して、JSON形式の応答を返 以下の要求はユーザーのすべての認証方法を削除します。 - + ```bash cURL lines curl --request DELETE \ --url https://%7ByourDomain%7D/api/v2/users/%7BuserId%7D/authentication-methods \ @@ -1908,7 +1927,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + ### 応答 @@ -1922,7 +1941,7 @@ Management APIは、有効な各要求に対して、ステータスコード`20 以下の要求は、指定された認証方法のIDに基づいて、ユーザーの1つの認証方法を削除します。 - + ```bash cURL lines curl --request DELETE \ --url https://%7ByourDomain%7D/api/v2/users/%7BuserId%7D/authentication-methods/%7BauthenticationMethodId%7D \ @@ -2089,7 +2108,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + ### 応答 diff --git a/main/docs/ja-jp/secure/multi-factor-authentication/manage-mfa-auth0-apis/manage-authenticator-factors-mfa-api.mdx b/main/docs/ja-jp/secure/multi-factor-authentication/manage-mfa-auth0-apis/manage-authenticator-factors-mfa-api.mdx index 597e10dfe..89388a931 100644 --- a/main/docs/ja-jp/secure/multi-factor-authentication/manage-mfa-auth0-apis/manage-authenticator-factors-mfa-api.mdx +++ b/main/docs/ja-jp/secure/multi-factor-authentication/manage-mfa-auth0-apis/manage-authenticator-factors-mfa-api.mdx @@ -10,6 +10,7 @@ permalink: "manage-authenticator-factors-mfa-api" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; @@ -75,14 +76,20 @@ MFAオーディエンスのトークンを要求する際、以下のスコー ## Authenticatorのリスト -export const codeExample1 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/mfa/authenticators' \ - --header 'authorization: Bearer MFA_TOKEN'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/mfa/authenticators"); + --header 'authorization: Bearer MFA_TOKEN' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/mfa/authenticators"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer MFA_TOKEN"); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -106,11 +113,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.get("https://{yourDomain}/mfa/authenticators") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/mfa/authenticators") .header("authorization", "Bearer MFA_TOKEN") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -122,8 +133,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MFA_TOKEN" }; @@ -143,8 +156,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/mfa/authenticators", @@ -168,8 +183,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -180,8 +197,10 @@ conn.request("GET", "/{yourDomain}/mfa/authenticators", headers=headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -195,8 +214,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer MFA_TOKEN' response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer MFA_TOKEN"] @@ -216,20 +237,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + 応答にAuthenticatorの種類に関する情報が含まれています。 @@ -298,14 +308,20 @@ Authenticatorを異なる要素で登録する方法については、以下の Authenticatorのリストのために`mfa_token`を使用した場合、Authenticatorを削除するために、[ユーザーは、MFAを完了させて](https://auth0.com/docs/ja-jp/api/authentication/muti-factor-authentication/verify-mfa-with-otp)、`https://{yourDomain}/mfa/`のオーディエンスのアクセストークンを取得する必要があります。 -export const codeExample11 = `curl --request DELETE \ + +```bash cURL +curl --request DELETE \ --url 'https://{yourDomain}/mfa/authenticators/AUTHENTICATOR_ID' \ - --header 'authorization: Bearer ACCESS_TOKEN'`; -export const codeExample12 = `var client = new RestClient("https://{yourDomain}/mfa/authenticators/AUTHENTICATOR_ID"); + --header 'authorization: Bearer ACCESS_TOKEN' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/mfa/authenticators/AUTHENTICATOR_ID"); var request = new RestRequest(Method.DELETE); request.AddHeader("authorization", "Bearer ACCESS_TOKEN"); -IRestResponse response = client.Execute(request);`; -export const codeExample13 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -329,11 +345,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample14 = `HttpResponse response = Unirest.delete("https://{yourDomain}/mfa/authenticators/AUTHENTICATOR_ID") +} +``` +```java Java +HttpResponse response = Unirest.delete("https://{yourDomain}/mfa/authenticators/AUTHENTICATOR_ID") .header("authorization", "Bearer ACCESS_TOKEN") - .asString();`; -export const codeExample15 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'DELETE', @@ -345,8 +365,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample16 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer ACCESS_TOKEN" }; @@ -366,8 +388,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/mfa/authenticators/AUTHENTICATOR_ID", @@ -391,8 +415,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -403,8 +429,10 @@ conn.request("DELETE", "/{yourDomain}/mfa/authenticators/AUTHENTICATOR_ID", head res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -418,8 +446,10 @@ request = Net::HTTP::Delete.new(url) request["authorization"] = 'Bearer ACCESS_TOKEN' response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer ACCESS_TOKEN"] @@ -439,20 +469,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + Authenticatorが削除されると、204応答が返されます。 @@ -484,14 +503,20 @@ Authenticatorを削除する際、Authenticatorの種類に応じて以下のア ## 復旧コードを再生成する -export const codeExample21 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/api/v2/users/USER_ID/recovery-code-regeneration' \ - --header 'authorization: Bearer MANAGEMENT_API_TOKEN'`; -export const codeExample22 = `var client = new RestClient("https://{yourDomain}/api/v2/users/USER_ID/recovery-code-regeneration"); + --header 'authorization: Bearer MANAGEMENT_API_TOKEN' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users/USER_ID/recovery-code-regeneration"); var request = new RestRequest(Method.POST); request.AddHeader("authorization", "Bearer MANAGEMENT_API_TOKEN"); -IRestResponse response = client.Execute(request);`; -export const codeExample23 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -515,11 +540,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample24 = `HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/users/USER_ID/recovery-code-regeneration") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/users/USER_ID/recovery-code-regeneration") .header("authorization", "Bearer MANAGEMENT_API_TOKEN") - .asString();`; -export const codeExample25 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -531,8 +560,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample26 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MANAGEMENT_API_TOKEN" }; @@ -552,8 +583,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample27 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users/USER_ID/recovery-code-regeneration", @@ -577,8 +610,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample28 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -589,8 +624,10 @@ conn.request("POST", "/{yourDomain}/api/v2/users/USER_ID/recovery-code-regenerat res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample29 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -604,8 +641,10 @@ request = Net::HTTP::Post.new(url) request["authorization"] = 'Bearer MANAGEMENT_API_TOKEN' response = http.request(request) -puts response.read_body`; -export const codeExample30 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer MANAGEMENT_API_TOKEN"] @@ -625,20 +664,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + 新しい復旧コードが生成され、エンドユーザーはそれをキャプチャする必要があります。例: diff --git a/main/docs/ja-jp/secure/multi-factor-authentication/multi-factor-authentication-factors/configure-sms-voice-notifications-mfa.mdx b/main/docs/ja-jp/secure/multi-factor-authentication/multi-factor-authentication-factors/configure-sms-voice-notifications-mfa.mdx index 57f44b2c8..0b3f6197d 100644 --- a/main/docs/ja-jp/secure/multi-factor-authentication/multi-factor-authentication-factors/configure-sms-voice-notifications-mfa.mdx +++ b/main/docs/ja-jp/secure/multi-factor-authentication/multi-factor-authentication-factors/configure-sms-voice-notifications-mfa.mdx @@ -10,6 +10,7 @@ permalink: "configure-sms-voice-notifications-mfa" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; @@ -82,18 +83,24 @@ SMSと音声メッセージテンプレートをカスタマイズすること Management APIを使用して、どのメッセージ配信方法を有効にするかを構成できます。その際に使用されるのが、`/api/v2/guardian/factors/phone/message-types`エンドポイントです。`message_types`パラメーターは、`["sms"]`、`["voice"]`、または`["sms", "voice"]`を使用できる配列です。APIを呼び出すには、`update:guardian_factors`スコープをベアラーに持つ[Management APIアクセストークン](/docs/ja-jp/secure/tokens/access-tokens/management-api-access-tokens)が必要です。 -export const codeExample1 = `curl --request PUT \ + +```bash cURL +curl --request PUT \ --url 'https://{yourDomain}/api/v2/guardian/factors/phone/message-types' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'content-type: application/json' \ ---data '{ "message_types": ["sms", "voice"] }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/guardian/factors/phone/message-types"); +--data '{ "message_types": ["sms", "voice"] }' +``` lines +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/guardian/factors/phone/message-types"); var request = new RestRequest(Method.PUT); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); -request.AddParameter("application/json", "{ \"message_types\": [\"sms\", \"voice\"] }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "message_types": ["sms", "voice"] }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" "strings" @@ -102,7 +109,7 @@ import ( ) func main() { url := "https://{yourDomain}/api/v2/guardian/factors/phone/message-types" -payload := strings.NewReader("{ \"message_types\": [\"sms\", \"voice\"] }") +payload := strings.NewReader("{ "message_types": ["sms", "voice"] }") req, _ := http.NewRequest("PUT", url, payload) req.Header.Add("content-type", "application/json") req.Header.Add("authorization", "Bearer MGMT_API_ACCESS_TOKEN") @@ -111,13 +118,17 @@ defer res.Body.Close() body, _ := ioutil.ReadAll(res.Body) fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.put("https://{yourDomain}/api/v2/guardian/factors/phone/message-types") +} +``` lines +```java Java +HttpResponse response = Unirest.put("https://{yourDomain}/api/v2/guardian/factors/phone/message-types") .header("content-type", "application/json") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") -.body("{ \"message_types\": [\"sms\", \"voice\"] }") -.asString();`; -export const codeExample5 = `var axios = require("axios").default; +.body("{ "message_types": ["sms", "voice"] }") +.asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PUT', url: 'https://{yourDomain}/api/v2/guardian/factors/phone/message-types', @@ -131,8 +142,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` lines +```obj-c Obj-C +#import NSDictionary \*headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN" }; NSDictionary \*parameters = @{ @"message_types": @[ @"sms", @"voice" ] }; @@ -153,8 +166,10 @@ NSHTTPURLResponse \*httpResponse = (NSHTTPURLResponse \*) response; NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/guardian/factors/phone/message-types", CURLOPT_RETURNTRANSFER => true, @@ -163,7 +178,7 @@ CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PUT", -CURLOPT_POSTFIELDS => "{ \"message_types\": [\"sms\", \"voice\"] }", +CURLOPT_POSTFIELDS => "{ "message_types": ["sms", "voice"] }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "content-type: application/json" @@ -176,10 +191,12 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` lines +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"message_types\": [\"sms\", \"voice\"] }" +payload = "{ "message_types": ["sms", "voice"] }" headers = { 'content-type': "application/json", 'authorization': "Bearer MGMT_API_ACCESS_TOKEN" @@ -187,8 +204,10 @@ headers = { conn.request("PUT", "/{yourDomain}/api/v2/guardian/factors/phone/message-types", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' url = URI("https://{yourDomain}/api/v2/guardian/factors/phone/message-types") @@ -198,10 +217,12 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Put.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' -request.body = "{ \"message_types\": [\"sms\", \"voice\"] }" +request.body = "{ "message_types": ["sms", "voice"] }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` lines +```swift Swift +import Foundation let headers = [ "content-type": "application/json", "authorization": "Bearer MGMT_API_ACCESS_TOKEN" @@ -223,20 +244,9 @@ let httpResponse = response as? HTTPURLResponse print(httpResponse) } }) -dataTask.resume()`; - - - lines - - lines - - lines - - lines - - lines - - +dataTask.resume() +``` + ## 統合されたSMSメッセージングプロバイダー diff --git a/main/docs/ja-jp/secure/security-guidance/data-security/denylist.mdx b/main/docs/ja-jp/secure/security-guidance/data-security/denylist.mdx index 49edc787d..620132544 100644 --- a/main/docs/ja-jp/secure/security-guidance/data-security/denylist.mdx +++ b/main/docs/ja-jp/secure/security-guidance/data-security/denylist.mdx @@ -10,26 +10,33 @@ permalink: "denylist" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; プライバシー上の理由により Auth0 データベースに保存すべきでないユーザーフィールドがある場合は、それらを拒否リストに追加できます。拒否リストに属性を追加するには、Management APIの更新接続エンドポイントに対して`PATCH`呼び出しを行います。 1. `/patch_connections_by_id`[エンドポイント](/docs/ja-jp/api/management/v2#!/Connections/patch_connections_by_id)にアクセスするための有効なアクセストークンを取得します。トークンには、`update:connections`スコープが含まれている必要があります。詳細については、[[Management API Access Tokens(Management APIのアクセストークン)]](/docs/ja-jp/secure/tokens/access-tokens/management-api-access-tokens)を参照してください。 2. アクセストークンと拒否する属性のリストを使用して、API を呼び出します。以下は、ethnicityとgenderの2つの属性を拒否するHTTP要求の例です。1つまたは2つの値のみを更新する場合は「マージ」が行われないため、optionsオブジェクトを取得してPATCH要求でオブジェクト全体を送信する必要があることに注意してください。 -export const codeExample1 = ` curl --request PATCH \ + +```bash cURL + curl --request PATCH \ --url 'https://{yourDomain}/api/v2/connections/YOUR_CONNECTION_ID' \ --header 'authorization: Bearer YOUR_TOKEN' \ --header 'content-type: application/json' \ --data '{"options": {"non_persistent_attrs": ["ethnicity", "gender"]}}' -`; -export const codeExample2 = ` var client = new RestClient("https://{yourDomain}/api/v2/connections/YOUR_CONNECTION_ID"); + +``` +```csharp C# + var client = new RestClient("https://{yourDomain}/api/v2/connections/YOUR_CONNECTION_ID"); var request = new RestRequest(Method.PATCH); request.AddHeader("authorization", "Bearer YOUR_TOKEN"); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\"options\": {\"non_persistent_attrs\": [\"ethnicity\", \"gender\"]}}", ParameterType.RequestBody); +request.AddParameter("application/json", "{"options": {"non_persistent_attrs": ["ethnicity", "gender"]}}", ParameterType.RequestBody); IRestResponse response = client.Execute(request); -`; -export const codeExample3 = ` package main + +``` +```go Go + package main import ( "fmt" @@ -42,7 +49,7 @@ func main() { url := "https://{yourDomain}/api/v2/connections/YOUR_CONNECTION_ID" - payload := strings.NewReader("{\"options\": {\"non_persistent_attrs\": [\"ethnicity\", \"gender\"]}}") + payload := strings.NewReader("{"options": {"non_persistent_attrs": ["ethnicity", "gender"]}}") req, _ := http.NewRequest("PATCH", url, payload) @@ -58,14 +65,18 @@ func main() { fmt.Println(string(body)) } -`; -export const codeExample4 = ` HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/connections/YOUR_CONNECTION_ID") + +``` +```java Java + HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/connections/YOUR_CONNECTION_ID") .header("authorization", "Bearer YOUR_TOKEN") .header("content-type", "application/json") - .body("{\"options\": {\"non_persistent_attrs\": [\"ethnicity\", \"gender\"]}}") + .body("{"options": {"non_persistent_attrs": ["ethnicity", "gender"]}}") .asString(); -`; -export const codeExample5 = ` var axios = require("axios").default; + +``` +```javascript Node.JS + var axios = require("axios").default; var options = { method: 'PATCH', @@ -79,8 +90,10 @@ axios.request(options).then(function (response) { }).catch(function (error) { console.error(error); }); -`; -export const codeExample6 = ` #import + +``` +```obj-c Obj-C + #import NSDictionary *headers = @{ @"authorization": @"Bearer YOUR_TOKEN", @"content-type": @"application/json" }; @@ -106,8 +119,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request } }]; [dataTask resume]; -`; -export const codeExample7 = ` $curl = curl_init(); + +``` +```php PHP + $curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/connections/YOUR_CONNECTION_ID", @@ -117,7 +132,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{\"options\": {\"non_persistent_attrs\": [\"ethnicity\", \"gender\"]}}", + CURLOPT_POSTFIELDS => "{"options": {"non_persistent_attrs": ["ethnicity", "gender"]}}", CURLOPT_HTTPHEADER => [ "authorization: Bearer YOUR_TOKEN", "content-type: application/json" @@ -134,12 +149,14 @@ if ($err) { } else { echo $response; } -`; -export const codeExample8 = ` import http.client + +``` +```python Python + import http.client conn = http.client.HTTPSConnection("") -payload = "{\"options\": {\"non_persistent_attrs\": [\"ethnicity\", \"gender\"]}}" +payload = "{"options": {"non_persistent_attrs": ["ethnicity", "gender"]}}" headers = { 'authorization': "Bearer YOUR_TOKEN", @@ -152,8 +169,10 @@ res = conn.getresponse() data = res.read() print(data.decode("utf-8")) -`; -export const codeExample9 = ` require 'uri' + +``` +```ruby Ruby + require 'uri' require 'net/http' require 'openssl' @@ -166,12 +185,14 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Patch.new(url) request["authorization"] = 'Bearer YOUR_TOKEN' request["content-type"] = 'application/json' -request.body = "{\"options\": {\"non_persistent_attrs\": [\"ethnicity\", \"gender\"]}}" +request.body = "{"options": {"non_persistent_attrs": ["ethnicity", "gender"]}}" response = http.request(request) puts response.read_body -`; -export const codeExample10 = ` import Foundation + +``` +```swift Swift + import Foundation let headers = [ "authorization": "Bearer YOUR_TOKEN", @@ -199,20 +220,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: }) dataTask.resume() -`; - - - - - - - - - - - - - + +``` + ここでは、 1. `{yourConnectionId}` は、これらの属性が拒否される[接続 ID](/docs/ja-jp/authenticate/identity-providers/locate-the-connection-id)です。 diff --git a/main/docs/ja-jp/secure/security-guidance/data-security/user-data-storage.mdx b/main/docs/ja-jp/secure/security-guidance/data-security/user-data-storage.mdx index 223af7c26..131ee4bb1 100644 --- a/main/docs/ja-jp/secure/security-guidance/data-security/user-data-storage.mdx +++ b/main/docs/ja-jp/secure/security-guidance/data-security/user-data-storage.mdx @@ -10,6 +10,7 @@ permalink: "user-data-storage" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; Auth0ではテナントのユーザー情報をホストされたクラウドデータベースに保存しますが、独自の外部カスタムデータベースにユーザーデータを保存することもできます。 @@ -79,7 +80,7 @@ function(user, context, callback){ 変更内容をデータベースに保存するため、アプリケーションがManagement APIの[ユーザー取得](/docs/api/management/v2#!/Users/get_users_by_id)エンドポイントを呼び出して適切なユーザーを識別します。 - + ```bash cURL lines curl --request GET \ --url https://%7ByourAccount%7D.auth0.com/api/v2/users/user_id \ @@ -215,22 +216,28 @@ print(httpResponse) }) dataTask.resume() ``` - + その後、[ユーザー更新](/docs/api/management/v2#!/Users/patch_users_by_id)エンドポイントが呼び出され、`user_metadata`フィールドが更新されます。 -export const codeExample1 = `curl --request PATCH \ + +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/users/user_id' \ --header 'authorization: Bearer {yourAccessToken}' \ --header 'content-type: application/json' \ ---data '{"user_metadata": {"displayName": "J-vald3z"}'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/users/user_id"); +--data '{"user_metadata": {"displayName": "J-vald3z"}' +``` lines +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users/user_id"); var request = new RestRequest(Method.PATCH); request.AddHeader("authorization", "Bearer {yourAccessToken}"); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\"user_metadata\": {\"displayName\": \"J-vald3z\"}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{"user_metadata": {"displayName": "J-vald3z"}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" "strings" @@ -239,7 +246,7 @@ import ( ) func main() { url := "https://{yourDomain}/api/v2/users/user_id" -payload := strings.NewReader("{\"user_metadata\": {\"displayName\": \"J-vald3z\"}") +payload := strings.NewReader("{"user_metadata": {"displayName": "J-vald3z"}") req, _ := http.NewRequest("PATCH", url, payload) req.Header.Add("authorization", "Bearer {yourAccessToken}") req.Header.Add("content-type", "application/json") @@ -248,13 +255,17 @@ defer res.Body.Close() body, _ := ioutil.ReadAll(res.Body) fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/users/user_id") +} +``` lines +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/users/user_id") .header("authorization", "Bearer {yourAccessToken}") .header("content-type", "application/json") -.body("{\"user_metadata\": {\"displayName\": \"J-vald3z\"}") -.asString();`; -export const codeExample5 = `var axios = require("axios").default; +.body("{"user_metadata": {"displayName": "J-vald3z"}") +.asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', url: 'https://{yourDomain}/api/v2/users/user_id', @@ -265,8 +276,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` lines +```obj-c Obj-C +#import NSDictionary \*headers = @{ @"authorization": @"Bearer {yourAccessToken}", @"content-type": @"application/json" }; NSData \*postData = [[NSData alloc] initWithData:[@"{"user_metadata": {"displayName": "J-vald3z"}" dataUsingEncoding:NSUTF8StringEncoding]]; @@ -286,8 +299,10 @@ NSHTTPURLResponse \*httpResponse = (NSHTTPURLResponse \*) response; NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users/user_id", CURLOPT_RETURNTRANSFER => true, @@ -296,7 +311,7 @@ CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", -CURLOPT_POSTFIELDS => "{\"user_metadata\": {\"displayName\": \"J-vald3z\"}", +CURLOPT_POSTFIELDS => "{"user_metadata": {"displayName": "J-vald3z"}", CURLOPT_HTTPHEADER => [ "authorization: Bearer {yourAccessToken}", "content-type: application/json" @@ -309,10 +324,12 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` lines +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"user_metadata\": {\"displayName\": \"J-vald3z\"}" +payload = "{"user_metadata": {"displayName": "J-vald3z"}" headers = { 'authorization': "Bearer {yourAccessToken}", 'content-type': "application/json" @@ -320,8 +337,10 @@ headers = { conn.request("PATCH", "/{yourDomain}/api/v2/users/user_id", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' url = URI("https://{yourDomain}/api/v2/users/user_id") @@ -331,10 +350,12 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Patch.new(url) request["authorization"] = 'Bearer {yourAccessToken}' request["content-type"] = 'application/json' -request.body = "{\"user_metadata\": {\"displayName\": \"J-vald3z\"}" +request.body = "{"user_metadata": {"displayName": "J-vald3z"}" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` lines +```swift Swift +import Foundation let headers = [ "authorization": "Bearer {yourAccessToken}", "content-type": "application/json" @@ -355,20 +376,9 @@ let httpResponse = response as? HTTPURLResponse print(httpResponse) } }) -dataTask.resume()`; - - - lines - - lines - - lines - - lines - - lines - - +dataTask.resume() +``` + `{yourAccessToken}`を[Management APIアクセストークン](/docs/api/management/v2/concepts/tokens)に置き換える必要があります。 diff --git a/main/docs/ja-jp/secure/tokens/access-tokens/get-access-tokens.mdx b/main/docs/ja-jp/secure/tokens/access-tokens/get-access-tokens.mdx index 159f96e81..655e5ae3e 100644 --- a/main/docs/ja-jp/secure/tokens/access-tokens/get-access-tokens.mdx +++ b/main/docs/ja-jp/secure/tokens/access-tokens/get-access-tokens.mdx @@ -10,6 +10,7 @@ permalink: "get-access-tokens" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; ユーザーを認証する際、APIにアクセスするには[アクセストークン](/docs/ja-jp/secure/tokens/access-tokens)を要求しなければなりません。 @@ -26,19 +27,25 @@ import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; #### トークンURLへのPOSTの例 -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=client_credentials \ --data client_id=YOUR_CLIENT_ID \ --data client_secret=YOUR_CLIENT_SECRET \ - --data audience=YOUR_API_IDENTIFIER`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data audience=YOUR_API_IDENTIFIER +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&audience=YOUR_API_IDENTIFIER", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -65,12 +72,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&audience=YOUR_API_IDENTIFIER") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -88,8 +99,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -115,8 +128,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -141,8 +156,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -155,8 +172,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -171,8 +190,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&audience=YOUR_API_IDENTIFIER" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -198,20 +219,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ##### パラメーター diff --git a/main/docs/ja-jp/secure/tokens/access-tokens/management-api-access-tokens/get-management-api-access-tokens-for-production.mdx b/main/docs/ja-jp/secure/tokens/access-tokens/management-api-access-tokens/get-management-api-access-tokens-for-production.mdx index 1af28f507..bde1c30b4 100644 --- a/main/docs/ja-jp/secure/tokens/access-tokens/management-api-access-tokens/get-management-api-access-tokens-for-production.mdx +++ b/main/docs/ja-jp/secure/tokens/access-tokens/management-api-access-tokens/get-management-api-access-tokens-for-production.mdx @@ -10,6 +10,7 @@ permalink: "get-management-api-access-tokens-for-production" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; 本番環境に定期的かつ頻繁な呼び出しを行うには、バックエンドでトークンを自動的に提供するプロセスを構築(して、擬似的に無期限のトークンに)します。 @@ -23,19 +24,25 @@ Auth0に response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=client_credentials&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&audience=https%3A%2F%2F{yourDomain}%2Fapi%2Fv2%2F") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -85,8 +96,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -112,8 +125,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -138,8 +153,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -152,8 +169,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -168,8 +187,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=client_credentials&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&audience=https%3A%2F%2F{yourDomain}%2Fapi%2Fv2%2F" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -195,20 +216,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + [アプリケーションの設定タブ](https://manage.auth0.com/#/applications/{yourClientId}/settings)で必ず``{yourClientSecret}``をクライアントシークレットに更新します。 @@ -267,7 +277,7 @@ HTTP呼び出しの代わりに、[node-auth0](https://www.npmjs.com/package/aut このトークンを使用するには、要求の`Authorization`ヘッダーに含めます。 - + ```bash cURL lines curl --request POST \ --url http:///%7BmgmtApiEndpoint%7D \ @@ -447,20 +457,26 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + たとえば、[すべてのアプリケーションを取得](/docs/ja-jp/api/management/v2#!/Clients/get_clients)するには、以下を使用します。 -export const codeExample11 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/clients' \ --header 'authorization: Bearer {yourAccessToken}' \ - --header 'content-type: application/json'`; -export const codeExample12 = `var client = new RestClient("https://{yourDomain}/api/v2/clients"); + --header 'content-type: application/json' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/clients"); var request = new RestRequest(Method.GET); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer {yourAccessToken}"); -IRestResponse response = client.Execute(request);`; -export const codeExample13 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -485,12 +501,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample14 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/clients") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/clients") .header("content-type", "application/json") .header("authorization", "Bearer {yourAccessToken}") - .asString();`; -export const codeExample15 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -502,8 +522,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample16 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer {yourAccessToken}" }; @@ -524,8 +546,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/clients", @@ -550,8 +574,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -565,8 +591,10 @@ conn.request("GET", "/{yourDomain}/api/v2/clients", headers=headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -581,8 +609,10 @@ request["content-type"] = 'application/json' request["authorization"] = 'Bearer {yourAccessToken}' response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -605,20 +635,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + diff --git a/main/docs/ja-jp/secure/tokens/refresh-tokens/get-refresh-tokens.mdx b/main/docs/ja-jp/secure/tokens/refresh-tokens/get-refresh-tokens.mdx index 44bc28c16..e7e667b07 100644 --- a/main/docs/ja-jp/secure/tokens/refresh-tokens/get-refresh-tokens.mdx +++ b/main/docs/ja-jp/secure/tokens/refresh-tokens/get-refresh-tokens.mdx @@ -10,6 +10,7 @@ permalink: "get-refresh-tokens" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; リフレッシュトークンを取得するには、`/authorize`エンドポイントを通じて認証要求を開始する際に、`offline_access`[スコープ](/docs/ja-jp/get-started/apis/scopes)を含める必要があります。必ずAPIでオフラインアクセスを開始してください。詳細については、「[API設定](/docs/ja-jp/get-started/apis/api-settings)」をお読みください。 @@ -29,20 +30,26 @@ export const codeExample1 = `https://{yourDomain}/authorize? ユーザー認証が成功すると、アプリケーションは`redirect_uri`にリダイレクトされ、URLの一部として`code`が付加されます(`{https://yourApp/callback}?code=BPPLN3Z4qCTvSNOy`)。`/oauth/token`エンドポイントを使用して、このコードをアクセストークンと交換できます。 -export const codeExample2 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=authorization_code \ --data 'client_id={yourClientId}' \ --data 'client_secret={yourClientSecret}' \ --data 'code={yourAuthorizationCode}' \ - --data 'redirect_uri={https://yourApp/callback}'`; -export const codeExample3 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data 'redirect_uri={https://yourApp/callback}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=authorization_code&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&code=%7ByourAuthorizationCode%7D&redirect_uri={https://yourApp/callback}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample4 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -69,12 +76,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample5 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=authorization_code&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&code=%7ByourAuthorizationCode%7D&redirect_uri={https://yourApp/callback}") - .asString();`; -export const codeExample6 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -93,8 +104,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample7 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -121,8 +134,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample8 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -147,8 +162,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample9 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -161,8 +178,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample10 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -177,8 +196,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=authorization_code&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&code=%7ByourAuthorizationCode%7D&redirect_uri={https://yourApp/callback}" response = http.request(request) -puts response.read_body`; -export const codeExample11 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -205,20 +226,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + 応答には、アクセストークンとリフレッシュトークンが含まれているはずです。 diff --git a/main/docs/ja-jp/secure/tokens/refresh-tokens/multi-resource-refresh-token/configure-and-implement-multi-resource-refresh-token.mdx b/main/docs/ja-jp/secure/tokens/refresh-tokens/multi-resource-refresh-token/configure-and-implement-multi-resource-refresh-token.mdx index ed2e8bcf0..9bd5c9d00 100644 --- a/main/docs/ja-jp/secure/tokens/refresh-tokens/multi-resource-refresh-token/configure-and-implement-multi-resource-refresh-token.mdx +++ b/main/docs/ja-jp/secure/tokens/refresh-tokens/multi-resource-refresh-token/configure-and-implement-multi-resource-refresh-token.mdx @@ -10,6 +10,7 @@ permalink: "configure-and-implement-multi-resource-refresh-token" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; @@ -52,20 +53,26 @@ The audience and scope properties must correspond to an existing application in For existing applications, make a PATCH call to the [Update a Client](/docs/ja-jp/api/management/v2/clients/patch-clients-by-id) endpoint. To create a new application, make a POST call to the [Create a Client](/docs/ja-jp/api/management/v2/clients/post-clients) endpoint: -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'authorization: Basic {yourApplicationCredentials}' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=refresh_token \ --data 'client_id={yourClientId}' \ - --data 'refresh_token={yourRefreshToken}'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data 'refresh_token={yourRefreshToken}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddHeader("authorization", "Basic {yourApplicationCredentials}"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=refresh_token&client_id={yourClientId}&refresh_token=%7ByourRefreshToken%7D", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -93,13 +100,17 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .header("authorization", "Basic {yourApplicationCredentials}") .body("grant_type=refresh_token&client_id={yourClientId}&refresh_token=%7ByourRefreshToken%7D") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -119,8 +130,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded", @"authorization": @"Basic {yourApplicationCredentials}" }; @@ -146,8 +159,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -173,8 +188,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -190,8 +207,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -207,8 +226,10 @@ request["authorization"] = 'Basic {yourApplicationCredentials}' request.body = "grant_type=refresh_token&client_id={yourClientId}&refresh_token=%7ByourRefreshToken%7D" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/x-www-form-urlencoded", @@ -236,20 +257,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + Sample response: @@ -296,19 +306,25 @@ If you do not receive a refresh token, confirm that: Once the refresh token is issued, you can request access tokens for any API and scopes defined in both the initial authentication and the MRRT policy. For example: -export const codeExample11 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=refresh_token \ --data 'client_id={yourClientId}' \ --data 'client_secret={yourClientSecret}' \ - --data 'refresh_token={yourRefreshToken}'`; -export const codeExample12 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data 'refresh_token={yourRefreshToken}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=refresh_token&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&refresh_token=%7ByourRefreshToken%7D", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample13 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -335,12 +351,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample14 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=refresh_token&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&refresh_token=%7ByourRefreshToken%7D") - .asString();`; -export const codeExample15 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -358,8 +378,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample16 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -385,8 +407,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -411,8 +435,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -425,8 +451,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -441,8 +469,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=refresh_token&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&refresh_token=%7ByourRefreshToken%7D" response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -468,20 +498,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +  To learn more, read [Use Refresh tokens](/docs/ja-jp/secure/tokens/refresh-tokens/use-refresh-tokens). diff --git a/main/docs/ja-jp/secure/tokens/refresh-tokens/revoke-refresh-tokens.mdx b/main/docs/ja-jp/secure/tokens/refresh-tokens/revoke-refresh-tokens.mdx index 861d8e0e5..9af2d6ea6 100644 --- a/main/docs/ja-jp/secure/tokens/refresh-tokens/revoke-refresh-tokens.mdx +++ b/main/docs/ja-jp/secure/tokens/refresh-tokens/revoke-refresh-tokens.mdx @@ -10,6 +10,7 @@ permalink: "revoke-refresh-tokens" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; リフレッシュトークンが侵害された場合に備えて、リフレッシュトークンを取り消すことができます。Auth0は、トークンが悪意のある攻撃者にさらされている可能性があるかのように、トークンの失効を処理します。 @@ -53,16 +54,22 @@ Dashboardを使用して、トークンを発行したアプリケーション `/oauth/revoke`エンドポイントは、特定のトークンだけでなく、許可全体を取り消します。リフレッシュトークンを取り消すには、`/api/v2/device-credentials`エンドポイントを使用します。APIは最初にアプリケーションの資格情報を検証し、次にトークンが取り消し要求を行ったアプリケーションに発行されたかどうかを確認します。この検証が失敗すると、要求は拒否され、アプリケーションにエラーが通知されます。次に、APIはトークンを無効にします。無効化は直ちに行われ、取り消し後はトークンを再び使用することはできません。取り消し要求ごとに、同じ承認許可に対して発行されたすべてのトークンが無効になります。 -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/revoke' \ --header 'content-type: application/json' \ - --data '{ "client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "token": "{yourRefreshToken}" }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/oauth/revoke"); + --data '{ "client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "token": "{yourRefreshToken}" }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/revoke"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{ \"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"token\": \"{yourRefreshToken}\" }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "token": "{yourRefreshToken}" }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -75,7 +82,7 @@ func main() { url := "https://{yourDomain}/oauth/revoke" - payload := strings.NewReader("{ \"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"token\": \"{yourRefreshToken}\" }") + payload := strings.NewReader("{ "client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "token": "{yourRefreshToken}" }") req, _ := http.NewRequest("POST", url, payload) @@ -89,12 +96,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/revoke") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/revoke") .header("content-type", "application/json") - .body("{ \"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"token\": \"{yourRefreshToken}\" }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "token": "{yourRefreshToken}" }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -111,8 +122,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json" }; NSDictionary *parameters = @{ @"client_id": @"{yourClientId}", @@ -138,8 +151,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/revoke", @@ -149,7 +164,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{ \"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"token\": \"{yourRefreshToken}\" }", + CURLOPT_POSTFIELDS => "{ "client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "token": "{yourRefreshToken}" }", CURLOPT_HTTPHEADER => [ "content-type: application/json" ], @@ -164,12 +179,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"token\": \"{yourRefreshToken}\" }" +payload = "{ "client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "token": "{yourRefreshToken}" }" headers = { 'content-type': "application/json" } @@ -178,8 +195,10 @@ conn.request("POST", "/{yourDomain}/oauth/revoke", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -191,11 +210,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["content-type"] = 'application/json' -request.body = "{ \"client_id\": \"{yourClientId}\", \"client_secret\": \"{yourClientSecret}\", \"token\": \"{yourRefreshToken}\" }" +request.body = "{ "client_id": "{yourClientId}", "client_secret": "{yourClientSecret}", "token": "{yourRefreshToken}" }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/json"] let parameters = [ @@ -223,20 +244,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ここでは、 diff --git a/main/docs/ja-jp/secure/tokens/refresh-tokens/use-refresh-tokens.mdx b/main/docs/ja-jp/secure/tokens/refresh-tokens/use-refresh-tokens.mdx index aad99e2c3..2be9e26ad 100644 --- a/main/docs/ja-jp/secure/tokens/refresh-tokens/use-refresh-tokens.mdx +++ b/main/docs/ja-jp/secure/tokens/refresh-tokens/use-refresh-tokens.mdx @@ -10,6 +10,7 @@ permalink: "use-refresh-tokens" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; リフレッシュトークンは、ユーザーに再認証を求めることなく、ユーザーの新しいアクセストークンおよび/またはIDトークンを要求するために使用します。 @@ -25,20 +26,26 @@ Authentication APIで使える認証方法の詳細は、「[認証方法](https ### 基本認証の使用 -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'authorization: Basic {yourApplicationCredentials}' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=refresh_token \ --data 'client_id={yourClientId}' \ - --data 'refresh_token={yourRefreshToken}'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data 'refresh_token={yourRefreshToken}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddHeader("authorization", "Basic {yourApplicationCredentials}"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=refresh_token&client_id={yourClientId}&refresh_token=%7ByourRefreshToken%7D", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -66,13 +73,17 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .header("authorization", "Basic {yourApplicationCredentials}") .body("grant_type=refresh_token&client_id={yourClientId}&refresh_token=%7ByourRefreshToken%7D") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -92,8 +103,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded", @"authorization": @"Basic {yourApplicationCredentials}" }; @@ -119,8 +132,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -146,8 +161,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -163,8 +180,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -180,8 +199,10 @@ request["authorization"] = 'Basic {yourApplicationCredentials}' request.body = "grant_type=refresh_token&client_id={yourClientId}&refresh_token=%7ByourRefreshToken%7D" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/x-www-form-urlencoded", @@ -209,36 +230,31 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ### POST認証の使用 -export const codeExample11 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=refresh_token \ --data 'client_id={yourClientId}' \ --data 'client_secret={yourClientSecret}' \ - --data 'refresh_token={yourRefreshToken}'`; -export const codeExample12 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data 'refresh_token={yourRefreshToken}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=refresh_token&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&refresh_token=%7ByourRefreshToken%7D", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample13 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -265,12 +281,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample14 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=refresh_token&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&refresh_token=%7ByourRefreshToken%7D") - .asString();`; -export const codeExample15 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -288,8 +308,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample16 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -315,8 +337,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -341,8 +365,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -355,8 +381,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -371,8 +399,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=refresh_token&client_id={yourClientId}&client_secret=%7ByourClientSecret%7D&refresh_token=%7ByourRefreshToken%7D" response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -398,20 +428,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ### パラメーターの定義 diff --git a/main/docs/ja-jp/troubleshoot/product-lifecycle/past-migrations/link-user-accounts-with-access-tokens-migration.mdx b/main/docs/ja-jp/troubleshoot/product-lifecycle/past-migrations/link-user-accounts-with-access-tokens-migration.mdx index 2afdd1767..c477c7cf0 100644 --- a/main/docs/ja-jp/troubleshoot/product-lifecycle/past-migrations/link-user-accounts-with-access-tokens-migration.mdx +++ b/main/docs/ja-jp/troubleshoot/product-lifecycle/past-migrations/link-user-accounts-with-access-tokens-migration.mdx @@ -10,6 +10,7 @@ permalink: "link-user-accounts-with-access-tokens-migration" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; 以前は、一部のケースで、IDトークンを使ってユーザーアカウントのリンクやリンク解除ができました。この機能は、廃止されます。今後は、すべてのケースでアクセストークンを使う必要があります。 @@ -261,18 +262,24 @@ export const codeExample5 = ` // get an Access Token ただ、ここで紹介している新しいメソッドはその代わりになります。APIでの認証には引き続き`update:users`スコープを含むアクセストークンを使用しますが、要求のペイロードでセカンダリのアカウントIDトークンを(`user_id`および`プロバイダー`の代わりに)送信できます。 -export const codeExample6 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/api/v2/users/PRIMARY_ACCOUNT_USER_ID/identities' \ --header 'authorization: Bearer ACCESS_TOKEN' \ --header 'content-type: application/json' \ - --data '{"link_with":"SECONDARY_ACCOUNT_ID_TOKEN"}'`; -export const codeExample7 = `var client = new RestClient("https://{yourDomain}/api/v2/users/PRIMARY_ACCOUNT_USER_ID/identities"); + --data '{"link_with":"SECONDARY_ACCOUNT_ID_TOKEN"}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users/PRIMARY_ACCOUNT_USER_ID/identities"); var request = new RestRequest(Method.POST); request.AddHeader("authorization", "Bearer ACCESS_TOKEN"); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\"link_with\":\"SECONDARY_ACCOUNT_ID_TOKEN\"}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample8 = `package main +request.AddParameter("application/json", "{"link_with":"SECONDARY_ACCOUNT_ID_TOKEN"}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -285,7 +292,7 @@ func main() { url := "https://{yourDomain}/api/v2/users/PRIMARY_ACCOUNT_USER_ID/identities" - payload := strings.NewReader("{\"link_with\":\"SECONDARY_ACCOUNT_ID_TOKEN\"}") + payload := strings.NewReader("{"link_with":"SECONDARY_ACCOUNT_ID_TOKEN"}") req, _ := http.NewRequest("POST", url, payload) @@ -300,13 +307,17 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample9 = `HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/users/PRIMARY_ACCOUNT_USER_ID/identities") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/users/PRIMARY_ACCOUNT_USER_ID/identities") .header("authorization", "Bearer ACCESS_TOKEN") .header("content-type", "application/json") - .body("{\"link_with\":\"SECONDARY_ACCOUNT_ID_TOKEN\"}") - .asString();`; -export const codeExample10 = `var axios = require("axios").default; + .body("{"link_with":"SECONDARY_ACCOUNT_ID_TOKEN"}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -319,8 +330,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample11 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer ACCESS_TOKEN", @"content-type": @"application/json" }; @@ -345,8 +358,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample12 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users/PRIMARY_ACCOUNT_USER_ID/identities", @@ -356,7 +371,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{\"link_with\":\"SECONDARY_ACCOUNT_ID_TOKEN\"}", + CURLOPT_POSTFIELDS => "{"link_with":"SECONDARY_ACCOUNT_ID_TOKEN"}", CURLOPT_HTTPHEADER => [ "authorization: Bearer ACCESS_TOKEN", "content-type: application/json" @@ -372,12 +387,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample13 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"link_with\":\"SECONDARY_ACCOUNT_ID_TOKEN\"}" +payload = "{"link_with":"SECONDARY_ACCOUNT_ID_TOKEN"}" headers = { 'authorization': "Bearer ACCESS_TOKEN", @@ -389,8 +406,10 @@ conn.request("POST", "/{yourDomain}/api/v2/users/PRIMARY_ACCOUNT_USER_ID/identit res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample14 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -403,11 +422,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["authorization"] = 'Bearer ACCESS_TOKEN' request["content-type"] = 'application/json' -request.body = "{\"link_with\":\"SECONDARY_ACCOUNT_ID_TOKEN\"}" +request.body = "{"link_with":"SECONDARY_ACCOUNT_ID_TOKEN"}" response = http.request(request) -puts response.read_body`; -export const codeExample15 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "authorization": "Bearer ACCESS_TOKEN", @@ -434,20 +455,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + 次のような条件があります。 diff --git a/main/docs/libraries/lock/lock-api-reference.mdx b/main/docs/libraries/lock/lock-api-reference.mdx index 214a7212c..e02538a3e 100644 --- a/main/docs/libraries/lock/lock-api-reference.mdx +++ b/main/docs/libraries/lock/lock-api-reference.mdx @@ -26,9 +26,9 @@ Lock has many methods, features, and configurable options. This reference is des Initializes a new instance of `Auth0Lock` configured with your application's `clientID` and your account's `domain` from your [Auth0](https://manage.auth0.com/#/) management dashboard. The third and optional parameter is an `options` object used to configure Lock for your application's needs. You can find this information at your [application settings](https://manage.auth0.com/#/applications). -* **clientId {String}**: Required parameter. Your application's clientId in Auth0. -* **domain {String}**: Required parameter. Your Auth0 domain. Usually your-account.auth0.com. -* **options {Object}**: Optional parameter. Allows for the configuration of Lock's appearance and behavior. See [the configuration options page](/docs/libraries/lock/lock-configuration) for details. +* **clientId `{String}`**: Required parameter. Your application's clientId in Auth0. +* **domain `{String}`**: Required parameter. Your Auth0 domain. Usually your-account.auth0.com. +* **options `{Object}`**: Optional parameter. Allows for the configuration of Lock's appearance and behavior. See [the configuration options page](/docs/libraries/lock/lock-configuration) for details. export const codeExample1 = `var Auth = (function() { diff --git a/main/docs/libraries/lock/lock-ui-customization.mdx b/main/docs/libraries/lock/lock-ui-customization.mdx index 9938124a9..526785649 100644 --- a/main/docs/libraries/lock/lock-ui-customization.mdx +++ b/main/docs/libraries/lock/lock-ui-customization.mdx @@ -53,7 +53,7 @@ var options = { }; ``` -#### authButtons {Object} +#### authButtons `{Object}` Allows the customization of buttons in Lock. Each custom connection whose button you desire to customize should be listed by name, each with their own set of parameters. The customizable parameters are listed below: diff --git a/main/docs/manage-users/access-control/configure-core-rbac/enable-role-based-access-control-for-apis.mdx b/main/docs/manage-users/access-control/configure-core-rbac/enable-role-based-access-control-for-apis.mdx index d895cf7de..41bc76f61 100644 --- a/main/docs/manage-users/access-control/configure-core-rbac/enable-role-based-access-control-for-apis.mdx +++ b/main/docs/manage-users/access-control/configure-core-rbac/enable-role-based-access-control-for-apis.mdx @@ -11,6 +11,8 @@ title: Enable Role-Based Access Control for APIs --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + You can enable [role-based access control (RBAC)](/docs/manage-users/access-control/rbac) using the Auth0 Dashboard or the Management API. This enables the API Authorization Core feature set. When RBAC is enabled, the `scope` claim of the access token includes an intersection of the requested permissions and the permissions assigned to the user, regardless of whether permissions are also included in the access token. When RBAC is disabled, an application can request any permission defined for the API, and the `scope` claim includes all requested permissions. @@ -41,20 +43,26 @@ If you configure any [Actions](/docs/customize/actions) that modify access token To enable RBAC using the Management API, make a PATCH request to the [Update a resource server endpoint](https://auth0.com/docs/api/management/v2/resource-servers/patch-resource-servers-by-id). In the PATCH request, set `enforce_policies` to `true`: -export const codeExample1 = `curl --request PATCH \ + +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/resource-servers/API_ID' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{ "enforce_policies": "true", "token_dialect": "TOKEN_DIALECT" }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/resource-servers/API_ID"); + --data '{ "enforce_policies": "true", "token_dialect": "TOKEN_DIALECT" }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/resource-servers/API_ID"); var request = new RestRequest(Method.PATCH); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{ \"enforce_policies\": \"true\", \"token_dialect\": \"TOKEN_DIALECT\" }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "enforce_policies": "true", "token_dialect": "TOKEN_DIALECT" }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -67,7 +75,7 @@ func main() { url := "https://{yourDomain}/api/v2/resource-servers/API_ID" - payload := strings.NewReader("{ \"enforce_policies\": \"true\", \"token_dialect\": \"TOKEN_DIALECT\" }") + payload := strings.NewReader("{ "enforce_policies": "true", "token_dialect": "TOKEN_DIALECT" }") req, _ := http.NewRequest("PATCH", url, payload) @@ -83,14 +91,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/resource-servers/API_ID") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/resource-servers/API_ID") .header("content-type", "application/json") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ \"enforce_policies\": \"true\", \"token_dialect\": \"TOKEN_DIALECT\" }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "enforce_policies": "true", "token_dialect": "TOKEN_DIALECT" }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -107,8 +119,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @@ -135,8 +149,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/resource-servers/API_ID", @@ -146,7 +162,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{ \"enforce_policies\": \"true\", \"token_dialect\": \"TOKEN_DIALECT\" }", + CURLOPT_POSTFIELDS => "{ "enforce_policies": "true", "token_dialect": "TOKEN_DIALECT" }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "cache-control: no-cache", @@ -163,12 +179,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"enforce_policies\": \"true\", \"token_dialect\": \"TOKEN_DIALECT\" }" +payload = "{ "enforce_policies": "true", "token_dialect": "TOKEN_DIALECT" }" headers = { 'content-type': "application/json", @@ -181,8 +199,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/resource-servers/API_ID", payload, h res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -196,11 +216,13 @@ request = Net::HTTP::Patch.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ \"enforce_policies\": \"true\", \"token_dialect\": \"TOKEN_DIALECT\" }" +request.body = "{ "enforce_policies": "true", "token_dialect": "TOKEN_DIALECT" }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -231,20 +253,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + Replace `API_ID`, `MGMT_API_ACCESS_TOKEN`, and `TOKEN_DIALECT` with their respective values, as shown in the following table: diff --git a/main/docs/manage-users/access-control/configure-core-rbac/rbac-users/assign-permissions-to-users.mdx b/main/docs/manage-users/access-control/configure-core-rbac/rbac-users/assign-permissions-to-users.mdx index a45380726..984239284 100644 --- a/main/docs/manage-users/access-control/configure-core-rbac/rbac-users/assign-permissions-to-users.mdx +++ b/main/docs/manage-users/access-control/configure-core-rbac/rbac-users/assign-permissions-to-users.mdx @@ -11,6 +11,8 @@ title: Assign Permissions to Users --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + You can assign [permissions](/docs/manage-users/access-control/rbac) to a user using the Auth0 Dashboard or the Management API. The assigned permissions can be used with the API Authorization Core feature set. @@ -47,20 +49,26 @@ You can also assign permissions to users from their individual profile page. Make a `POST` call to the [Assign User Permissions endpoint](https://auth0.com/docs/api/management/v2#!/Users/post_permissions). Be sure to replace `USER_ID`, `MGMT_API_ACCESS_TOKEN`, `API_IDENTIFIER`, and `PERMISSION_NAME` placeholder values with your user ID, Management API access token, API identifier(s), and permission name(s), respectively. -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/api/v2/users/USER_ID/permissions' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{ "permissions": [ { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" } ] }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/users/USER_ID/permissions"); + --data '{ "permissions": [ { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" } ] }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users/USER_ID/permissions"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{ \"permissions\": [ { \"resource_server_identifier\": \"API_IDENTIFIER\", \"permission_name\": \"PERMISSION_NAME\" }, { \"resource_server_identifier\": \"API_IDENTIFIER\", \"permission_name\": \"PERMISSION_NAME\" } ] }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "permissions": [ { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" } ] }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -73,7 +81,7 @@ func main() { url := "https://{yourDomain}/api/v2/users/USER_ID/permissions" - payload := strings.NewReader("{ \"permissions\": [ { \"resource_server_identifier\": \"API_IDENTIFIER\", \"permission_name\": \"PERMISSION_NAME\" }, { \"resource_server_identifier\": \"API_IDENTIFIER\", \"permission_name\": \"PERMISSION_NAME\" } ] }") + payload := strings.NewReader("{ "permissions": [ { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" } ] }") req, _ := http.NewRequest("POST", url, payload) @@ -89,14 +97,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/users/USER_ID/permissions") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/users/USER_ID/permissions") .header("content-type", "application/json") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ \"permissions\": [ { \"resource_server_identifier\": \"API_IDENTIFIER\", \"permission_name\": \"PERMISSION_NAME\" }, { \"resource_server_identifier\": \"API_IDENTIFIER\", \"permission_name\": \"PERMISSION_NAME\" } ] }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "permissions": [ { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" } ] }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -124,8 +136,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @@ -151,8 +165,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users/USER_ID/permissions", @@ -162,7 +178,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{ \"permissions\": [ { \"resource_server_identifier\": \"API_IDENTIFIER\", \"permission_name\": \"PERMISSION_NAME\" }, { \"resource_server_identifier\": \"API_IDENTIFIER\", \"permission_name\": \"PERMISSION_NAME\" } ] }", + CURLOPT_POSTFIELDS => "{ "permissions": [ { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" } ] }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "cache-control: no-cache", @@ -179,12 +195,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"permissions\": [ { \"resource_server_identifier\": \"API_IDENTIFIER\", \"permission_name\": \"PERMISSION_NAME\" }, { \"resource_server_identifier\": \"API_IDENTIFIER\", \"permission_name\": \"PERMISSION_NAME\" } ] }" +payload = "{ "permissions": [ { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" } ] }" headers = { 'content-type': "application/json", @@ -197,8 +215,10 @@ conn.request("POST", "/{yourDomain}/api/v2/users/USER_ID/permissions", payload, res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -212,11 +232,13 @@ request = Net::HTTP::Post.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ \"permissions\": [ { \"resource_server_identifier\": \"API_IDENTIFIER\", \"permission_name\": \"PERMISSION_NAME\" }, { \"resource_server_identifier\": \"API_IDENTIFIER\", \"permission_name\": \"PERMISSION_NAME\" } ] }" +request.body = "{ "permissions": [ { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" } ] }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -253,20 +275,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + | Value | Description | | --- | --- | diff --git a/main/docs/manage-users/access-control/configure-core-rbac/rbac-users/assign-roles-to-users.mdx b/main/docs/manage-users/access-control/configure-core-rbac/rbac-users/assign-roles-to-users.mdx index 2cf873c11..1fc2dd314 100644 --- a/main/docs/manage-users/access-control/configure-core-rbac/rbac-users/assign-roles-to-users.mdx +++ b/main/docs/manage-users/access-control/configure-core-rbac/rbac-users/assign-roles-to-users.mdx @@ -11,6 +11,8 @@ title: Assign Roles to Users --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + You can assign [roles](/docs/manage-users/access-control/rbac) to a user using the Auth0 Dashboard or the Management API. The assigned roles can be used with the API Authorization Core feature set. ## Prerequisites @@ -42,20 +44,26 @@ You can also assign roles to users from their individual profile page. Make a `POST` call to the [Assign User Roles endpoint](https://auth0.com/docs/api/management/v2#!/Users/post_user_roles). Be sure to replace `USER_ID`, `MGMT_API_ACCESS_TOKEN`, and `ROLE_ID` placeholder values with your user ID, Management API access token, and role ID(s), respectively. -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/api/v2/users/USER_ID/roles' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{ "roles": [ "ROLE_ID", "ROLE_ID" ] }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/users/USER_ID/roles"); + --data '{ "roles": [ "ROLE_ID", "ROLE_ID" ] }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users/USER_ID/roles"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{ \"roles\": [ \"ROLE_ID\", \"ROLE_ID\" ] }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "roles": [ "ROLE_ID", "ROLE_ID" ] }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -68,7 +76,7 @@ func main() { url := "https://{yourDomain}/api/v2/users/USER_ID/roles" - payload := strings.NewReader("{ \"roles\": [ \"ROLE_ID\", \"ROLE_ID\" ] }") + payload := strings.NewReader("{ "roles": [ "ROLE_ID", "ROLE_ID" ] }") req, _ := http.NewRequest("POST", url, payload) @@ -84,14 +92,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/users/USER_ID/roles") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/users/USER_ID/roles") .header("content-type", "application/json") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ \"roles\": [ \"ROLE_ID\", \"ROLE_ID\" ] }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "roles": [ "ROLE_ID", "ROLE_ID" ] }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -108,8 +120,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @@ -135,8 +149,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users/USER_ID/roles", @@ -146,7 +162,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{ \"roles\": [ \"ROLE_ID\", \"ROLE_ID\" ] }", + CURLOPT_POSTFIELDS => "{ "roles": [ "ROLE_ID", "ROLE_ID" ] }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "cache-control: no-cache", @@ -163,12 +179,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"roles\": [ \"ROLE_ID\", \"ROLE_ID\" ] }" +payload = "{ "roles": [ "ROLE_ID", "ROLE_ID" ] }" headers = { 'content-type': "application/json", @@ -181,8 +199,10 @@ conn.request("POST", "/{yourDomain}/api/v2/users/USER_ID/roles", payload, header res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -196,11 +216,13 @@ request = Net::HTTP::Post.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ \"roles\": [ \"ROLE_ID\", \"ROLE_ID\" ] }" +request.body = "{ "roles": [ "ROLE_ID", "ROLE_ID" ] }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -228,20 +250,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + | Value | Description | | --- | --- | diff --git a/main/docs/manage-users/access-control/configure-core-rbac/rbac-users/remove-permissions-from-users.mdx b/main/docs/manage-users/access-control/configure-core-rbac/rbac-users/remove-permissions-from-users.mdx index 7eb1eafbc..12d1f2608 100644 --- a/main/docs/manage-users/access-control/configure-core-rbac/rbac-users/remove-permissions-from-users.mdx +++ b/main/docs/manage-users/access-control/configure-core-rbac/rbac-users/remove-permissions-from-users.mdx @@ -11,6 +11,8 @@ title: Remove Permissions from Users --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + You can remove the permissions directly assigned to a user using the Auth0 Dashboard or the Management API. The assigned permissions are used with the API Authorization Core feature set. To learn more, read [Role-Based Access Control](/docs/manage-users/access-control/rbac). ## Prerequisites @@ -28,20 +30,26 @@ For role-based access control (RBAC) to work properly, you must enable it for yo Make a `DELETE` call to the [Delete User Permissions endpoint](https://auth0.com/docs/api/management/v2#!/Users/delete_permissions). Be sure to replace `USER_ID`, `MGMT_API_ACCESS_TOKEN`, `API_ID`, and `PERMISSION_NAME` placeholder values with your user ID, Management API access token, API ID(s), and permission name(s), respectively. -export const codeExample1 = `curl --request DELETE \ + +```bash cURL +curl --request DELETE \ --url 'https://{yourDomain}/api/v2/users/USER_ID/permissions' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{ "permissions": [ { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" } ] }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/users/USER_ID/permissions"); + --data '{ "permissions": [ { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" } ] }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users/USER_ID/permissions"); var request = new RestRequest(Method.DELETE); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{ \"permissions\": [ { \"resource_server_identifier\": \"API_ID\", \"permission_name\": \"PERMISSION_NAME\" }, { \"resource_server_identifier\": \"API_ID\", \"permission_name\": \"PERMISSION_NAME\" } ] }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "permissions": [ { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" } ] }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -54,7 +62,7 @@ func main() { url := "https://{yourDomain}/api/v2/users/USER_ID/permissions" - payload := strings.NewReader("{ \"permissions\": [ { \"resource_server_identifier\": \"API_ID\", \"permission_name\": \"PERMISSION_NAME\" }, { \"resource_server_identifier\": \"API_ID\", \"permission_name\": \"PERMISSION_NAME\" } ] }") + payload := strings.NewReader("{ "permissions": [ { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" } ] }") req, _ := http.NewRequest("DELETE", url, payload) @@ -70,14 +78,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.delete("https://{yourDomain}/api/v2/users/USER_ID/permissions") +} +``` +```java Java +HttpResponse response = Unirest.delete("https://{yourDomain}/api/v2/users/USER_ID/permissions") .header("content-type", "application/json") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ \"permissions\": [ { \"resource_server_identifier\": \"API_ID\", \"permission_name\": \"PERMISSION_NAME\" }, { \"resource_server_identifier\": \"API_ID\", \"permission_name\": \"PERMISSION_NAME\" } ] }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "permissions": [ { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" } ] }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'DELETE', @@ -99,8 +111,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @@ -126,8 +140,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users/USER_ID/permissions", @@ -137,7 +153,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "DELETE", - CURLOPT_POSTFIELDS => "{ \"permissions\": [ { \"resource_server_identifier\": \"API_ID\", \"permission_name\": \"PERMISSION_NAME\" }, { \"resource_server_identifier\": \"API_ID\", \"permission_name\": \"PERMISSION_NAME\" } ] }", + CURLOPT_POSTFIELDS => "{ "permissions": [ { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" } ] }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "cache-control: no-cache", @@ -154,12 +170,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"permissions\": [ { \"resource_server_identifier\": \"API_ID\", \"permission_name\": \"PERMISSION_NAME\" }, { \"resource_server_identifier\": \"API_ID\", \"permission_name\": \"PERMISSION_NAME\" } ] }" +payload = "{ "permissions": [ { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" } ] }" headers = { 'content-type': "application/json", @@ -172,8 +190,10 @@ conn.request("DELETE", "/{yourDomain}/api/v2/users/USER_ID/permissions", payload res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -187,11 +207,13 @@ request = Net::HTTP::Delete.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ \"permissions\": [ { \"resource_server_identifier\": \"API_ID\", \"permission_name\": \"PERMISSION_NAME\" }, { \"resource_server_identifier\": \"API_ID\", \"permission_name\": \"PERMISSION_NAME\" } ] }" +request.body = "{ "permissions": [ { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" } ] }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -228,20 +250,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + | Value | Description | | --- | --- | diff --git a/main/docs/manage-users/access-control/configure-core-rbac/rbac-users/remove-roles-from-users.mdx b/main/docs/manage-users/access-control/configure-core-rbac/rbac-users/remove-roles-from-users.mdx index b93be57eb..f49cbc3ad 100644 --- a/main/docs/manage-users/access-control/configure-core-rbac/rbac-users/remove-roles-from-users.mdx +++ b/main/docs/manage-users/access-control/configure-core-rbac/rbac-users/remove-roles-from-users.mdx @@ -11,6 +11,8 @@ title: Remove Roles from Users --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + You can remove the [roles](/docs/manage-users/access-control/rbac) assigned to a user using the Auth0 Dashboard or the Management API. The assigned roles are used with the API Authorization Core feature set. ## Prerequisites @@ -26,20 +28,26 @@ For role-based access control (RBAC) to work properly, you must enable it for yo Make a `DELETE` call to the [Delete User Roles endpoint](https://auth0.com/docs/api/management/v2#!/Users/delete_user_roles). Be sure to replace `USER_ID`, `MGMT_API_ACCESS_TOKEN`, and `ROLE_ID` placeholder values with your user ID, Management API access token, and role ID(s), respectively. -export const codeExample1 = `curl --request DELETE \ + +```bash cURL +curl --request DELETE \ --url 'https://{yourDomain}/api/v2/users/USER_ID/roles' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{ "roles": [ "ROLE_ID", "ROLE_ID" ] }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/users/USER_ID/roles"); + --data '{ "roles": [ "ROLE_ID", "ROLE_ID" ] }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users/USER_ID/roles"); var request = new RestRequest(Method.DELETE); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{ \"roles\": [ \"ROLE_ID\", \"ROLE_ID\" ] }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "roles": [ "ROLE_ID", "ROLE_ID" ] }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -52,7 +60,7 @@ func main() { url := "https://{yourDomain}/api/v2/users/USER_ID/roles" - payload := strings.NewReader("{ \"roles\": [ \"ROLE_ID\", \"ROLE_ID\" ] }") + payload := strings.NewReader("{ "roles": [ "ROLE_ID", "ROLE_ID" ] }") req, _ := http.NewRequest("DELETE", url, payload) @@ -68,14 +76,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.delete("https://{yourDomain}/api/v2/users/USER_ID/roles") +} +``` +```java Java +HttpResponse response = Unirest.delete("https://{yourDomain}/api/v2/users/USER_ID/roles") .header("content-type", "application/json") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ \"roles\": [ \"ROLE_ID\", \"ROLE_ID\" ] }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "roles": [ "ROLE_ID", "ROLE_ID" ] }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'DELETE', @@ -92,8 +104,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @@ -119,8 +133,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users/USER_ID/roles", @@ -130,7 +146,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "DELETE", - CURLOPT_POSTFIELDS => "{ \"roles\": [ \"ROLE_ID\", \"ROLE_ID\" ] }", + CURLOPT_POSTFIELDS => "{ "roles": [ "ROLE_ID", "ROLE_ID" ] }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "cache-control: no-cache", @@ -147,12 +163,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"roles\": [ \"ROLE_ID\", \"ROLE_ID\" ] }" +payload = "{ "roles": [ "ROLE_ID", "ROLE_ID" ] }" headers = { 'content-type': "application/json", @@ -165,8 +183,10 @@ conn.request("DELETE", "/{yourDomain}/api/v2/users/USER_ID/roles", payload, head res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -180,11 +200,13 @@ request = Net::HTTP::Delete.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ \"roles\": [ \"ROLE_ID\", \"ROLE_ID\" ] }" +request.body = "{ "roles": [ "ROLE_ID", "ROLE_ID" ] }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -212,20 +234,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + | Value | Description | | --- | --- | diff --git a/main/docs/manage-users/access-control/configure-core-rbac/rbac-users/view-user-permissions.mdx b/main/docs/manage-users/access-control/configure-core-rbac/rbac-users/view-user-permissions.mdx index 26cc462ea..6b04ce882 100644 --- a/main/docs/manage-users/access-control/configure-core-rbac/rbac-users/view-user-permissions.mdx +++ b/main/docs/manage-users/access-control/configure-core-rbac/rbac-users/view-user-permissions.mdx @@ -11,6 +11,8 @@ title: View User Permissions --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + You can view the [permissions](/docs/manage-users/access-control/rbac) assigned to a user using the Auth0 Dashboard. This task can also be performed using the Management API. The assigned permissions are used with the API Authorization Core feature set. ## Prerequisites @@ -37,14 +39,20 @@ The following information is displayed for each permission: Make a `GET` call to the [Get User Permissions endpoint](https://auth0.com/docs/api/management/v2#!/Users/get_permissions). Be sure to replace `USER_ID` and `MGMT_API_ACCESS_TOKEN` placeholder values with your user ID and Management API access token, respectively. -export const codeExample1 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/users/USER_ID/permissions' \ - --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/users/USER_ID/permissions"); + --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users/USER_ID/permissions"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -68,11 +76,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/users/USER_ID/permissions") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/users/USER_ID/permissions") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -84,8 +96,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN" }; @@ -105,8 +119,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users/USER_ID/permissions", @@ -130,8 +146,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -142,8 +160,10 @@ conn.request("GET", "/{yourDomain}/api/v2/users/USER_ID/permissions", headers=he res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -157,8 +177,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer MGMT_API_ACCESS_TOKEN"] @@ -178,20 +200,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + | Value | Description | | --- | --- | diff --git a/main/docs/manage-users/access-control/configure-core-rbac/rbac-users/view-user-roles.mdx b/main/docs/manage-users/access-control/configure-core-rbac/rbac-users/view-user-roles.mdx index 0df689165..d7a6617c4 100644 --- a/main/docs/manage-users/access-control/configure-core-rbac/rbac-users/view-user-roles.mdx +++ b/main/docs/manage-users/access-control/configure-core-rbac/rbac-users/view-user-roles.mdx @@ -11,6 +11,8 @@ title: View Roles Assigned to Users --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + You can view the [roles](/docs/manage-users/access-control/rbac) assigned to a user using Auth0's Dashboard. This task can also be performed using the Management API. The assigned roles are used with the API Authorization Core feature set. ## Prerequisites @@ -33,14 +35,20 @@ The following information is displayed for each role: Make a `GET` call to the [Get User Roles endpoint](https://auth0.com/docs/api/management/v2#!/Users/get_user_roles). Be sure to replace `USER_ID` and `MGMT_API_ACCESS_TOKEN` placeholder values with your user ID and Management API access token, respectively. -export const codeExample1 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/users/USER_ID/roles' \ - --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/users/USER_ID/roles"); + --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users/USER_ID/roles"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -64,11 +72,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/users/USER_ID/roles") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/users/USER_ID/roles") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -80,8 +92,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN" }; @@ -101,8 +115,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users/USER_ID/roles", @@ -126,8 +142,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -138,8 +156,10 @@ conn.request("GET", "/{yourDomain}/api/v2/users/USER_ID/roles", headers=headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -153,8 +173,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer MGMT_API_ACCESS_TOKEN"] @@ -174,20 +196,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + | Value | Description | | --- | --- | diff --git a/main/docs/manage-users/access-control/configure-core-rbac/roles/add-permissions-to-roles.mdx b/main/docs/manage-users/access-control/configure-core-rbac/roles/add-permissions-to-roles.mdx index 0a50e8ed7..bcacfac3d 100644 --- a/main/docs/manage-users/access-control/configure-core-rbac/roles/add-permissions-to-roles.mdx +++ b/main/docs/manage-users/access-control/configure-core-rbac/roles/add-permissions-to-roles.mdx @@ -11,6 +11,8 @@ title: Add Permissions to Roles --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + You can add permissions to [roles](/docs/manage-users/access-control/rbac) using the Auth0 Dashboard or the Management API. The roles and their permissions can be used with the API Authorization Core feature set. ## Prerequisites @@ -30,20 +32,26 @@ You can add permissions to [roles](/docs/manage-users/access-control/rbac) using Make a `POST` call to the [Add Role Permissions endpoint](https://auth0.com/docs/api/management/v2#!/Roles/post_role_permission_assignment). Be sure to replace `ROLE_ID`, `MGMT_API_ACCESS_TOKEN`, `API_IDENTIFIER`, and `PERMISSION_NAME` placeholder values with your role ID, Management API access token, API identifier (audience), and permission name(s), respectively. -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/api/v2/roles/ROLE_ID/permissions' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{ "permissions": [ { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" } ] }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/roles/ROLE_ID/permissions"); + --data '{ "permissions": [ { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" } ] }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/roles/ROLE_ID/permissions"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{ \"permissions\": [ { \"resource_server_identifier\": \"API_IDENTIFIER\", \"permission_name\": \"PERMISSION_NAME\" }, { \"resource_server_identifier\": \"API_IDENTIFIER\", \"permission_name\": \"PERMISSION_NAME\" } ] }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "permissions": [ { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" } ] }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -56,7 +64,7 @@ func main() { url := "https://{yourDomain}/api/v2/roles/ROLE_ID/permissions" - payload := strings.NewReader("{ \"permissions\": [ { \"resource_server_identifier\": \"API_IDENTIFIER\", \"permission_name\": \"PERMISSION_NAME\" }, { \"resource_server_identifier\": \"API_IDENTIFIER\", \"permission_name\": \"PERMISSION_NAME\" } ] }") + payload := strings.NewReader("{ "permissions": [ { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" } ] }") req, _ := http.NewRequest("POST", url, payload) @@ -72,14 +80,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/roles/ROLE_ID/permissions") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/roles/ROLE_ID/permissions") .header("content-type", "application/json") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ \"permissions\": [ { \"resource_server_identifier\": \"API_IDENTIFIER\", \"permission_name\": \"PERMISSION_NAME\" }, { \"resource_server_identifier\": \"API_IDENTIFIER\", \"permission_name\": \"PERMISSION_NAME\" } ] }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "permissions": [ { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" } ] }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -107,8 +119,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @@ -134,8 +148,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/roles/ROLE_ID/permissions", @@ -145,7 +161,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{ \"permissions\": [ { \"resource_server_identifier\": \"API_IDENTIFIER\", \"permission_name\": \"PERMISSION_NAME\" }, { \"resource_server_identifier\": \"API_IDENTIFIER\", \"permission_name\": \"PERMISSION_NAME\" } ] }", + CURLOPT_POSTFIELDS => "{ "permissions": [ { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" } ] }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "cache-control: no-cache", @@ -162,12 +178,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"permissions\": [ { \"resource_server_identifier\": \"API_IDENTIFIER\", \"permission_name\": \"PERMISSION_NAME\" }, { \"resource_server_identifier\": \"API_IDENTIFIER\", \"permission_name\": \"PERMISSION_NAME\" } ] }" +payload = "{ "permissions": [ { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" } ] }" headers = { 'content-type': "application/json", @@ -180,8 +198,10 @@ conn.request("POST", "/{yourDomain}/api/v2/roles/ROLE_ID/permissions", payload, res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -195,11 +215,13 @@ request = Net::HTTP::Post.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ \"permissions\": [ { \"resource_server_identifier\": \"API_IDENTIFIER\", \"permission_name\": \"PERMISSION_NAME\" }, { \"resource_server_identifier\": \"API_IDENTIFIER\", \"permission_name\": \"PERMISSION_NAME\" } ] }" +request.body = "{ "permissions": [ { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_IDENTIFIER", "permission_name": "PERMISSION_NAME" } ] }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -236,20 +258,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + | Value | Description | | --- | --- | diff --git a/main/docs/manage-users/access-control/configure-core-rbac/roles/create-roles.mdx b/main/docs/manage-users/access-control/configure-core-rbac/roles/create-roles.mdx index 2a105c83f..9718452db 100644 --- a/main/docs/manage-users/access-control/configure-core-rbac/roles/create-roles.mdx +++ b/main/docs/manage-users/access-control/configure-core-rbac/roles/create-roles.mdx @@ -11,6 +11,8 @@ title: Create Roles --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + You can create [roles](/docs/manage-users/access-control/rbac) using Auth0's Dashboard or the Management API. The roles can be used with the API Authorization Core feature set. ## Prerequisites @@ -28,20 +30,26 @@ You can create [roles](/docs/manage-users/access-control/rbac) using Auth0's Das Make a `POST` call to the [Create Role endpoint](https://auth0.com/docs/api/management/v2#!/Roles/post_roles). Be sure to replace `MGMT_API_ACCESS_TOKEN`, `ROLE_NAME`, and `ROLE_DESC` placeholder values with your Management API access token, role name, and role description, respectively. -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/api/v2/roles' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{ "name": "ROLE_NAME", "description": "ROLE_DESC" }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/roles"); + --data '{ "name": "ROLE_NAME", "description": "ROLE_DESC" }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/roles"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{ \"name\": \"ROLE_NAME\", \"description\": \"ROLE_DESC\" }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "name": "ROLE_NAME", "description": "ROLE_DESC" }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -54,7 +62,7 @@ func main() { url := "https://{yourDomain}/api/v2/roles" - payload := strings.NewReader("{ \"name\": \"ROLE_NAME\", \"description\": \"ROLE_DESC\" }") + payload := strings.NewReader("{ "name": "ROLE_NAME", "description": "ROLE_DESC" }") req, _ := http.NewRequest("POST", url, payload) @@ -70,14 +78,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/roles") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/roles") .header("content-type", "application/json") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ \"name\": \"ROLE_NAME\", \"description\": \"ROLE_DESC\" }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "name": "ROLE_NAME", "description": "ROLE_DESC" }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -94,8 +106,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @@ -122,8 +136,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/roles", @@ -133,7 +149,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{ \"name\": \"ROLE_NAME\", \"description\": \"ROLE_DESC\" }", + CURLOPT_POSTFIELDS => "{ "name": "ROLE_NAME", "description": "ROLE_DESC" }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "cache-control: no-cache", @@ -150,12 +166,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"name\": \"ROLE_NAME\", \"description\": \"ROLE_DESC\" }" +payload = "{ "name": "ROLE_NAME", "description": "ROLE_DESC" }" headers = { 'content-type': "application/json", @@ -168,8 +186,10 @@ conn.request("POST", "/{yourDomain}/api/v2/roles", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -183,11 +203,13 @@ request = Net::HTTP::Post.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ \"name\": \"ROLE_NAME\", \"description\": \"ROLE_DESC\" }" +request.body = "{ "name": "ROLE_NAME", "description": "ROLE_DESC" }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -218,20 +240,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + | **Value** | **Description** | | --- | --- | diff --git a/main/docs/manage-users/access-control/configure-core-rbac/roles/delete-roles.mdx b/main/docs/manage-users/access-control/configure-core-rbac/roles/delete-roles.mdx index 0f0194f05..e0bdec2da 100644 --- a/main/docs/manage-users/access-control/configure-core-rbac/roles/delete-roles.mdx +++ b/main/docs/manage-users/access-control/configure-core-rbac/roles/delete-roles.mdx @@ -11,6 +11,8 @@ title: Delete Roles --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + You can delete a [role](/docs/manage-users/access-control/rbac) using the Auth0 Dashboard or the Management API. Roles are used with the API Authorization Core feature set. For role-based access control (RBAC) to work properly, you must enable it for your API using either the Dashboard or the Management API. The Authorization Core functionality is different from the Authorization Extension. For a comparison, read [Authorization Core vs. Authorization Extension](/docs/manage-users/access-control/authorization-core-vs-authorization-extension). @@ -24,14 +26,20 @@ For role-based access control (RBAC) to work properly, you must enable it for yo Make a `DELETE` call to the [Delete Role endpoint](https://auth0.com/docs/api/management/v2#!/Roles/delete_roles_by_id). Be sure to replace `ROLE_ID` and `MGMT_API_ACCESS_TOKEN` placeholder values with your role ID and Management API access token, respectively. -export const codeExample1 = `curl --request DELETE \ + +```bash cURL +curl --request DELETE \ --url 'https://{yourDomain}/api/v2/roles/ROLE_ID' \ - --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/roles/ROLE_ID"); + --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/roles/ROLE_ID"); var request = new RestRequest(Method.DELETE); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -55,11 +63,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.delete("https://{yourDomain}/api/v2/roles/ROLE_ID") +} +``` +```java Java +HttpResponse response = Unirest.delete("https://{yourDomain}/api/v2/roles/ROLE_ID") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'DELETE', @@ -71,8 +83,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN" }; @@ -92,8 +106,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/roles/ROLE_ID", @@ -117,8 +133,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -129,8 +147,10 @@ conn.request("DELETE", "/{yourDomain}/api/v2/roles/ROLE_ID", headers=headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -144,8 +164,10 @@ request = Net::HTTP::Delete.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer MGMT_API_ACCESS_TOKEN"] @@ -165,20 +187,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + | Value | Description | | --- | --- | diff --git a/main/docs/manage-users/access-control/configure-core-rbac/roles/edit-role-definitions.mdx b/main/docs/manage-users/access-control/configure-core-rbac/roles/edit-role-definitions.mdx index b2e74cb30..952014652 100644 --- a/main/docs/manage-users/access-control/configure-core-rbac/roles/edit-role-definitions.mdx +++ b/main/docs/manage-users/access-control/configure-core-rbac/roles/edit-role-definitions.mdx @@ -11,6 +11,8 @@ title: Edit Role Definitions --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + You can edit a [role](/docs/manage-users/access-control/rbac) definition using the Auth0 Dashboard or the Management API. Roles are used with the API Authorization Core feature set. ## Prerequisite @@ -26,20 +28,26 @@ For role-based access control (RBAC) to work properly, you must enable it for yo Make a `PATCH` call to the [Update Role endpoint](https://auth0.com/docs/api/management/v2#!/Roles/patch_roles_by_id). Be sure to replace `ROLE_ID`, `MGMT_API_ACCESS_TOKEN`, `ROLE_NAME`, and `ROLE_DESC` placeholder values with your role ID, Management API access token, role name, and role description, respectively. -export const codeExample1 = `curl --request PATCH \ + +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/roles/ROLE_ID' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{ "name": "ROLE_NAME", "description": "ROLE_DESC" }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/roles/ROLE_ID"); + --data '{ "name": "ROLE_NAME", "description": "ROLE_DESC" }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/roles/ROLE_ID"); var request = new RestRequest(Method.PATCH); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{ \"name\": \"ROLE_NAME\", \"description\": \"ROLE_DESC\" }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "name": "ROLE_NAME", "description": "ROLE_DESC" }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -52,7 +60,7 @@ func main() { url := "https://{yourDomain}/api/v2/roles/ROLE_ID" - payload := strings.NewReader("{ \"name\": \"ROLE_NAME\", \"description\": \"ROLE_DESC\" }") + payload := strings.NewReader("{ "name": "ROLE_NAME", "description": "ROLE_DESC" }") req, _ := http.NewRequest("PATCH", url, payload) @@ -68,14 +76,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/roles/ROLE_ID") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/roles/ROLE_ID") .header("content-type", "application/json") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ \"name\": \"ROLE_NAME\", \"description\": \"ROLE_DESC\" }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "name": "ROLE_NAME", "description": "ROLE_DESC" }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -92,8 +104,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @@ -120,8 +134,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/roles/ROLE_ID", @@ -131,7 +147,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{ \"name\": \"ROLE_NAME\", \"description\": \"ROLE_DESC\" }", + CURLOPT_POSTFIELDS => "{ "name": "ROLE_NAME", "description": "ROLE_DESC" }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "cache-control: no-cache", @@ -148,12 +164,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"name\": \"ROLE_NAME\", \"description\": \"ROLE_DESC\" }" +payload = "{ "name": "ROLE_NAME", "description": "ROLE_DESC" }" headers = { 'content-type': "application/json", @@ -166,8 +184,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/roles/ROLE_ID", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -181,11 +201,13 @@ request = Net::HTTP::Patch.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ \"name\": \"ROLE_NAME\", \"description\": \"ROLE_DESC\" }" +request.body = "{ "name": "ROLE_NAME", "description": "ROLE_DESC" }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -216,20 +238,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + | Value | Description | | --- | --- | diff --git a/main/docs/manage-users/access-control/configure-core-rbac/roles/remove-permissions-from-roles.mdx b/main/docs/manage-users/access-control/configure-core-rbac/roles/remove-permissions-from-roles.mdx index 46839573e..083766fb9 100644 --- a/main/docs/manage-users/access-control/configure-core-rbac/roles/remove-permissions-from-roles.mdx +++ b/main/docs/manage-users/access-control/configure-core-rbac/roles/remove-permissions-from-roles.mdx @@ -11,6 +11,8 @@ title: Remove Permissions from Roles --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + You can remove the [permissions](/docs/manage-users/access-control/rbac) assigned to a role using the Auth0 Dashboard or the Management API. The assigned permissions and roles are used with the API Authorization Core feature set. ## Prerequisite @@ -26,20 +28,26 @@ For role-based access control (RBAC) to work properly, you must enable it for yo Make a `DELETE` call to the [Delete Role Permissions endpoint](https://auth0.com/docs/api/management/v2#!/Roles/delete_role_permission_assignment). Be sure to replace `ROLE_ID`, `MGMT_API_ACCESS_TOKEN`, `API_ID`, and `PERMISSION_NAME` placeholder values with your role ID, Management API access token, API ID(s), and permission name(s), respectively. -export const codeExample1 = `curl --request DELETE \ + +```bash cURL +curl --request DELETE \ --url 'https://{yourDomain}/api/v2/roles/ROLE_ID/permissions' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{ "permissions": [ { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" } ] }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/roles/ROLE_ID/permissions"); + --data '{ "permissions": [ { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" } ] }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/roles/ROLE_ID/permissions"); var request = new RestRequest(Method.DELETE); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{ \"permissions\": [ { \"resource_server_identifier\": \"API_ID\", \"permission_name\": \"PERMISSION_NAME\" }, { \"resource_server_identifier\": \"API_ID\", \"permission_name\": \"PERMISSION_NAME\" } ] }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "permissions": [ { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" } ] }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -52,7 +60,7 @@ func main() { url := "https://{yourDomain}/api/v2/roles/ROLE_ID/permissions" - payload := strings.NewReader("{ \"permissions\": [ { \"resource_server_identifier\": \"API_ID\", \"permission_name\": \"PERMISSION_NAME\" }, { \"resource_server_identifier\": \"API_ID\", \"permission_name\": \"PERMISSION_NAME\" } ] }") + payload := strings.NewReader("{ "permissions": [ { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" } ] }") req, _ := http.NewRequest("DELETE", url, payload) @@ -68,14 +76,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.delete("https://{yourDomain}/api/v2/roles/ROLE_ID/permissions") +} +``` +```java Java +HttpResponse response = Unirest.delete("https://{yourDomain}/api/v2/roles/ROLE_ID/permissions") .header("content-type", "application/json") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ \"permissions\": [ { \"resource_server_identifier\": \"API_ID\", \"permission_name\": \"PERMISSION_NAME\" }, { \"resource_server_identifier\": \"API_ID\", \"permission_name\": \"PERMISSION_NAME\" } ] }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "permissions": [ { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" } ] }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'DELETE', @@ -97,8 +109,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @@ -124,8 +138,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/roles/ROLE_ID/permissions", @@ -135,7 +151,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "DELETE", - CURLOPT_POSTFIELDS => "{ \"permissions\": [ { \"resource_server_identifier\": \"API_ID\", \"permission_name\": \"PERMISSION_NAME\" }, { \"resource_server_identifier\": \"API_ID\", \"permission_name\": \"PERMISSION_NAME\" } ] }", + CURLOPT_POSTFIELDS => "{ "permissions": [ { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" } ] }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "cache-control: no-cache", @@ -152,12 +168,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"permissions\": [ { \"resource_server_identifier\": \"API_ID\", \"permission_name\": \"PERMISSION_NAME\" }, { \"resource_server_identifier\": \"API_ID\", \"permission_name\": \"PERMISSION_NAME\" } ] }" +payload = "{ "permissions": [ { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" } ] }" headers = { 'content-type': "application/json", @@ -170,8 +188,10 @@ conn.request("DELETE", "/{yourDomain}/api/v2/roles/ROLE_ID/permissions", payload res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -185,11 +205,13 @@ request = Net::HTTP::Delete.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ \"permissions\": [ { \"resource_server_identifier\": \"API_ID\", \"permission_name\": \"PERMISSION_NAME\" }, { \"resource_server_identifier\": \"API_ID\", \"permission_name\": \"PERMISSION_NAME\" } ] }" +request.body = "{ "permissions": [ { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" }, { "resource_server_identifier": "API_ID", "permission_name": "PERMISSION_NAME" } ] }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -226,20 +248,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + | Value | Description | | --- | --- | diff --git a/main/docs/manage-users/access-control/configure-core-rbac/roles/view-role-permissions.mdx b/main/docs/manage-users/access-control/configure-core-rbac/roles/view-role-permissions.mdx index 7d70a96c3..9697d565c 100644 --- a/main/docs/manage-users/access-control/configure-core-rbac/roles/view-role-permissions.mdx +++ b/main/docs/manage-users/access-control/configure-core-rbac/roles/view-role-permissions.mdx @@ -11,6 +11,8 @@ title: View Role Permissions --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + You can view the [permissions](/docs/manage-users/access-control/rbac) added to a role using the Auth0 Dashboard or the Management API. The assigned permissions and roles are used with the API Authorization Core feature set. ## Prerequisites @@ -34,14 +36,20 @@ The following information is displayed for each permission: Make a `GET` call to the [Get Role Permissions endpoint](https://auth0.com/docs/api/management/v2#!/Roles/get_role_permission). Be sure to replace `ROLE_ID` and `MGMT_API_ACCESS_TOKEN` placeholder values with your role ID and Management API access token, respectively. -export const codeExample1 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/roles/ROLE_ID/permissions' \ - --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/roles/ROLE_ID/permissions"); + --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/roles/ROLE_ID/permissions"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -65,11 +73,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/roles/ROLE_ID/permissions") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/roles/ROLE_ID/permissions") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -81,8 +93,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN" }; @@ -102,8 +116,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/roles/ROLE_ID/permissions", @@ -127,8 +143,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -139,8 +157,10 @@ conn.request("GET", "/{yourDomain}/api/v2/roles/ROLE_ID/permissions", headers=he res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -154,8 +174,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer MGMT_API_ACCESS_TOKEN"] @@ -175,20 +197,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + | Value | Description | | --- | --- | diff --git a/main/docs/manage-users/my-account-api.mdx b/main/docs/manage-users/my-account-api.mdx index 46bd48bb0..2e243fa7f 100644 --- a/main/docs/manage-users/my-account-api.mdx +++ b/main/docs/manage-users/my-account-api.mdx @@ -12,6 +12,8 @@ title: My Account API --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + The My Account API is available in Limited Early Access. To request access, contact your Auth0 account manager. To learn more about Auth0's product release cycle, read [Product Release Stages](/docs/troubleshoot/product-lifecycle/product-release-stages). @@ -94,12 +96,18 @@ The My Account API supports the following scopes: ##### Step 1: Request authorization code -export const codeExample1 = `curl --request GET \ - --url 'https://{yourDomain}/authorize?response_type=code&client_id={yourClientId}&redirect_uri=%7ByourRedirectUri%7D&scope=create%3Ame%3Aauthentication_methods&offline_access=&audience=https%3A%2F%2F{yourDomain}%2Fme%2F'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/authorize?response_type=code&client_id={yourClientId}&redirect_uri=%7ByourRedirectUri%7D&scope=create%3Ame%3Aauthentication_methods&offline_access=&audience=https%3A%2F%2F{yourDomain}%2Fme%2F"); + +```bash cURL +curl --request GET \ + --url 'https://{yourDomain}/authorize?response_type=code&client_id={yourClientId}&redirect_uri=%7ByourRedirectUri%7D&scope=create%3Ame%3Aauthentication_methods&offline_access=&audience=https%3A%2F%2F{yourDomain}%2Fme%2F' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/authorize?response_type=code&client_id={yourClientId}&redirect_uri=%7ByourRedirectUri%7D&scope=create%3Ame%3Aauthentication_methods&offline_access=&audience=https%3A%2F%2F{yourDomain}%2Fme%2F"); var request = new RestRequest(Method.GET); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -121,10 +129,14 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.get("https://{yourDomain}/authorize?response_type=code&client_id={yourClientId}&redirect_uri=%7ByourRedirectUri%7D&scope=create%3Ame%3Aauthentication_methods&offline_access=&audience=https%3A%2F%2F{yourDomain}%2Fme%2F") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/authorize?response_type=code&client_id={yourClientId}&redirect_uri=%7ByourRedirectUri%7D&scope=create%3Ame%3Aauthentication_methods&offline_access=&audience=https%3A%2F%2F{yourDomain}%2Fme%2F") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -143,8 +155,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://{yourDomain}/authorize?response_type=code&client_id={yourClientId}&redirect_uri=%7ByourRedirectUri%7D&scope=create%3Ame%3Aauthentication_methods&offline_access=&audience=https%3A%2F%2F{yourDomain}%2Fme%2F"] cachePolicy:NSURLRequestUseProtocolCachePolicy @@ -161,8 +175,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/authorize?response_type=code&client_id={yourClientId}&redirect_uri=%7ByourRedirectUri%7D&scope=create%3Ame%3Aauthentication_methods&offline_access=&audience=https%3A%2F%2F{yourDomain}%2Fme%2F", @@ -183,8 +199,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -193,8 +211,10 @@ conn.request("GET", "/{yourDomain}/authorize?response_type=code&client_id={yourC res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -207,8 +227,10 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Get.new(url) response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let request = NSMutableURLRequest(url: NSURL(string: "https://{yourDomain}/authorize?response_type=code&client_id={yourClientId}&redirect_uri=%7ByourRedirectUri%7D&scope=create%3Ame%3Aauthentication_methods&offline_access=&audience=https%3A%2F%2F{yourDomain}%2Fme%2F")! as URL, cachePolicy: .useProtocolCachePolicy, @@ -225,33 +247,28 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ##### Step 2: Exchange code for access token -export const codeExample11 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/json' \ - --data '{"grant_type": "authorization_code","client_id": "{yourClientId}","client_secret": "{yourClientId}","code": "{yourAuthorizationCode}","redirect_uri": "{yourRedirectUri}","audience": "{yourAudience}","scope": "create:me:authentication_methods","offline_access": ""}'`; -export const codeExample12 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data '{"grant_type": "authorization_code","client_id": "{yourClientId}","client_secret": "{yourClientId}","code": "{yourAuthorizationCode}","redirect_uri": "{yourRedirectUri}","audience": "{yourAudience}","scope": "create:me:authentication_methods","offline_access": ""}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\"grant_type\": \"authorization_code\",\"client_id\": \"{yourClientId}\",\"client_secret\": \"{yourClientId}\",\"code\": \"{yourAuthorizationCode}\",\"redirect_uri\": \"{yourRedirectUri}\",\"audience\": \"{yourAudience}\",\"scope\": \"create:me:authentication_methods\",\"offline_access\": \"\"}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample13 = `package main +request.AddParameter("application/json", "{"grant_type": "authorization_code","client_id": "{yourClientId}","client_secret": "{yourClientId}","code": "{yourAuthorizationCode}","redirect_uri": "{yourRedirectUri}","audience": "{yourAudience}","scope": "create:me:authentication_methods","offline_access": ""}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -264,7 +281,7 @@ func main() { url := "https://{yourDomain}/oauth/token" - payload := strings.NewReader("{\"grant_type\": \"authorization_code\",\"client_id\": \"{yourClientId}\",\"client_secret\": \"{yourClientId}\",\"code\": \"{yourAuthorizationCode}\",\"redirect_uri\": \"{yourRedirectUri}\",\"audience\": \"{yourAudience}\",\"scope\": \"create:me:authentication_methods\",\"offline_access\": \"\"}") + payload := strings.NewReader("{"grant_type": "authorization_code","client_id": "{yourClientId}","client_secret": "{yourClientId}","code": "{yourAuthorizationCode}","redirect_uri": "{yourRedirectUri}","audience": "{yourAudience}","scope": "create:me:authentication_methods","offline_access": ""}") req, _ := http.NewRequest("POST", url, payload) @@ -278,12 +295,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample14 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/json") - .body("{\"grant_type\": \"authorization_code\",\"client_id\": \"{yourClientId}\",\"client_secret\": \"{yourClientId}\",\"code\": \"{yourAuthorizationCode}\",\"redirect_uri\": \"{yourRedirectUri}\",\"audience\": \"{yourAudience}\",\"scope\": \"create:me:authentication_methods\",\"offline_access\": \"\"}") - .asString();`; -export const codeExample15 = `var axios = require("axios").default; + .body("{"grant_type": "authorization_code","client_id": "{yourClientId}","client_secret": "{yourClientId}","code": "{yourAuthorizationCode}","redirect_uri": "{yourRedirectUri}","audience": "{yourAudience}","scope": "create:me:authentication_methods","offline_access": ""}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -305,8 +326,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample16 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json" }; NSDictionary *parameters = @{ @"grant_type": @"authorization_code", @@ -337,8 +360,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -348,7 +373,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{\"grant_type\": \"authorization_code\",\"client_id\": \"{yourClientId}\",\"client_secret\": \"{yourClientId}\",\"code\": \"{yourAuthorizationCode}\",\"redirect_uri\": \"{yourRedirectUri}\",\"audience\": \"{yourAudience}\",\"scope\": \"create:me:authentication_methods\",\"offline_access\": \"\"}", + CURLOPT_POSTFIELDS => "{"grant_type": "authorization_code","client_id": "{yourClientId}","client_secret": "{yourClientId}","code": "{yourAuthorizationCode}","redirect_uri": "{yourRedirectUri}","audience": "{yourAudience}","scope": "create:me:authentication_methods","offline_access": ""}", CURLOPT_HTTPHEADER => [ "content-type: application/json" ], @@ -363,12 +388,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"grant_type\": \"authorization_code\",\"client_id\": \"{yourClientId}\",\"client_secret\": \"{yourClientId}\",\"code\": \"{yourAuthorizationCode}\",\"redirect_uri\": \"{yourRedirectUri}\",\"audience\": \"{yourAudience}\",\"scope\": \"create:me:authentication_methods\",\"offline_access\": \"\"}" +payload = "{"grant_type": "authorization_code","client_id": "{yourClientId}","client_secret": "{yourClientId}","code": "{yourAuthorizationCode}","redirect_uri": "{yourRedirectUri}","audience": "{yourAudience}","scope": "create:me:authentication_methods","offline_access": ""}" headers = { 'content-type': "application/json" } @@ -377,8 +404,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -390,11 +419,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["content-type"] = 'application/json' -request.body = "{\"grant_type\": \"authorization_code\",\"client_id\": \"{yourClientId}\",\"client_secret\": \"{yourClientId}\",\"code\": \"{yourAuthorizationCode}\",\"redirect_uri\": \"{yourRedirectUri}\",\"audience\": \"{yourAudience}\",\"scope\": \"create:me:authentication_methods\",\"offline_access\": \"\"}" +request.body = "{"grant_type": "authorization_code","client_id": "{yourClientId}","client_secret": "{yourClientId}","code": "{yourAuthorizationCode}","redirect_uri": "{yourRedirectUri}","audience": "{yourAudience}","scope": "create:me:authentication_methods","offline_access": ""}" response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/json"] let parameters = [ @@ -427,35 +458,30 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + #### Embedded login with native passkeys ##### Step 1: Request login challenge -export const codeExample21 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/passkey/challenge' \ --header 'content-type: application/json' \ - --data '{"client_id": "{yourDomain}"}'`; -export const codeExample22 = `var client = new RestClient("https://{yourDomain}/passkey/challenge"); + --data '{"client_id": "{yourDomain}"}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/passkey/challenge"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\"client_id\": \"{yourDomain}\"}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample23 = `package main +request.AddParameter("application/json", "{"client_id": "{yourDomain}"}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -468,7 +494,7 @@ func main() { url := "https://{yourDomain}/passkey/challenge" - payload := strings.NewReader("{\"client_id\": \"{yourDomain}\"}") + payload := strings.NewReader("{"client_id": "{yourDomain}"}") req, _ := http.NewRequest("POST", url, payload) @@ -482,12 +508,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample24 = `HttpResponse response = Unirest.post("https://{yourDomain}/passkey/challenge") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/passkey/challenge") .header("content-type", "application/json") - .body("{\"client_id\": \"{yourDomain}\"}") - .asString();`; -export const codeExample25 = `var axios = require("axios").default; + .body("{"client_id": "{yourDomain}"}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -500,8 +530,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample26 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json" }; NSDictionary *parameters = @{ @"client_id": @"{yourDomain}" }; @@ -525,8 +557,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample27 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/passkey/challenge", @@ -536,7 +570,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{\"client_id\": \"{yourDomain}\"}", + CURLOPT_POSTFIELDS => "{"client_id": "{yourDomain}"}", CURLOPT_HTTPHEADER => [ "content-type: application/json" ], @@ -551,12 +585,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample28 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"client_id\": \"{yourDomain}\"}" +payload = "{"client_id": "{yourDomain}"}" headers = { 'content-type': "application/json" } @@ -565,8 +601,10 @@ conn.request("POST", "/{yourDomain}/passkey/challenge", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample29 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -578,11 +616,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["content-type"] = 'application/json' -request.body = "{\"client_id\": \"{yourDomain}\"}" +request.body = "{"client_id": "{yourDomain}"}" response = http.request(request) -puts response.read_body`; -export const codeExample30 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/json"] let parameters = ["client_id": "{yourDomain}"] as [String : Any] @@ -606,33 +646,28 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ##### Step 2: Authenticate existing user -export const codeExample31 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/json' \ - --data '{ "grant_type": "urn:okta:params:oauth:grant-type:webauthn", "client_id": "{yourClientId}", "scope": "create:me:authentication_methods offline_access", "audience": "https://{yourDomain}/me/" "auth_session": "{sessionIdFromTheFirstRequest}", "authn_response": "{authenticatorResponse}"}'`; -export const codeExample32 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data '{ "grant_type": "urn:okta:params:oauth:grant-type:webauthn", "client_id": "{yourClientId}", "scope": "create:me:authentication_methods offline_access", "audience": "https://{yourDomain}/me/" "auth_session": "{sessionIdFromTheFirstRequest}", "authn_response": "{authenticatorResponse}"}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{ \"grant_type\": \"urn:okta:params:oauth:grant-type:webauthn\", \"client_id\": \"{yourClientId}\", \"scope\": \"create:me:authentication_methods offline_access\", \"audience\": \"https://{yourDomain}/me/\" \"auth_session\": \"{sessionIdFromTheFirstRequest}\", \"authn_response\": \"{authenticatorResponse}\"}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample33 = `package main +request.AddParameter("application/json", "{ "grant_type": "urn:okta:params:oauth:grant-type:webauthn", "client_id": "{yourClientId}", "scope": "create:me:authentication_methods offline_access", "audience": "https://{yourDomain}/me/" "auth_session": "{sessionIdFromTheFirstRequest}", "authn_response": "{authenticatorResponse}"}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -645,7 +680,7 @@ func main() { url := "https://{yourDomain}/oauth/token" - payload := strings.NewReader("{ \"grant_type\": \"urn:okta:params:oauth:grant-type:webauthn\", \"client_id\": \"{yourClientId}\", \"scope\": \"create:me:authentication_methods offline_access\", \"audience\": \"https://{yourDomain}/me/\" \"auth_session\": \"{sessionIdFromTheFirstRequest}\", \"authn_response\": \"{authenticatorResponse}\"}") + payload := strings.NewReader("{ "grant_type": "urn:okta:params:oauth:grant-type:webauthn", "client_id": "{yourClientId}", "scope": "create:me:authentication_methods offline_access", "audience": "https://{yourDomain}/me/" "auth_session": "{sessionIdFromTheFirstRequest}", "authn_response": "{authenticatorResponse}"}") req, _ := http.NewRequest("POST", url, payload) @@ -659,12 +694,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample34 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/json") - .body("{ \"grant_type\": \"urn:okta:params:oauth:grant-type:webauthn\", \"client_id\": \"{yourClientId}\", \"scope\": \"create:me:authentication_methods offline_access\", \"audience\": \"https://{yourDomain}/me/\" \"auth_session\": \"{sessionIdFromTheFirstRequest}\", \"authn_response\": \"{authenticatorResponse}\"}") - .asString();`; -export const codeExample35 = `var axios = require("axios").default; + .body("{ "grant_type": "urn:okta:params:oauth:grant-type:webauthn", "client_id": "{yourClientId}", "scope": "create:me:authentication_methods offline_access", "audience": "https://{yourDomain}/me/" "auth_session": "{sessionIdFromTheFirstRequest}", "authn_response": "{authenticatorResponse}"}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -677,8 +716,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample36 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json" }; @@ -701,8 +742,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample37 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -712,7 +755,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{ \"grant_type\": \"urn:okta:params:oauth:grant-type:webauthn\", \"client_id\": \"{yourClientId}\", \"scope\": \"create:me:authentication_methods offline_access\", \"audience\": \"https://{yourDomain}/me/\" \"auth_session\": \"{sessionIdFromTheFirstRequest}\", \"authn_response\": \"{authenticatorResponse}\"}", + CURLOPT_POSTFIELDS => "{ "grant_type": "urn:okta:params:oauth:grant-type:webauthn", "client_id": "{yourClientId}", "scope": "create:me:authentication_methods offline_access", "audience": "https://{yourDomain}/me/" "auth_session": "{sessionIdFromTheFirstRequest}", "authn_response": "{authenticatorResponse}"}", CURLOPT_HTTPHEADER => [ "content-type: application/json" ], @@ -727,12 +770,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample38 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"grant_type\": \"urn:okta:params:oauth:grant-type:webauthn\", \"client_id\": \"{yourClientId}\", \"scope\": \"create:me:authentication_methods offline_access\", \"audience\": \"https://{yourDomain}/me/\" \"auth_session\": \"{sessionIdFromTheFirstRequest}\", \"authn_response\": \"{authenticatorResponse}\"}" +payload = "{ "grant_type": "urn:okta:params:oauth:grant-type:webauthn", "client_id": "{yourClientId}", "scope": "create:me:authentication_methods offline_access", "audience": "https://{yourDomain}/me/" "auth_session": "{sessionIdFromTheFirstRequest}", "authn_response": "{authenticatorResponse}"}" headers = { 'content-type': "application/json" } @@ -741,8 +786,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample39 = `rrequire 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +rrequire 'uri' require 'net/http' require 'openssl' @@ -754,11 +801,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["content-type"] = 'application/json' -request.body = "{ \"grant_type\": \"urn:okta:params:oauth:grant-type:webauthn\", \"client_id\": \"{yourClientId}\", \"scope\": \"create:me:authentication_methods offline_access\", \"audience\": \"https://{yourDomain}/me/\" \"auth_session\": \"{sessionIdFromTheFirstRequest}\", \"authn_response\": \"{authenticatorResponse}\"}" +request.body = "{ "grant_type": "urn:okta:params:oauth:grant-type:webauthn", "client_id": "{yourClientId}", "scope": "create:me:authentication_methods offline_access", "audience": "https://{yourDomain}/me/" "auth_session": "{sessionIdFromTheFirstRequest}", "authn_response": "{authenticatorResponse}"}" response = http.request(request) -puts response.read_body`; -export const codeExample40 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/json"] @@ -781,20 +830,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ## Endpoints diff --git a/main/docs/manage-users/organizations/configure-organizations/add-member-roles.mdx b/main/docs/manage-users/organizations/configure-organizations/add-member-roles.mdx index a667cab59..e3d9f324c 100644 --- a/main/docs/manage-users/organizations/configure-organizations/add-member-roles.mdx +++ b/main/docs/manage-users/organizations/configure-organizations/add-member-roles.mdx @@ -9,6 +9,9 @@ title: Add Roles to Organization Members Dashboard or Management API. 'twitter:title': Add Roles to Organization Members --- + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + Each [organization](/docs/manage-users/organizations/organizations-overview) member can be assigned one or more roles, which are applied when users log in through the organization. To learn more about roles and their behavior, read [Role-based Access Control](/docs/manage-users/access-control/rbac). You can add roles to members in organizations using either the Auth0 Dashboard or the Management API. @@ -29,7 +32,7 @@ To add roles to an organization member via the Auth0 Dashboard: To add roles to an organization member via the Management API: Make a `POST` call to the `Create Organization Member Roles` endpoint. Be sure to replace `ORG_ID`, `MGMT_API_ACCESS_TOKEN`, `USER_ID`, and `ROLE_ID` placeholder values with your organization ID, Management API Access Token, user ID, and role ID, respectively. - + ```bash cURL lines curl --request POST \ @@ -248,7 +251,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + **Find Your Auth0 Domain** diff --git a/main/docs/manage-users/organizations/configure-organizations/assign-members.mdx b/main/docs/manage-users/organizations/configure-organizations/assign-members.mdx index eef886fb3..eb408f00c 100644 --- a/main/docs/manage-users/organizations/configure-organizations/assign-members.mdx +++ b/main/docs/manage-users/organizations/configure-organizations/assign-members.mdx @@ -9,6 +9,9 @@ title: Assign Members to an Organization either the Auth0 Dashboard or Management API. 'twitter:title': Assign Members to an Organization --- + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + To assign a member to your [organization](/docs/manage-users/organizations/organizations-overview), you must have already [created the user](/docs/manage-users/user-accounts/create-users) in your tenant. If you cannot find a user, you can [invite them](/docs/manage-users/organizations/configure-organizations/invite-members) instead. To manage members directly, you can use either the Auth0 Dashboard or the Management API. @@ -27,7 +30,7 @@ To assign members via the Management API: Make a `POST` call to the `Create Organization Members` endpoint. Be sure to replace `ORG_ID`, `MGMT_API_ACCESS_TOKEN`, and `USER_ID` placeholder values with your organization ID, Management API Access Token, and user IDs, respectively. - + ```bash cURL lines curl --request POST \ @@ -246,7 +249,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + **Find Your Auth0 Domain** diff --git a/main/docs/manage-users/organizations/configure-organizations/create-organizations.mdx b/main/docs/manage-users/organizations/configure-organizations/create-organizations.mdx index 446bbafb4..51f988d85 100644 --- a/main/docs/manage-users/organizations/configure-organizations/create-organizations.mdx +++ b/main/docs/manage-users/organizations/configure-organizations/create-organizations.mdx @@ -11,6 +11,8 @@ title: Create Organizations --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + You can create [organizations](/docs/manage-users/organizations/organizations-overview) using either the Auth0 Dashboard or the Management API. @@ -46,20 +48,26 @@ To create an organization via the Management API: Make a `POST` call to the `Create Organizations` endpoint. Ensure you replace the placeholder values with the appropriate values from your tenant. For more details, review the parameter chart below. -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/api/v2/organizations' \ --header 'authorization: Bearer {MGMT_API_ACCESS_TOKEN}' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{ "name": "ORG_NAME", "display_name": "ORG_DISPLAY_NAME", "branding": [ { "logo_url": "{orgLogo}", "colors": [ { "primary": "{orgPrimaryColor}", "page_background": "{orgPageBackground}" } ] } ], "metadata": [ { "{key}": "{value}", "{key}": "{value}", "{key}": "{value}" } ] }, "enabled_connections": [ { "connection_id": "{connectionId}", "assign_membership_on_login": "{assignMembershipOption}" }, { "connection_id": "{connectionId}", "assign_membership_on_login": "{assignMembershipOption}" } ] }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/organizations"); + --data '{ "name": "ORG_NAME", "display_name": "ORG_DISPLAY_NAME", "branding": [ { "logo_url": "{orgLogo}", "colors": [ { "primary": "{orgPrimaryColor}", "page_background": "{orgPageBackground}" } ] } ], "metadata": [ { "{key}": "{value}", "{key}": "{value}", "{key}": "{value}" } ] }, "enabled_connections": [ { "connection_id": "{connectionId}", "assign_membership_on_login": "{assignMembershipOption}" }, { "connection_id": "{connectionId}", "assign_membership_on_login": "{assignMembershipOption}" } ] }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/organizations"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer {MGMT_API_ACCESS_TOKEN}"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{ \"name\": \"ORG_NAME\", \"display_name\": \"ORG_DISPLAY_NAME\", \"branding\": [ { \"logo_url\": \"{orgLogo}\", \"colors\": [ { \"primary\": \"{orgPrimaryColor}\", \"page_background\": \"{orgPageBackground}\" } ] } ], \"metadata\": [ { \"{key}\": \"{value}\", \"{key}\": \"{value}\", \"{key}\": \"{value}\" } ] }, \"enabled_connections\": [ { \"connection_id\": \"{connectionId}\", \"assign_membership_on_login\": \"{assignMembershipOption}\" }, { \"connection_id\": \"{connectionId}\", \"assign_membership_on_login\": \"{assignMembershipOption}\" } ] }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "name": "ORG_NAME", "display_name": "ORG_DISPLAY_NAME", "branding": [ { "logo_url": "{orgLogo}", "colors": [ { "primary": "{orgPrimaryColor}", "page_background": "{orgPageBackground}" } ] } ], "metadata": [ { "{key}": "{value}", "{key}": "{value}", "{key}": "{value}" } ] }, "enabled_connections": [ { "connection_id": "{connectionId}", "assign_membership_on_login": "{assignMembershipOption}" }, { "connection_id": "{connectionId}", "assign_membership_on_login": "{assignMembershipOption}" } ] }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -72,7 +80,7 @@ func main() { url := "https://{yourDomain}/api/v2/organizations" - payload := strings.NewReader("{ \"name\": \"ORG_NAME\", \"display_name\": \"ORG_DISPLAY_NAME\", \"branding\": [ { \"logo_url\": \"{orgLogo}\", \"colors\": [ { \"primary\": \"{orgPrimaryColor}\", \"page_background\": \"{orgPageBackground}\" } ] } ], \"metadata\": [ { \"{key}\": \"{value}\", \"{key}\": \"{value}\", \"{key}\": \"{value}\" } ] }, \"enabled_connections\": [ { \"connection_id\": \"{connectionId}\", \"assign_membership_on_login\": \"{assignMembershipOption}\" }, { \"connection_id\": \"{connectionId}\", \"assign_membership_on_login\": \"{assignMembershipOption}\" } ] }") + payload := strings.NewReader("{ "name": "ORG_NAME", "display_name": "ORG_DISPLAY_NAME", "branding": [ { "logo_url": "{orgLogo}", "colors": [ { "primary": "{orgPrimaryColor}", "page_background": "{orgPageBackground}" } ] } ], "metadata": [ { "{key}": "{value}", "{key}": "{value}", "{key}": "{value}" } ] }, "enabled_connections": [ { "connection_id": "{connectionId}", "assign_membership_on_login": "{assignMembershipOption}" }, { "connection_id": "{connectionId}", "assign_membership_on_login": "{assignMembershipOption}" } ] }") req, _ := http.NewRequest("POST", url, payload) @@ -88,14 +96,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/organizations") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/organizations") .header("content-type", "application/json") .header("authorization", "Bearer {MGMT_API_ACCESS_TOKEN}") .header("cache-control", "no-cache") - .body("{ \"name\": \"ORG_NAME\", \"display_name\": \"ORG_DISPLAY_NAME\", \"branding\": [ { \"logo_url\": \"{orgLogo}\", \"colors\": [ { \"primary\": \"{orgPrimaryColor}\", \"page_background\": \"{orgPageBackground}\" } ] } ], \"metadata\": [ { \"{key}\": \"{value}\", \"{key}\": \"{value}\", \"{key}\": \"{value}\" } ] }, \"enabled_connections\": [ { \"connection_id\": \"{connectionId}\", \"assign_membership_on_login\": \"{assignMembershipOption}\" }, { \"connection_id\": \"{connectionId}\", \"assign_membership_on_login\": \"{assignMembershipOption}\" } ] }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "name": "ORG_NAME", "display_name": "ORG_DISPLAY_NAME", "branding": [ { "logo_url": "{orgLogo}", "colors": [ { "primary": "{orgPrimaryColor}", "page_background": "{orgPageBackground}" } ] } ], "metadata": [ { "{key}": "{value}", "{key}": "{value}", "{key}": "{value}" } ] }, "enabled_connections": [ { "connection_id": "{connectionId}", "assign_membership_on_login": "{assignMembershipOption}" }, { "connection_id": "{connectionId}", "assign_membership_on_login": "{assignMembershipOption}" } ] }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -112,8 +124,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer {MGMT_API_ACCESS_TOKEN}", @@ -138,8 +152,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/organizations", @@ -149,7 +165,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{ \"name\": \"ORG_NAME\", \"display_name\": \"ORG_DISPLAY_NAME\", \"branding\": [ { \"logo_url\": \"{orgLogo}\", \"colors\": [ { \"primary\": \"{orgPrimaryColor}\", \"page_background\": \"{orgPageBackground}\" } ] } ], \"metadata\": [ { \"{key}\": \"{value}\", \"{key}\": \"{value}\", \"{key}\": \"{value}\" } ] }, \"enabled_connections\": [ { \"connection_id\": \"{connectionId}\", \"assign_membership_on_login\": \"{assignMembershipOption}\" }, { \"connection_id\": \"{connectionId}\", \"assign_membership_on_login\": \"{assignMembershipOption}\" } ] }", + CURLOPT_POSTFIELDS => "{ "name": "ORG_NAME", "display_name": "ORG_DISPLAY_NAME", "branding": [ { "logo_url": "{orgLogo}", "colors": [ { "primary": "{orgPrimaryColor}", "page_background": "{orgPageBackground}" } ] } ], "metadata": [ { "{key}": "{value}", "{key}": "{value}", "{key}": "{value}" } ] }, "enabled_connections": [ { "connection_id": "{connectionId}", "assign_membership_on_login": "{assignMembershipOption}" }, { "connection_id": "{connectionId}", "assign_membership_on_login": "{assignMembershipOption}" } ] }", CURLOPT_HTTPHEADER => [ "authorization: Bearer {MGMT_API_ACCESS_TOKEN}", "cache-control: no-cache", @@ -166,12 +182,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"name\": \"ORG_NAME\", \"display_name\": \"ORG_DISPLAY_NAME\", \"branding\": [ { \"logo_url\": \"{orgLogo}\", \"colors\": [ { \"primary\": \"{orgPrimaryColor}\", \"page_background\": \"{orgPageBackground}\" } ] } ], \"metadata\": [ { \"{key}\": \"{value}\", \"{key}\": \"{value}\", \"{key}\": \"{value}\" } ] }, \"enabled_connections\": [ { \"connection_id\": \"{connectionId}\", \"assign_membership_on_login\": \"{assignMembershipOption}\" }, { \"connection_id\": \"{connectionId}\", \"assign_membership_on_login\": \"{assignMembershipOption}\" } ] }" +payload = "{ "name": "ORG_NAME", "display_name": "ORG_DISPLAY_NAME", "branding": [ { "logo_url": "{orgLogo}", "colors": [ { "primary": "{orgPrimaryColor}", "page_background": "{orgPageBackground}" } ] } ], "metadata": [ { "{key}": "{value}", "{key}": "{value}", "{key}": "{value}" } ] }, "enabled_connections": [ { "connection_id": "{connectionId}", "assign_membership_on_login": "{assignMembershipOption}" }, { "connection_id": "{connectionId}", "assign_membership_on_login": "{assignMembershipOption}" } ] }" headers = { 'content-type': "application/json", @@ -184,8 +202,10 @@ conn.request("POST", "/{yourDomain}/api/v2/organizations", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -199,11 +219,13 @@ request = Net::HTTP::Post.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer {MGMT_API_ACCESS_TOKEN}' request["cache-control"] = 'no-cache' -request.body = "{ \"name\": \"ORG_NAME\", \"display_name\": \"ORG_DISPLAY_NAME\", \"branding\": [ { \"logo_url\": \"{orgLogo}\", \"colors\": [ { \"primary\": \"{orgPrimaryColor}\", \"page_background\": \"{orgPageBackground}\" } ] } ], \"metadata\": [ { \"{key}\": \"{value}\", \"{key}\": \"{value}\", \"{key}\": \"{value}\" } ] }, \"enabled_connections\": [ { \"connection_id\": \"{connectionId}\", \"assign_membership_on_login\": \"{assignMembershipOption}\" }, { \"connection_id\": \"{connectionId}\", \"assign_membership_on_login\": \"{assignMembershipOption}\" } ] }" +request.body = "{ "name": "ORG_NAME", "display_name": "ORG_DISPLAY_NAME", "branding": [ { "logo_url": "{orgLogo}", "colors": [ { "primary": "{orgPrimaryColor}", "page_background": "{orgPageBackground}" } ] } ], "metadata": [ { "{key}": "{value}", "{key}": "{value}", "{key}": "{value}" } ] }, "enabled_connections": [ { "connection_id": "{connectionId}", "assign_membership_on_login": "{assignMembershipOption}" }, { "connection_id": "{connectionId}", "assign_membership_on_login": "{assignMembershipOption}" } ] }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -230,20 +252,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + **Find Your Auth0 Domain** diff --git a/main/docs/manage-users/organizations/configure-organizations/define-organization-behavior.mdx b/main/docs/manage-users/organizations/configure-organizations/define-organization-behavior.mdx index 8291b4e7d..31f05b479 100644 --- a/main/docs/manage-users/organizations/configure-organizations/define-organization-behavior.mdx +++ b/main/docs/manage-users/organizations/configure-organizations/define-organization-behavior.mdx @@ -12,6 +12,8 @@ title: Define Organization Behavior --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + When representing your application in Auth0, you can specify what types of users the application should support. Some applications support individuals logging in with personal accounts, while others are intended for use by members of [organizations](/docs/manage-users/organizations/organizations-overview). Some should support both. This is known as organization behavior and can be set for each application that you connect to Auth0. For example, your application could have: @@ -102,20 +104,26 @@ To define organization behavior via the Auth0 Dashboard: Make a `PATCH` call to the [Update a Client endpoint](https://auth0.com/docs/api/management/v2#!/Clients/patch_clients_by_id). Be sure to replace `client_id`, `mgmt_api_access_token`, `organization_usage`, and `organization_require_behavior` placeholder values with your client ID, Management API Access Token, organization use option, and organization behavior option, respectively. -export const codeExample1 = `curl --request PATCH \ + +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/clients/CLIENT_ID' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{ "organization_usage": "ORG_USAGE", "organization_require_behavior": "ORG_REQUIRE_BEHAVIOR" }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/clients/CLIENT_ID"); + --data '{ "organization_usage": "ORG_USAGE", "organization_require_behavior": "ORG_REQUIRE_BEHAVIOR" }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/clients/CLIENT_ID"); var request = new RestRequest(Method.PATCH); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{ \"organization_usage\": \"ORG_USAGE\", \"organization_require_behavior\": \"ORG_REQUIRE_BEHAVIOR\" }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "organization_usage": "ORG_USAGE", "organization_require_behavior": "ORG_REQUIRE_BEHAVIOR" }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -128,7 +136,7 @@ func main() { url := "https://{yourDomain}/api/v2/clients/CLIENT_ID" - payload := strings.NewReader("{ \"organization_usage\": \"ORG_USAGE\", \"organization_require_behavior\": \"ORG_REQUIRE_BEHAVIOR\" }") + payload := strings.NewReader("{ "organization_usage": "ORG_USAGE", "organization_require_behavior": "ORG_REQUIRE_BEHAVIOR" }") req, _ := http.NewRequest("PATCH", url, payload) @@ -144,14 +152,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/clients/CLIENT_ID") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/clients/CLIENT_ID") .header("content-type", "application/json") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ \"organization_usage\": \"ORG_USAGE\", \"organization_require_behavior\": \"ORG_REQUIRE_BEHAVIOR\" }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "organization_usage": "ORG_USAGE", "organization_require_behavior": "ORG_REQUIRE_BEHAVIOR" }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -171,8 +183,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @@ -199,8 +213,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/clients/CLIENT_ID", @@ -210,7 +226,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{ \"organization_usage\": \"ORG_USAGE\", \"organization_require_behavior\": \"ORG_REQUIRE_BEHAVIOR\" }", + CURLOPT_POSTFIELDS => "{ "organization_usage": "ORG_USAGE", "organization_require_behavior": "ORG_REQUIRE_BEHAVIOR" }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "cache-control: no-cache", @@ -227,12 +243,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"organization_usage\": \"ORG_USAGE\", \"organization_require_behavior\": \"ORG_REQUIRE_BEHAVIOR\" }" +payload = "{ "organization_usage": "ORG_USAGE", "organization_require_behavior": "ORG_REQUIRE_BEHAVIOR" }" headers = { 'content-type': "application/json", @@ -245,8 +263,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/clients/CLIENT_ID", payload, headers res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -260,11 +280,13 @@ request = Net::HTTP::Patch.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ \"organization_usage\": \"ORG_USAGE\", \"organization_require_behavior\": \"ORG_REQUIRE_BEHAVIOR\" }" +request.body = "{ "organization_usage": "ORG_USAGE", "organization_require_behavior": "ORG_REQUIRE_BEHAVIOR" }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -295,20 +317,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
    diff --git a/main/docs/manage-users/organizations/configure-organizations/delete-organizations.mdx b/main/docs/manage-users/organizations/configure-organizations/delete-organizations.mdx index 15c42b7e4..36010e4a7 100644 --- a/main/docs/manage-users/organizations/configure-organizations/delete-organizations.mdx +++ b/main/docs/manage-users/organizations/configure-organizations/delete-organizations.mdx @@ -11,6 +11,8 @@ title: Delete Organizations --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + When deleting an [organization](/docs/manage-users/organizations/organizations-overview), the association between all users’ membership and the deleted organization will be removed, though the users themselves will not be deleted from your tenant. @@ -32,14 +34,20 @@ To delete an organization via the Auth0 Dashboard: Make a `DELETE` call to the `Delete Organization` endpoint. Be sure to replace the `ORG_ID` and `MGMT_API_ACCESS_TOKEN` placeholder values with your organization ID and Management API Access Token, respectively. -export const codeExample1 = `curl --request DELETE \ + +```bash cURL +curl --request DELETE \ --url 'https://{yourDomain}/api/v2/organizations/ORG_ID' \ - --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/organizations/ORG_ID"); + --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/organizations/ORG_ID"); var request = new RestRequest(Method.DELETE); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -63,11 +71,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.delete("https://{yourDomain}/api/v2/organizations/ORG_ID") +} +``` +```java Java +HttpResponse response = Unirest.delete("https://{yourDomain}/api/v2/organizations/ORG_ID") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'DELETE', @@ -79,8 +91,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN" }; @@ -100,8 +114,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/organizations/ORG_ID", @@ -125,8 +141,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -137,8 +155,10 @@ conn.request("DELETE", "/{yourDomain}/api/v2/organizations/ORG_ID", headers=head res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -152,8 +172,10 @@ request = Net::HTTP::Delete.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer MGMT_API_ACCESS_TOKEN"] @@ -173,20 +195,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + **Find Your Auth0 Domain** diff --git a/main/docs/manage-users/organizations/configure-organizations/disable-connections.mdx b/main/docs/manage-users/organizations/configure-organizations/disable-connections.mdx index 6e287cc51..f8fdf0d74 100644 --- a/main/docs/manage-users/organizations/configure-organizations/disable-connections.mdx +++ b/main/docs/manage-users/organizations/configure-organizations/disable-connections.mdx @@ -11,6 +11,8 @@ title: Disable Organization Connections --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + You can disable connections for [organizations](/docs/manage-users/organizations/organizations-overview) using either the Auth0 Dashboard or the Management API. ## Auth0 Dashboard @@ -25,14 +27,20 @@ To disable a connection via the Auth0 Dashboard: Make a `DELETE` call to the `Delete Organization Connections` endpoint. Be sure to replace the `ORG_ID`, `MGMT_API_ACCESS_TOKEN`, and `CONNECTION_ID` placeholder values with your organization ID, Management API Access Token, and connection ID, respectively. -export const codeExample1 = `curl --request DELETE \ + +```bash cURL +curl --request DELETE \ --url 'https://{yourDomain}/api/v2/organizations/ORG_ID/enabled_connections/CONNECTION_ID' \ - --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/organizations/ORG_ID/enabled_connections/CONNECTION_ID"); + --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/organizations/ORG_ID/enabled_connections/CONNECTION_ID"); var request = new RestRequest(Method.DELETE); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -56,11 +64,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.delete("https://{yourDomain}/api/v2/organizations/ORG_ID/enabled_connections/CONNECTION_ID") +} +``` +```java Java +HttpResponse response = Unirest.delete("https://{yourDomain}/api/v2/organizations/ORG_ID/enabled_connections/CONNECTION_ID") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'DELETE', @@ -72,8 +84,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN" }; @@ -93,8 +107,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/organizations/ORG_ID/enabled_connections/CONNECTION_ID", @@ -118,8 +134,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -130,8 +148,10 @@ conn.request("DELETE", "/{yourDomain}/api/v2/organizations/ORG_ID/enabled_connec res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -145,8 +165,10 @@ request = Net::HTTP::Delete.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer MGMT_API_ACCESS_TOKEN"] @@ -166,20 +188,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + **Find Your Auth0 Domain** diff --git a/main/docs/manage-users/organizations/configure-organizations/enable-connections.mdx b/main/docs/manage-users/organizations/configure-organizations/enable-connections.mdx index c59bc2cf1..14bf231bb 100644 --- a/main/docs/manage-users/organizations/configure-organizations/enable-connections.mdx +++ b/main/docs/manage-users/organizations/configure-organizations/enable-connections.mdx @@ -9,6 +9,9 @@ title: Enable Organization Connections and Management API. 'twitter:title': Enable Organization Connections --- + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + You can enable specific connections for each [organization](/docs/manage-users/organizations/organizations-overview) to provide users with different login options. After you enable a connection, it is added to the organization login prompt, and users can authenticate through that connection to access your applications. To enable a connection for an organization, the connection **must** already exist in your tenant. Supported connections include [database connections](/docs/authenticate/database-connections), [social connections](/docs/authenticate/identity-providers/social-identity-providers), and [enterprise connections](/docs/authenticate/identity-providers/enterprise-identity-providers). @@ -107,7 +110,7 @@ Make a `POST` call to the `Create Organization Connections` endpoint. Ensure you * **For Database connections only**: Replace `{isSignupEnabled}` with `true` or `false` with respect to your signup selection. * **For Enterprise connections only**: Replace `{showAsButtonOption}` with `true` or `false` with respect to your Connection Button selection. - + ```bash cURL lines curl --request POST \ @@ -324,7 +327,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + diff --git a/main/docs/manage-users/organizations/configure-organizations/remove-member-roles.mdx b/main/docs/manage-users/organizations/configure-organizations/remove-member-roles.mdx index cbabd63a3..dc98c232b 100644 --- a/main/docs/manage-users/organizations/configure-organizations/remove-member-roles.mdx +++ b/main/docs/manage-users/organizations/configure-organizations/remove-member-roles.mdx @@ -11,6 +11,8 @@ title: Remove Roles from Organization Members --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + You can remove roles from [organization](/docs/manage-users/organizations/organizations-overview) members using either the Auth0 Dashboard or the Management API. ## Auth0 Dashboard @@ -26,18 +28,24 @@ To remove a role from an organization member via the Auth0 Dashboard: To remove roles from an organization member via the Management API: Make a `DELETE` call to the `Delete Organization Member Roles` endpoint. Be sure to replace the `ORG_ID`, `MGMT_API_ACCESS_TOKEN`, `USER_ID`, and `ROLE_ID` placeholder values with your organization ID, Management API Access Token, user ID, and role ID, respectively. -export const codeExample1 = `curl --request DELETE \ + +```bash cURL +curl --request DELETE \ --url 'https://{yourDomain}/api/v2/organizations/ORG_ID/members/USER_ID/roles' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'cache-control: no-cache' \ - --data '{ "roles": [ "ROLE_ID", "ROLE_ID", "ROLE_ID" ] }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/organizations/ORG_ID/members/USER_ID/roles"); + --data '{ "roles": [ "ROLE_ID", "ROLE_ID", "ROLE_ID" ] }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/organizations/ORG_ID/members/USER_ID/roles"); var request = new RestRequest(Method.DELETE); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("undefined", "{ \"roles\": [ \"ROLE_ID\", \"ROLE_ID\", \"ROLE_ID\" ] }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("undefined", "{ "roles": [ "ROLE_ID", "ROLE_ID", "ROLE_ID" ] }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -50,7 +58,7 @@ func main() { url := "https://{yourDomain}/api/v2/organizations/ORG_ID/members/USER_ID/roles" - payload := strings.NewReader("{ \"roles\": [ \"ROLE_ID\", \"ROLE_ID\", \"ROLE_ID\" ] }") + payload := strings.NewReader("{ "roles": [ "ROLE_ID", "ROLE_ID", "ROLE_ID" ] }") req, _ := http.NewRequest("DELETE", url, payload) @@ -65,13 +73,17 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.delete("https://{yourDomain}/api/v2/organizations/ORG_ID/members/USER_ID/roles") +} +``` +```java Java +HttpResponse response = Unirest.delete("https://{yourDomain}/api/v2/organizations/ORG_ID/members/USER_ID/roles") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ \"roles\": [ \"ROLE_ID\", \"ROLE_ID\", \"ROLE_ID\" ] }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "roles": [ "ROLE_ID", "ROLE_ID", "ROLE_ID" ] }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'DELETE', @@ -84,8 +96,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @"cache-control": @"no-cache" }; @@ -110,8 +124,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/organizations/ORG_ID/members/USER_ID/roles", @@ -121,7 +137,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "DELETE", - CURLOPT_POSTFIELDS => "{ \"roles\": [ \"ROLE_ID\", \"ROLE_ID\", \"ROLE_ID\" ] }", + CURLOPT_POSTFIELDS => "{ "roles": [ "ROLE_ID", "ROLE_ID", "ROLE_ID" ] }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "cache-control: no-cache" @@ -137,12 +153,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"roles\": [ \"ROLE_ID\", \"ROLE_ID\", \"ROLE_ID\" ] }" +payload = "{ "roles": [ "ROLE_ID", "ROLE_ID", "ROLE_ID" ] }" headers = { 'authorization': "Bearer MGMT_API_ACCESS_TOKEN", @@ -154,8 +172,10 @@ conn.request("DELETE", "/{yourDomain}/api/v2/organizations/ORG_ID/members/USER_I res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -168,11 +188,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Delete.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ \"roles\": [ \"ROLE_ID\", \"ROLE_ID\", \"ROLE_ID\" ] }" +request.body = "{ "roles": [ "ROLE_ID", "ROLE_ID", "ROLE_ID" ] }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "authorization": "Bearer MGMT_API_ACCESS_TOKEN", @@ -199,20 +221,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + **Find Your Auth0 Domain** diff --git a/main/docs/manage-users/organizations/configure-organizations/remove-members.mdx b/main/docs/manage-users/organizations/configure-organizations/remove-members.mdx index ced06bf38..b39269c41 100644 --- a/main/docs/manage-users/organizations/configure-organizations/remove-members.mdx +++ b/main/docs/manage-users/organizations/configure-organizations/remove-members.mdx @@ -11,6 +11,8 @@ title: Remove Members From Organizations --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + You can remove members from [organizations](/docs/manage-users/organizations/organizations-overview) using either the Auth0 Dashboard or the Management API. Removing a user from an organization will remove only that user’s membership in the given organization; it will not remove the user from the connection or the Auth0 tenant. The removal process takes approximately 5 - 10 seconds. ## Auth0 Dashboard @@ -26,18 +28,24 @@ To remove a member via the Auth0 Dashboard: To remove members via the Management API: Make a `DELETE` call to the `Delete Organization Members` endpoint. Be sure to replace the `ORG_ID`, `MGMT_API_ACCESS_TOKEN`, and `USER_ID` placeholder values with your organization ID, Management API Access Token, and user ID, respectively. -export const codeExample1 = `curl --request DELETE \ + +```bash cURL +curl --request DELETE \ --url 'https://{yourDomain}/api/v2/organizations/ORG_ID/members' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'cache-control: no-cache' \ - --data '{ "members": [ "USER_ID", "USER_ID", "USER_ID" ] }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/organizations/ORG_ID/members"); + --data '{ "members": [ "USER_ID", "USER_ID", "USER_ID" ] }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/organizations/ORG_ID/members"); var request = new RestRequest(Method.DELETE); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("undefined", "{ \"members\": [ \"USER_ID\", \"USER_ID\", \"USER_ID\" ] }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("undefined", "{ "members": [ "USER_ID", "USER_ID", "USER_ID" ] }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -50,7 +58,7 @@ func main() { url := "https://{yourDomain}/api/v2/organizations/ORG_ID/members" - payload := strings.NewReader("{ \"members\": [ \"USER_ID\", \"USER_ID\", \"USER_ID\" ] }") + payload := strings.NewReader("{ "members": [ "USER_ID", "USER_ID", "USER_ID" ] }") req, _ := http.NewRequest("DELETE", url, payload) @@ -65,13 +73,17 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.delete("https://{yourDomain}/api/v2/organizations/ORG_ID/members") +} +``` +```java Java +HttpResponse response = Unirest.delete("https://{yourDomain}/api/v2/organizations/ORG_ID/members") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ \"members\": [ \"USER_ID\", \"USER_ID\", \"USER_ID\" ] }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "members": [ "USER_ID", "USER_ID", "USER_ID" ] }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'DELETE', @@ -84,8 +96,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @"cache-control": @"no-cache" }; @@ -110,8 +124,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/organizations/ORG_ID/members", @@ -121,7 +137,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "DELETE", - CURLOPT_POSTFIELDS => "{ \"members\": [ \"USER_ID\", \"USER_ID\", \"USER_ID\" ] }", + CURLOPT_POSTFIELDS => "{ "members": [ "USER_ID", "USER_ID", "USER_ID" ] }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "cache-control: no-cache" @@ -137,12 +153,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"members\": [ \"USER_ID\", \"USER_ID\", \"USER_ID\" ] }" +payload = "{ "members": [ "USER_ID", "USER_ID", "USER_ID" ] }" headers = { 'authorization': "Bearer MGMT_API_ACCESS_TOKEN", @@ -154,8 +172,10 @@ conn.request("DELETE", "/{yourDomain}/api/v2/organizations/ORG_ID/members", payl res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -168,11 +188,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Delete.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ \"members\": [ \"USER_ID\", \"USER_ID\", \"USER_ID\" ] }" +request.body = "{ "members": [ "USER_ID", "USER_ID", "USER_ID" ] }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "authorization": "Bearer MGMT_API_ACCESS_TOKEN", @@ -199,20 +221,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + **Find Your Auth0 Domain** diff --git a/main/docs/manage-users/organizations/configure-organizations/retrieve-connections.mdx b/main/docs/manage-users/organizations/configure-organizations/retrieve-connections.mdx index be058fd8b..59a791853 100644 --- a/main/docs/manage-users/organizations/configure-organizations/retrieve-connections.mdx +++ b/main/docs/manage-users/organizations/configure-organizations/retrieve-connections.mdx @@ -11,6 +11,8 @@ title: Retrieve Organization Connections --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + When working with [organizations](/docs/manage-users/organizations/organizations-overview) programmatically, you may need to retrieve a list of connections enabled for an organization. You can view the connections associated with an organization using either the Auth0 Dashboard or the Management API. @@ -24,14 +26,20 @@ You can view the connections associated with an organization using either the Access Token, respectively. -export const codeExample1 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/organizations/ORG_ID/enabled_connections' \ - --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/organizations/ORG_ID/enabled_connections"); + --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/organizations/ORG_ID/enabled_connections"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -55,11 +63,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/organizations/ORG_ID/enabled_connections") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/organizations/ORG_ID/enabled_connections") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -71,8 +83,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN" }; @@ -92,8 +106,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/organizations/ORG_ID/enabled_connections", @@ -117,8 +133,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -129,8 +147,10 @@ conn.request("GET", "/{yourDomain}/api/v2/organizations/ORG_ID/enabled_connectio res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -144,8 +164,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer MGMT_API_ACCESS_TOKEN"] @@ -165,20 +187,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + **Find Your Auth0 Domain** diff --git a/main/docs/manage-users/organizations/configure-organizations/retrieve-member-roles.mdx b/main/docs/manage-users/organizations/configure-organizations/retrieve-member-roles.mdx index 0ce31f1f4..d2cecd478 100644 --- a/main/docs/manage-users/organizations/configure-organizations/retrieve-member-roles.mdx +++ b/main/docs/manage-users/organizations/configure-organizations/retrieve-member-roles.mdx @@ -11,6 +11,8 @@ title: Retrieve Member Roles for an Organization --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + When working with [organizations](/docs/manage-users/organizations/organizations-overview) programmatically, you may need to retrieve a list of roles assigned to a member of an organization. You can view the roles associated with an organization member using either the Auth0 Dashboard or the Management API. @@ -24,14 +26,20 @@ You can view the roles associated with an organization member using either the < Make a `GET` call to the `Get Organization Member Roles` endpoint. Be sure to replace the `ORG_ID`, `USER_ID`, and `MGMT_API_ACCESS_TOKEN` placeholder values with your organization ID, member's user ID, and Management API Access Token, respectively. -export const codeExample1 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/organizations/ORG_ID/members/USER_ID/roles' \ - --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/organizations/ORG_ID/members/USER_ID/roles"); + --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/organizations/ORG_ID/members/USER_ID/roles"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -55,11 +63,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/organizations/ORG_ID/members/USER_ID/roles") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/organizations/ORG_ID/members/USER_ID/roles") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -71,8 +83,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN" }; @@ -92,8 +106,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/organizations/ORG_ID/members/USER_ID/roles", @@ -117,8 +133,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -129,8 +147,10 @@ conn.request("GET", "/{yourDomain}/api/v2/organizations/ORG_ID/members/USER_ID/r res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -144,8 +164,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer MGMT_API_ACCESS_TOKEN"] @@ -165,20 +187,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + **Find Your Auth0 Domain** diff --git a/main/docs/manage-users/organizations/configure-organizations/retrieve-members.mdx b/main/docs/manage-users/organizations/configure-organizations/retrieve-members.mdx index fed470c1c..9de6beced 100644 --- a/main/docs/manage-users/organizations/configure-organizations/retrieve-members.mdx +++ b/main/docs/manage-users/organizations/configure-organizations/retrieve-members.mdx @@ -11,6 +11,8 @@ title: Retrieve Organization Members --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + When working with [organizations](/docs/manage-users/organizations/organizations-overview) programmatically, you may need to retrieve a list of members for an organization. You can view the members associated with an organization using either the Auth0 Dashboard or the Management API. @@ -30,14 +32,20 @@ Up to 1000 organization members can be displayed using the Auth0 Dashboard or Ma Make a `GET` call to the `Get Organization Members` endpoint. Be sure to replace the `ORG_ID` and `MGMT_API_ACCESS_TOKEN` placeholder values with your organization ID and Management API Access Token, respectively. -export const codeExample1 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/organizations/ORG_ID/members' \ - --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/organizations/ORG_ID/members"); + --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/organizations/ORG_ID/members"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -61,11 +69,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/organizations/ORG_ID/members") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/organizations/ORG_ID/members") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -77,8 +89,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN" }; @@ -98,8 +112,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/organizations/ORG_ID/members", @@ -123,8 +139,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -135,8 +153,10 @@ conn.request("GET", "/{yourDomain}/api/v2/organizations/ORG_ID/members", headers res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -150,8 +170,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer MGMT_API_ACCESS_TOKEN"] @@ -171,20 +193,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + **Find Your Auth0 Domain** diff --git a/main/docs/manage-users/organizations/configure-organizations/retrieve-organizations.mdx b/main/docs/manage-users/organizations/configure-organizations/retrieve-organizations.mdx index da293602e..f47b036d2 100644 --- a/main/docs/manage-users/organizations/configure-organizations/retrieve-organizations.mdx +++ b/main/docs/manage-users/organizations/configure-organizations/retrieve-organizations.mdx @@ -11,6 +11,8 @@ title: Retrieve Organizations --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + When working with [organizations](/docs/manage-users/organizations/organizations-overview) programmatically, you may need to retrieve either a list of all organizations or organizations individually by name or ID. @@ -31,14 +33,20 @@ To retrieve more than 1000 results, you must use the checkpoint pagination metho Make a `GET` call to the `Get Organizations` endpoint. Be sure to replace the `MGMT_API_ACCESS_TOKEN` placeholder value with your Management API Access Token. -export const codeExample1 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/organizations' \ - --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/organizations"); + --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/organizations"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -62,11 +70,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/organizations") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/organizations") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -78,8 +90,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN" }; @@ -99,8 +113,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/organizations", @@ -124,8 +140,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -136,8 +154,10 @@ conn.request("GET", "/{yourDomain}/api/v2/organizations", headers=headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -151,8 +171,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer MGMT_API_ACCESS_TOKEN"] @@ -172,20 +194,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + **Find Your Auth0 Domain** @@ -220,14 +231,20 @@ You can retrieve an organization by its ID through the Management API. Make a `GET` call to the `Get Organization` endpoint. Be sure to replace the `ORG_ID` and `MGMT_API_ACCESS_TOKEN` placeholder values with your organization ID and Management API Access Token, respectively. -export const codeExample11 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/organizations/ORG_ID' \ - --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN'`; -export const codeExample12 = `var client = new RestClient("https://{yourDomain}/api/v2/organizations/ORG_ID"); + --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/organizations/ORG_ID"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); -IRestResponse response = client.Execute(request);`; -export const codeExample13 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -251,11 +268,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample14 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/organizations/ORG_ID") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/organizations/ORG_ID") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") - .asString();`; -export const codeExample15 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -267,8 +288,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample16 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN" }; @@ -288,8 +311,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/organizations/ORG_ID", @@ -313,8 +338,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -325,8 +352,10 @@ conn.request("GET", "/{yourDomain}/api/v2/organizations/ORG_ID", headers=headers res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -340,8 +369,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer MGMT_API_ACCESS_TOKEN"] @@ -361,20 +392,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + **Find Your Auth0 Domain** @@ -409,14 +429,20 @@ You can retrieve an organization by its name through the Management API. Make a `GET` call to the `Get Organization by Name` endpoint. Be sure to replace the `ORG_NAME` and `MGMT_API_ACCESS_TOKEN` placeholder values with your organization ID and Management API Access Token, respectively. -export const codeExample21 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/organizations/name/ORG_NAME' \ - --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN'`; -export const codeExample22 = `var client = new RestClient("https://{yourDomain}/api/v2/organizations/name/ORG_NAME"); + --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/organizations/name/ORG_NAME"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); -IRestResponse response = client.Execute(request);`; -export const codeExample23 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -440,11 +466,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample24 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/organizations/name/ORG_NAME") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/organizations/name/ORG_NAME") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") - .asString();`; -export const codeExample25 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -456,8 +486,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample26 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN" }; @@ -477,8 +509,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample27 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/organizations/name/ORG_NAME", @@ -502,8 +536,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample28 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -514,8 +550,10 @@ conn.request("GET", "/{yourDomain}/api/v2/organizations/name/ORG_NAME", headers= res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample29 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -529,8 +567,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' response = http.request(request) -puts response.read_body`; -export const codeExample30 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer MGMT_API_ACCESS_TOKEN"] @@ -550,20 +590,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + **Find Your Auth0 Domain** diff --git a/main/docs/manage-users/organizations/configure-organizations/retrieve-user-membership.mdx b/main/docs/manage-users/organizations/configure-organizations/retrieve-user-membership.mdx index 7d30753e4..72ce752eb 100644 --- a/main/docs/manage-users/organizations/configure-organizations/retrieve-user-membership.mdx +++ b/main/docs/manage-users/organizations/configure-organizations/retrieve-user-membership.mdx @@ -11,6 +11,8 @@ title: Retrieve User's Organization Memberships --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + When working with [organizations](/docs/manage-users/organizations/organizations-overview) programmatically, you may need to retrieve a list of organizations to which a user is assigned membership. ## Management API @@ -23,14 +25,20 @@ Up to 1000 organization members can be displayed using the Auth0 Dashboard or Ma Make a `GET` call to the `Get User Organizations` endpoint. Be sure to replace the `USER_ID` and `MGMT_API_ACCESS_TOKEN` placeholder values with the user ID and your Management API Access Token, respectively. -export const codeExample1 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/users/USER_ID/organizations' \ - --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/users/USER_ID/organizations"); + --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users/USER_ID/organizations"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -54,11 +62,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/users/USER_ID/organizations") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/users/USER_ID/organizations") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -70,8 +82,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN" }; @@ -91,8 +105,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users/USER_ID/organizations", @@ -116,8 +132,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -128,8 +146,10 @@ conn.request("GET", "/{yourDomain}/api/v2/users/USER_ID/organizations", headers= res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -143,8 +163,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer MGMT_API_ACCESS_TOKEN"] @@ -164,20 +186,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + **Find Your Auth0 Domain** diff --git a/main/docs/manage-users/sessions/configure-session-lifetime-settings.mdx b/main/docs/manage-users/sessions/configure-session-lifetime-settings.mdx index 739414d71..8d3211b6f 100644 --- a/main/docs/manage-users/sessions/configure-session-lifetime-settings.mdx +++ b/main/docs/manage-users/sessions/configure-session-lifetime-settings.mdx @@ -12,6 +12,8 @@ title: Configure Session Lifetime Settings --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + The **Absolute Expiration** of a session is defined upon session creation. You can adjust the Absolute Expiration by configuring session settings using the Auth0 Dashboard or the Management API. ## Dashboard @@ -43,20 +45,26 @@ The **Absolute Expiration** of a session is defined upon session creation. You c Make a `PATCH` call to the [Tenant Settings endpoint](https://auth0.com/docs/api/management/v2#!/tenants/patch_settings). Be sure to replace `MGMT_API_ACCESS_TOKEN`, `SESSION_LIFETIME`, and `IDLE_SESSION_LIFETIME` placeholder values with your Management API Access Token, session lifetime value, and idle session lifetime value, respectively. -export const codeExample1 = `curl --request PATCH \ + +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/tenants/settings' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{ "session_lifetime": SESSION_LIFETIME_VALUE, "idle_session_lifetime": IDLE_SESSION_LIFETIME_VALUE }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/tenants/settings"); + --data '{ "session_lifetime": SESSION_LIFETIME_VALUE, "idle_session_lifetime": IDLE_SESSION_LIFETIME_VALUE }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/tenants/settings"); var request = new RestRequest(Method.PATCH); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{ \"session_lifetime\": SESSION_LIFETIME_VALUE, \"idle_session_lifetime\": IDLE_SESSION_LIFETIME_VALUE }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "session_lifetime": SESSION_LIFETIME_VALUE, "idle_session_lifetime": IDLE_SESSION_LIFETIME_VALUE }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -69,7 +77,7 @@ func main() { url := "https://{yourDomain}/api/v2/tenants/settings" - payload := strings.NewReader("{ \"session_lifetime\": SESSION_LIFETIME_VALUE, \"idle_session_lifetime\": IDLE_SESSION_LIFETIME_VALUE }") + payload := strings.NewReader("{ "session_lifetime": SESSION_LIFETIME_VALUE, "idle_session_lifetime": IDLE_SESSION_LIFETIME_VALUE }") req, _ := http.NewRequest("PATCH", url, payload) @@ -85,14 +93,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/tenants/settings") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/tenants/settings") .header("content-type", "application/json") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ \"session_lifetime\": SESSION_LIFETIME_VALUE, \"idle_session_lifetime\": IDLE_SESSION_LIFETIME_VALUE }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "session_lifetime": SESSION_LIFETIME_VALUE, "idle_session_lifetime": IDLE_SESSION_LIFETIME_VALUE }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -109,8 +121,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @@ -135,8 +149,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/tenants/settings", @@ -146,7 +162,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{ \"session_lifetime\": SESSION_LIFETIME_VALUE, \"idle_session_lifetime\": IDLE_SESSION_LIFETIME_VALUE }", + CURLOPT_POSTFIELDS => "{ "session_lifetime": SESSION_LIFETIME_VALUE, "idle_session_lifetime": IDLE_SESSION_LIFETIME_VALUE }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "cache-control: no-cache", @@ -163,12 +179,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"session_lifetime\": SESSION_LIFETIME_VALUE, \"idle_session_lifetime\": IDLE_SESSION_LIFETIME_VALUE }" +payload = "{ "session_lifetime": SESSION_LIFETIME_VALUE, "idle_session_lifetime": IDLE_SESSION_LIFETIME_VALUE }" headers = { 'content-type': "application/json", @@ -181,8 +199,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/tenants/settings", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -196,11 +216,13 @@ request = Net::HTTP::Patch.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ \"session_lifetime\": SESSION_LIFETIME_VALUE, \"idle_session_lifetime\": IDLE_SESSION_LIFETIME_VALUE }" +request.body = "{ "session_lifetime": SESSION_LIFETIME_VALUE, "idle_session_lifetime": IDLE_SESSION_LIFETIME_VALUE }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -227,20 +249,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
    diff --git a/main/docs/manage-users/user-accounts/change-user-picture.mdx b/main/docs/manage-users/user-accounts/change-user-picture.mdx index 1fcda6bfa..7ac25cf94 100644 --- a/main/docs/manage-users/user-accounts/change-user-picture.mdx +++ b/main/docs/manage-users/user-accounts/change-user-picture.mdx @@ -12,6 +12,8 @@ title: Change User Pictures --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + Auth0 normalizes common profile properties in the User Profile, this includes the `name`, `picture` field and more. The picture field is populated by either the social provider profile picture or the Gravatar image associated with the user's email address. By default, all database users will have a placeholder image with their initials. When you authenticate the user, this picture field is referred to as `user.picture`. @@ -22,18 +24,24 @@ The `user.picture` attribute is not directly editable when provided by +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/users/USER_ID' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'content-type: application/json' \ - --data '{"user_metadata": {"picture": "https://example.com/some-image.png"}}'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/users/USER_ID"); + --data '{"user_metadata": {"picture": "https://example.com/some-image.png"}}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users/USER_ID"); var request = new RestRequest(Method.PATCH); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\"user_metadata\": {\"picture\": \"https://example.com/some-image.png\"}}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{"user_metadata": {"picture": "https://example.com/some-image.png"}}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -46,7 +54,7 @@ func main() { url := "https://{yourDomain}/api/v2/users/USER_ID" - payload := strings.NewReader("{\"user_metadata\": {\"picture\": \"https://example.com/some-image.png\"}}") + payload := strings.NewReader("{"user_metadata": {"picture": "https://example.com/some-image.png"}}") req, _ := http.NewRequest("PATCH", url, payload) @@ -61,13 +69,17 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/users/USER_ID") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/users/USER_ID") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("content-type", "application/json") - .body("{\"user_metadata\": {\"picture\": \"https://example.com/some-image.png\"}}") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{"user_metadata": {"picture": "https://example.com/some-image.png"}}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -83,8 +95,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @"content-type": @"application/json" }; @@ -109,8 +123,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users/USER_ID", @@ -120,7 +136,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{\"user_metadata\": {\"picture\": \"https://example.com/some-image.png\"}}", + CURLOPT_POSTFIELDS => "{"user_metadata": {"picture": "https://example.com/some-image.png"}}", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "content-type: application/json" @@ -136,12 +152,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"user_metadata\": {\"picture\": \"https://example.com/some-image.png\"}}" +payload = "{"user_metadata": {"picture": "https://example.com/some-image.png"}}" headers = { 'authorization': "Bearer MGMT_API_ACCESS_TOKEN", @@ -153,8 +171,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/users/USER_ID", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -167,11 +187,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Patch.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["content-type"] = 'application/json' -request.body = "{\"user_metadata\": {\"picture\": \"https://example.com/some-image.png\"}}" +request.body = "{"user_metadata": {"picture": "https://example.com/some-image.png"}}" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "authorization": "Bearer MGMT_API_ACCESS_TOKEN", @@ -198,20 +220,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ## Use Actions @@ -231,7 +242,6 @@ To ensure that the picture from the `user_metadata` is returned in the { }; ``` - - - - - In this Action, the custom picture is returned in the ID Token and overrides any `picture` property that may come from an external identity provider login, such as Google. ## Limitations diff --git a/main/docs/manage-users/user-accounts/metadata/manage-metadata-api.mdx b/main/docs/manage-users/user-accounts/metadata/manage-metadata-api.mdx index c43c6fe24..810cf475a 100644 --- a/main/docs/manage-users/user-accounts/metadata/manage-metadata-api.mdx +++ b/main/docs/manage-users/user-accounts/metadata/manage-metadata-api.mdx @@ -12,6 +12,8 @@ title: Manage Metadata Using the Management API --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + ## User metadata ### Create user metadata @@ -30,25 +32,26 @@ To create a user with the following profile details: } ``` - - - - - Make the following `POST` call to the Management API [`/post_users`](https://auth0.com/docs/api/management/v2#!/Users/post_users) endpoint to create the user and set the property values: -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/api/v2/users' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'content-type: application/json' \ - --data '{"email": "jane.doe@example.com", "user_metadata": {"hobby": "surfing"}, "app_metadata": {"plan": "full"}}'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/users"); + --data '{"email": "jane.doe@example.com", "user_metadata": {"hobby": "surfing"}, "app_metadata": {"plan": "full"}}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users"); var request = new RestRequest(Method.POST); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\"email\": \"jane.doe@example.com\", \"user_metadata\": {\"hobby\": \"surfing\"}, \"app_metadata\": {\"plan\": \"full\"}}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{"email": "jane.doe@example.com", "user_metadata": {"hobby": "surfing"}, "app_metadata": {"plan": "full"}}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -61,7 +64,7 @@ func main() { url := "https://{yourDomain}/api/v2/users" - payload := strings.NewReader("{\"email\": \"jane.doe@example.com\", \"user_metadata\": {\"hobby\": \"surfing\"}, \"app_metadata\": {\"plan\": \"full\"}}") + payload := strings.NewReader("{"email": "jane.doe@example.com", "user_metadata": {"hobby": "surfing"}, "app_metadata": {"plan": "full"}}") req, _ := http.NewRequest("POST", url, payload) @@ -76,13 +79,17 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/users") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/users") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("content-type", "application/json") - .body("{\"email\": \"jane.doe@example.com\", \"user_metadata\": {\"hobby\": \"surfing\"}, \"app_metadata\": {\"plan\": \"full\"}}") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{"email": "jane.doe@example.com", "user_metadata": {"hobby": "surfing"}, "app_metadata": {"plan": "full"}}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -102,8 +109,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @"content-type": @"application/json" }; @@ -130,8 +139,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users", @@ -141,7 +152,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{\"email\": \"jane.doe@example.com\", \"user_metadata\": {\"hobby\": \"surfing\"}, \"app_metadata\": {\"plan\": \"full\"}}", + CURLOPT_POSTFIELDS => "{"email": "jane.doe@example.com", "user_metadata": {"hobby": "surfing"}, "app_metadata": {"plan": "full"}}", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "content-type: application/json" @@ -157,12 +168,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"email\": \"jane.doe@example.com\", \"user_metadata\": {\"hobby\": \"surfing\"}, \"app_metadata\": {\"plan\": \"full\"}}" +payload = "{"email": "jane.doe@example.com", "user_metadata": {"hobby": "surfing"}, "app_metadata": {"plan": "full"}}" headers = { 'authorization': "Bearer MGMT_API_ACCESS_TOKEN", @@ -174,8 +187,10 @@ conn.request("POST", "/{yourDomain}/api/v2/users", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -188,11 +203,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["content-type"] = 'application/json' -request.body = "{\"email\": \"jane.doe@example.com\", \"user_metadata\": {\"hobby\": \"surfing\"}, \"app_metadata\": {\"plan\": \"full\"}}" +request.body = "{"email": "jane.doe@example.com", "user_metadata": {"hobby": "surfing"}, "app_metadata": {"plan": "full"}}" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "authorization": "Bearer MGMT_API_ACCESS_TOKEN", @@ -223,20 +240,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ### Update user metadata @@ -256,11 +262,6 @@ Assuming you created a user with the following metadata values: } ``` - - - - - To update `user_metadata` and add the user's home address as a second-level property: ```json lines @@ -271,25 +272,26 @@ To update `user_metadata` and add the user's home address as a second-level prop } ``` - - - - - You would make the following `PATCH` call: -export const codeExample11 = `curl --request PATCH \ + +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/users/user_id' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'content-type: application/json' \ - --data '{"user_metadata": {"addresses": {"home": "123 Main Street, Anytown, ST 12345"}}}'`; -export const codeExample12 = `var client = new RestClient("https://{yourDomain}/api/v2/users/user_id"); + --data '{"user_metadata": {"addresses": {"home": "123 Main Street, Anytown, ST 12345"}}}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users/user_id"); var request = new RestRequest(Method.PATCH); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\"user_metadata\": {\"addresses\": {\"home\": \"123 Main Street, Anytown, ST 12345\"}}}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample13 = `package main +request.AddParameter("application/json", "{"user_metadata": {"addresses": {"home": "123 Main Street, Anytown, ST 12345"}}}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -302,7 +304,7 @@ func main() { url := "https://{yourDomain}/api/v2/users/user_id" - payload := strings.NewReader("{\"user_metadata\": {\"addresses\": {\"home\": \"123 Main Street, Anytown, ST 12345\"}}}") + payload := strings.NewReader("{"user_metadata": {"addresses": {"home": "123 Main Street, Anytown, ST 12345"}}}") req, _ := http.NewRequest("PATCH", url, payload) @@ -317,13 +319,17 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample14 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/users/user_id") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/users/user_id") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("content-type", "application/json") - .body("{\"user_metadata\": {\"addresses\": {\"home\": \"123 Main Street, Anytown, ST 12345\"}}}") - .asString();`; -export const codeExample15 = `var axios = require("axios").default; + .body("{"user_metadata": {"addresses": {"home": "123 Main Street, Anytown, ST 12345"}}}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -339,8 +345,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample16 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @"content-type": @"application/json" }; @@ -365,8 +373,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users/user_id", @@ -376,7 +386,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{\"user_metadata\": {\"addresses\": {\"home\": \"123 Main Street, Anytown, ST 12345\"}}}", + CURLOPT_POSTFIELDS => "{"user_metadata": {"addresses": {"home": "123 Main Street, Anytown, ST 12345"}}}", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "content-type: application/json" @@ -392,12 +402,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"user_metadata\": {\"addresses\": {\"home\": \"123 Main Street, Anytown, ST 12345\"}}}" +payload = "{"user_metadata": {"addresses": {"home": "123 Main Street, Anytown, ST 12345"}}}" headers = { 'authorization': "Bearer MGMT_API_ACCESS_TOKEN", @@ -409,8 +421,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/users/user_id", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -423,11 +437,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Patch.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["content-type"] = 'application/json' -request.body = "{\"user_metadata\": {\"addresses\": {\"home\": \"123 Main Street, Anytown, ST 12345\"}}}" +request.body = "{"user_metadata": {"addresses": {"home": "123 Main Street, Anytown, ST 12345"}}}" response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "authorization": "Bearer MGMT_API_ACCESS_TOKEN", @@ -454,20 +470,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + The user's profile will now appear as follows: @@ -486,11 +491,6 @@ The user's profile will now appear as follows: } ``` - - - - - When you send a `PATCH` call in which you have set a property's value to `null` (for example, `{user_metadata: {color: null}}`), Auth0 **deletes** the property/value from the database. Also, patching the metadata itself with an empty object removes the metadata completely. @@ -514,25 +514,26 @@ For example, to add a user's work address as an additional inner property, you w } ``` - - - - - Therefore, the corresponding `PATCH` call to the API would be: -export const codeExample21 = `curl --request PATCH \ + +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/users/user_id' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'content-type: application/json' \ - --data '{"user_metadata": {"addresses": {"home": "123 Main Street, Anytown, ST 12345", "work": "100 Industrial Way, Anytown, ST 12345"}}}'`; -export const codeExample22 = `var client = new RestClient("https://{yourDomain}/api/v2/users/user_id"); + --data '{"user_metadata": {"addresses": {"home": "123 Main Street, Anytown, ST 12345", "work": "100 Industrial Way, Anytown, ST 12345"}}}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users/user_id"); var request = new RestRequest(Method.PATCH); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\"user_metadata\": {\"addresses\": {\"home\": \"123 Main Street, Anytown, ST 12345\", \"work\": \"100 Industrial Way, Anytown, ST 12345\"}}}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample23 = `package main +request.AddParameter("application/json", "{"user_metadata": {"addresses": {"home": "123 Main Street, Anytown, ST 12345", "work": "100 Industrial Way, Anytown, ST 12345"}}}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -545,7 +546,7 @@ func main() { url := "https://{yourDomain}/api/v2/users/user_id" - payload := strings.NewReader("{\"user_metadata\": {\"addresses\": {\"home\": \"123 Main Street, Anytown, ST 12345\", \"work\": \"100 Industrial Way, Anytown, ST 12345\"}}}") + payload := strings.NewReader("{"user_metadata": {"addresses": {"home": "123 Main Street, Anytown, ST 12345", "work": "100 Industrial Way, Anytown, ST 12345"}}}") req, _ := http.NewRequest("PATCH", url, payload) @@ -560,13 +561,17 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample24 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/users/user_id") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/users/user_id") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("content-type", "application/json") - .body("{\"user_metadata\": {\"addresses\": {\"home\": \"123 Main Street, Anytown, ST 12345\", \"work\": \"100 Industrial Way, Anytown, ST 12345\"}}}") - .asString();`; -export const codeExample25 = `var axios = require("axios").default; + .body("{"user_metadata": {"addresses": {"home": "123 Main Street, Anytown, ST 12345", "work": "100 Industrial Way, Anytown, ST 12345"}}}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -589,8 +594,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample26 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @"content-type": @"application/json" }; @@ -615,8 +622,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample27 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users/user_id", @@ -626,7 +635,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{\"user_metadata\": {\"addresses\": {\"home\": \"123 Main Street, Anytown, ST 12345\", \"work\": \"100 Industrial Way, Anytown, ST 12345\"}}}", + CURLOPT_POSTFIELDS => "{"user_metadata": {"addresses": {"home": "123 Main Street, Anytown, ST 12345", "work": "100 Industrial Way, Anytown, ST 12345"}}}", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "content-type: application/json" @@ -642,12 +651,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample28 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"user_metadata\": {\"addresses\": {\"home\": \"123 Main Street, Anytown, ST 12345\", \"work\": \"100 Industrial Way, Anytown, ST 12345\"}}}" +payload = "{"user_metadata": {"addresses": {"home": "123 Main Street, Anytown, ST 12345", "work": "100 Industrial Way, Anytown, ST 12345"}}}" headers = { 'authorization': "Bearer MGMT_API_ACCESS_TOKEN", @@ -659,8 +670,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/users/user_id", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample29 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -673,11 +686,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Patch.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["content-type"] = 'application/json' -request.body = "{\"user_metadata\": {\"addresses\": {\"home\": \"123 Main Street, Anytown, ST 12345\", \"work\": \"100 Industrial Way, Anytown, ST 12345\"}}}" +request.body = "{"user_metadata": {"addresses": {"home": "123 Main Street, Anytown, ST 12345", "work": "100 Industrial Way, Anytown, ST 12345"}}}" response = http.request(request) -puts response.read_body`; -export const codeExample30 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "authorization": "Bearer MGMT_API_ACCESS_TOKEN", @@ -707,20 +722,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ### Delete user metadata @@ -732,11 +736,6 @@ You can delete `user_metadata`: } ``` - - - - - ## App metadata Patching the metadata with an empty object removes the metadata completely. For example, sending this body removes everything in `app_metadata`: @@ -747,11 +746,6 @@ Patching the metadata with an empty object removes the metadata completely. For } ``` - - - - - ## Client metadata ### Create applications with client metadata @@ -780,22 +774,12 @@ Client metadata can be updated using the [`PATCH /api/v2/clients/{id}`](https:// } ``` - - - - - Request: `PATCH /api/v2/client/myclientid123` with body: ```json lines { "client_metadata": { "mycolor": "blue" } } ``` - - - - - **Application after:** ```json lines @@ -809,11 +793,6 @@ Request: `PATCH /api/v2/client/myclientid123` with body: } ``` - - - - - ### Delete client metadata properties and values Client metadata keys can be removed by issuing a PATCH, as described in "Update app_metadata" above, but supplying `null` for the key value. This behavior matches that of the `user_metadata` and `app_metadata` properties in the `PATCH` [/api/v2/users/{id}](https://auth0.com/docs/api/management/v2#!/Users/patch_users_by_id) endpoint. diff --git a/main/docs/manage-users/user-accounts/user-account-linking.mdx b/main/docs/manage-users/user-accounts/user-account-linking.mdx index d9675d5ca..489894240 100644 --- a/main/docs/manage-users/user-accounts/user-account-linking.mdx +++ b/main/docs/manage-users/user-accounts/user-account-linking.mdx @@ -11,6 +11,9 @@ title: User Account Linking identity providers. 'twitter:title': User Account Linking --- + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + Auth0 supports the linking of user accounts from various identity providers. This allows a user to authenticate from any of their accounts and still be recognized by your app and associated with the same user profile. @@ -42,7 +45,7 @@ The process of linking accounts merges two existing user profiles into a single In the example below you can see how the resulting linked profile will be for the sample primary and secondary accounts. - + ```json Profile of primary account lines expandable { "email": "your0@email.com", @@ -142,7 +145,7 @@ In the example below you can see how the resulting linked profile will be for th ... } ``` - + Note that: diff --git a/main/docs/manage-users/user-accounts/user-account-linking/link-user-accounts.mdx b/main/docs/manage-users/user-accounts/user-account-linking/link-user-accounts.mdx index 0b5a73dba..cd7adf98c 100644 --- a/main/docs/manage-users/user-accounts/user-account-linking/link-user-accounts.mdx +++ b/main/docs/manage-users/user-accounts/user-account-linking/link-user-accounts.mdx @@ -13,6 +13,8 @@ title: Link User Accounts --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + Both your specific login implementation and your Auth0 plan or custom agreement affect whether this feature is available. To learn more, read [Pricing](https://auth0.com/pricing). @@ -65,7 +67,6 @@ The following steps illustrate an example implementation: } ``` - @@ -87,7 +88,6 @@ The following steps illustrate an example implementation: } ``` - @@ -164,29 +164,29 @@ const getManagementClient = async (event, api) => { } /** - * @typedef {Object} CandidateUsersIdentities + * @typedef `{Object}` CandidateUsersIdentities * @property {string} user_id * @property {string} provider * @property {string} connection */ /** - * @typedef {Object} CandidateUsers + * @typedef `{Object}` CandidateUsers * @property {string} email - * @property {boolean} email_verified + * @property `{Boolean}` email_verified * @property {string} user_id * @property {CandidateUsersIdentities[]} identities */ /** - * @typedef {Object} CandidateIdentities + * @typedef `{Object}` CandidateIdentities * @property {User['user_id']} user_id * @property {string} connection * @property {string} provider */ /** - * @typedef {Object} LinkedIdentity + * @typedef `{Object}` LinkedIdentity * @property {User['user_id']} user_id */ @@ -377,11 +377,6 @@ exports.onContinuePostLogin = async (event, api) => { }; ``` - - - - - ## Management API You can use the Management API [Link a user account](https://auth0.com/docs/api/v2#!/Users/post_identities) endpoint in two ways: @@ -399,18 +394,24 @@ For user-initiated client-side account linking, you need an access token that co An access token that contains the `update:current_user_identities` scope can only be used to update the information of the currently logged-in user. Therefore, this method is suitable for scenarios where the user initiates the linking process. -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/api/v2/users/PRIMARY_ACCOUNT_USER_ID/identities' \ --header 'authorization: Bearer MANAGEMENT_API_ACCESS_TOKEN' \ --header 'content-type: application/json' \ - --data '{"link_with":"SECONDARY_ACCOUNT_ID_TOKEN"}'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/users/PRIMARY_ACCOUNT_USER_ID/identities"); + --data '{"link_with":"SECONDARY_ACCOUNT_ID_TOKEN"}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users/PRIMARY_ACCOUNT_USER_ID/identities"); var request = new RestRequest(Method.POST); request.AddHeader("authorization", "Bearer MANAGEMENT_API_ACCESS_TOKEN"); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\"link_with\":\"SECONDARY_ACCOUNT_ID_TOKEN\"}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{"link_with":"SECONDARY_ACCOUNT_ID_TOKEN"}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -423,7 +424,7 @@ func main() { url := "https://{yourDomain}/api/v2/users/PRIMARY_ACCOUNT_USER_ID/identities" - payload := strings.NewReader("{\"link_with\":\"SECONDARY_ACCOUNT_ID_TOKEN\"}") + payload := strings.NewReader("{"link_with":"SECONDARY_ACCOUNT_ID_TOKEN"}") req, _ := http.NewRequest("POST", url, payload) @@ -438,13 +439,17 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/users/PRIMARY_ACCOUNT_USER_ID/identities") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/users/PRIMARY_ACCOUNT_USER_ID/identities") .header("authorization", "Bearer MANAGEMENT_API_ACCESS_TOKEN") .header("content-type", "application/json") - .body("{\"link_with\":\"SECONDARY_ACCOUNT_ID_TOKEN\"}") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{"link_with":"SECONDARY_ACCOUNT_ID_TOKEN"}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -460,8 +465,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MANAGEMENT_API_ACCESS_TOKEN", @"content-type": @"application/json" }; @@ -486,8 +493,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users/PRIMARY_ACCOUNT_USER_ID/identities", @@ -497,7 +506,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{\"link_with\":\"SECONDARY_ACCOUNT_ID_TOKEN\"}", + CURLOPT_POSTFIELDS => "{"link_with":"SECONDARY_ACCOUNT_ID_TOKEN"}", CURLOPT_HTTPHEADER => [ "authorization: Bearer MANAGEMENT_API_ACCESS_TOKEN", "content-type: application/json" @@ -513,12 +522,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"link_with\":\"SECONDARY_ACCOUNT_ID_TOKEN\"}" +payload = "{"link_with":"SECONDARY_ACCOUNT_ID_TOKEN"}" headers = { 'authorization': "Bearer MANAGEMENT_API_ACCESS_TOKEN", @@ -530,8 +541,10 @@ conn.request("POST", "/{yourDomain}/api/v2/users/PRIMARY_ACCOUNT_USER_ID/identit res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -544,11 +557,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["authorization"] = 'Bearer MANAGEMENT_API_ACCESS_TOKEN' request["content-type"] = 'application/json' -request.body = "{\"link_with\":\"SECONDARY_ACCOUNT_ID_TOKEN\"}" +request.body = "{"link_with":"SECONDARY_ACCOUNT_ID_TOKEN"}" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "authorization": "Bearer MANAGEMENT_API_ACCESS_TOKEN", @@ -575,20 +590,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ### Server-side account linking @@ -601,18 +605,24 @@ For server-side account linking, you need an access token that contains the foll Access tokens that contain the `update:users` scope can be used to update the information of any user. Therefore, this method is intended for use in server-side code only. -export const codeExample11 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/api/v2/users/PRIMARY_ACCOUNT_USER_ID/identities' \ --header 'authorization: Bearer MANAGEMENT_API_ACCESS_TOKEN' \ --header 'content-type: application/json' \ - --data '{"provider":"SECONDARY_ACCOUNT_PROVIDER", "user_id": "SECONDARY_ACCOUNT_USER_ID"}'`; -export const codeExample12 = `var client = new RestClient("https://{yourDomain}/api/v2/users/PRIMARY_ACCOUNT_USER_ID/identities"); + --data '{"provider":"SECONDARY_ACCOUNT_PROVIDER", "user_id": "SECONDARY_ACCOUNT_USER_ID"}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users/PRIMARY_ACCOUNT_USER_ID/identities"); var request = new RestRequest(Method.POST); request.AddHeader("authorization", "Bearer MANAGEMENT_API_ACCESS_TOKEN"); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\"provider\":\"SECONDARY_ACCOUNT_PROVIDER\", \"user_id\": \"SECONDARY_ACCOUNT_USER_ID\"}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample13 = `package main +request.AddParameter("application/json", "{"provider":"SECONDARY_ACCOUNT_PROVIDER", "user_id": "SECONDARY_ACCOUNT_USER_ID"}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -625,7 +635,7 @@ func main() { url := "https://{yourDomain}/api/v2/users/PRIMARY_ACCOUNT_USER_ID/identities" - payload := strings.NewReader("{\"provider\":\"SECONDARY_ACCOUNT_PROVIDER\", \"user_id\": \"SECONDARY_ACCOUNT_USER_ID\"}") + payload := strings.NewReader("{"provider":"SECONDARY_ACCOUNT_PROVIDER", "user_id": "SECONDARY_ACCOUNT_USER_ID"}") req, _ := http.NewRequest("POST", url, payload) @@ -640,13 +650,17 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample14 = `HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/users/PRIMARY_ACCOUNT_USER_ID/identities") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/users/PRIMARY_ACCOUNT_USER_ID/identities") .header("authorization", "Bearer MANAGEMENT_API_ACCESS_TOKEN") .header("content-type", "application/json") - .body("{\"provider\":\"SECONDARY_ACCOUNT_PROVIDER\", \"user_id\": \"SECONDARY_ACCOUNT_USER_ID\"}") - .asString();`; -export const codeExample15 = `var axios = require("axios").default; + .body("{"provider":"SECONDARY_ACCOUNT_PROVIDER", "user_id": "SECONDARY_ACCOUNT_USER_ID"}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -662,8 +676,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample16 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MANAGEMENT_API_ACCESS_TOKEN", @"content-type": @"application/json" }; @@ -689,8 +705,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users/PRIMARY_ACCOUNT_USER_ID/identities", @@ -700,7 +718,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{\"provider\":\"SECONDARY_ACCOUNT_PROVIDER\", \"user_id\": \"SECONDARY_ACCOUNT_USER_ID\"}", + CURLOPT_POSTFIELDS => "{"provider":"SECONDARY_ACCOUNT_PROVIDER", "user_id": "SECONDARY_ACCOUNT_USER_ID"}", CURLOPT_HTTPHEADER => [ "authorization: Bearer MANAGEMENT_API_ACCESS_TOKEN", "content-type: application/json" @@ -716,12 +734,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"provider\":\"SECONDARY_ACCOUNT_PROVIDER\", \"user_id\": \"SECONDARY_ACCOUNT_USER_ID\"}" +payload = "{"provider":"SECONDARY_ACCOUNT_PROVIDER", "user_id": "SECONDARY_ACCOUNT_USER_ID"}" headers = { 'authorization': "Bearer MANAGEMENT_API_ACCESS_TOKEN", @@ -733,8 +753,10 @@ conn.request("POST", "/{yourDomain}/api/v2/users/PRIMARY_ACCOUNT_USER_ID/identit res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -747,11 +769,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["authorization"] = 'Bearer MANAGEMENT_API_ACCESS_TOKEN' request["content-type"] = 'application/json' -request.body = "{\"provider\":\"SECONDARY_ACCOUNT_PROVIDER\", \"user_id\": \"SECONDARY_ACCOUNT_USER_ID\"}" +request.body = "{"provider":"SECONDARY_ACCOUNT_PROVIDER", "user_id": "SECONDARY_ACCOUNT_USER_ID"}" response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "authorization": "Bearer MANAGEMENT_API_ACCESS_TOKEN", @@ -781,20 +805,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + The secondary user account's `user_id` and `provider` can be deduced by its unique identifier. For example, for the identifier `google-oauth2|108091299999329986433`: @@ -803,18 +816,24 @@ The secondary user account's `user_id` and `provider` can be deduced by its uniq Alternatively, you can you can send the secondary account's ID token instead of the `provider` and `user_id`: -export const codeExample21 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/api/v2/users/PRIMARY_ACCOUNT_USER_ID/identities' \ --header 'authorization: Bearer MANAGEMENT_API_ACCESS_TOKEN' \ --header 'content-type: application/json' \ - --data '{"link_with":"SECONDARY_ACCOUNT_ID_TOKEN"}'`; -export const codeExample22 = `var client = new RestClient("https://{yourDomain}/api/v2/users/PRIMARY_ACCOUNT_USER_ID/identities"); + --data '{"link_with":"SECONDARY_ACCOUNT_ID_TOKEN"}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users/PRIMARY_ACCOUNT_USER_ID/identities"); var request = new RestRequest(Method.POST); request.AddHeader("authorization", "Bearer MANAGEMENT_API_ACCESS_TOKEN"); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\"link_with\":\"SECONDARY_ACCOUNT_ID_TOKEN\"}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample23 = `package main +request.AddParameter("application/json", "{"link_with":"SECONDARY_ACCOUNT_ID_TOKEN"}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -827,7 +846,7 @@ func main() { url := "https://{yourDomain}/api/v2/users/PRIMARY_ACCOUNT_USER_ID/identities" - payload := strings.NewReader("{\"link_with\":\"SECONDARY_ACCOUNT_ID_TOKEN\"}") + payload := strings.NewReader("{"link_with":"SECONDARY_ACCOUNT_ID_TOKEN"}") req, _ := http.NewRequest("POST", url, payload) @@ -842,13 +861,17 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample24 = `HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/users/PRIMARY_ACCOUNT_USER_ID/identities") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/users/PRIMARY_ACCOUNT_USER_ID/identities") .header("authorization", "Bearer MANAGEMENT_API_ACCESS_TOKEN") .header("content-type", "application/json") - .body("{\"link_with\":\"SECONDARY_ACCOUNT_ID_TOKEN\"}") - .asString();`; -export const codeExample25 = `var axios = require("axios").default; + .body("{"link_with":"SECONDARY_ACCOUNT_ID_TOKEN"}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -864,8 +887,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample26 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MANAGEMENT_API_ACCESS_TOKEN", @"content-type": @"application/json" }; @@ -890,8 +915,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample27 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users/PRIMARY_ACCOUNT_USER_ID/identities", @@ -901,7 +928,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{\"link_with\":\"SECONDARY_ACCOUNT_ID_TOKEN\"}", + CURLOPT_POSTFIELDS => "{"link_with":"SECONDARY_ACCOUNT_ID_TOKEN"}", CURLOPT_HTTPHEADER => [ "authorization: Bearer MANAGEMENT_API_ACCESS_TOKEN", "content-type: application/json" @@ -917,12 +944,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample28 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"link_with\":\"SECONDARY_ACCOUNT_ID_TOKEN\"}" +payload = "{"link_with":"SECONDARY_ACCOUNT_ID_TOKEN"}" headers = { 'authorization': "Bearer MANAGEMENT_API_ACCESS_TOKEN", @@ -934,8 +963,10 @@ conn.request("POST", "/{yourDomain}/api/v2/users/PRIMARY_ACCOUNT_USER_ID/identit res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample29 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -948,11 +979,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["authorization"] = 'Bearer MANAGEMENT_API_ACCESS_TOKEN' request["content-type"] = 'application/json' -request.body = "{\"link_with\":\"SECONDARY_ACCOUNT_ID_TOKEN\"}" +request.body = "{"link_with":"SECONDARY_ACCOUNT_ID_TOKEN"}" response = http.request(request) -puts response.read_body`; -export const codeExample30 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "authorization": "Bearer MANAGEMENT_API_ACCESS_TOKEN", @@ -979,20 +1012,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ## Auth0.js library diff --git a/main/docs/manage-users/user-accounts/user-profiles/configure-connection-sync-with-auth0.mdx b/main/docs/manage-users/user-accounts/user-profiles/configure-connection-sync-with-auth0.mdx index 7c45b0644..3517240f7 100644 --- a/main/docs/manage-users/user-accounts/user-profiles/configure-connection-sync-with-auth0.mdx +++ b/main/docs/manage-users/user-accounts/user-profiles/configure-connection-sync-with-auth0.mdx @@ -12,6 +12,8 @@ title: Configure Identity Provider Connection for User Profile Updates --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + You can update connection preferences for an upstream identity provider so you can control when updates to user profile root attributes are allowed using the Auth0 Dashboard or the Management API. By default, user profile attributes provided by identity providers other than Auth0 (such as Google, Facebook, or X) are not directly editable because they are updated from the identity provider each time the user logs in. @@ -38,20 +40,26 @@ Before completing this step, you should first [retrieve the existing values of t Make a `PATCH` call to the [Update a Connection endpoint](https://auth0.com/docs/api/management/v2#!/Connections/patch_connections_by_id). Make sure you include the original options values in the call to avoid overriding the current values. Also, be sure to replace `CONNECTION_ID`, `MGMT_API_ACCESS_TOKEN`, and `ATTRIBUTE_UPDATE_VALUE` placeholder values with your connection ID, Management API access token, and attribute update value, respectively. -export const codeExample1 = `curl --request PATCH \ + +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/connections/CONNECTION_ID' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{"options":{"set_user_root_attributes": "ATTRIBUTE_UPDATE_VALUE"}}'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/connections/CONNECTION_ID"); + --data '{"options":{"set_user_root_attributes": "ATTRIBUTE_UPDATE_VALUE"}}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/connections/CONNECTION_ID"); var request = new RestRequest(Method.PATCH); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{\"options\":{\"set_user_root_attributes\": \"ATTRIBUTE_UPDATE_VALUE\"}}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{"options":{"set_user_root_attributes": "ATTRIBUTE_UPDATE_VALUE"}}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -64,7 +72,7 @@ func main() { url := "https://{yourDomain}/api/v2/connections/CONNECTION_ID" - payload := strings.NewReader("{\"options\":{\"set_user_root_attributes\": \"ATTRIBUTE_UPDATE_VALUE\"}}") + payload := strings.NewReader("{"options":{"set_user_root_attributes": "ATTRIBUTE_UPDATE_VALUE"}}") req, _ := http.NewRequest("PATCH", url, payload) @@ -80,14 +88,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/connections/CONNECTION_ID") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/connections/CONNECTION_ID") .header("content-type", "application/json") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{\"options\":{\"set_user_root_attributes\": \"ATTRIBUTE_UPDATE_VALUE\"}}") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{"options":{"set_user_root_attributes": "ATTRIBUTE_UPDATE_VALUE"}}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -104,8 +116,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @@ -131,8 +145,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/connections/CONNECTION_ID", @@ -142,7 +158,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{\"options\":{\"set_user_root_attributes\": \"ATTRIBUTE_UPDATE_VALUE\"}}", + CURLOPT_POSTFIELDS => "{"options":{"set_user_root_attributes": "ATTRIBUTE_UPDATE_VALUE"}}", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "cache-control: no-cache", @@ -159,12 +175,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"options\":{\"set_user_root_attributes\": \"ATTRIBUTE_UPDATE_VALUE\"}}" +payload = "{"options":{"set_user_root_attributes": "ATTRIBUTE_UPDATE_VALUE"}}" headers = { 'content-type': "application/json", @@ -177,8 +195,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/connections/CONNECTION_ID", payload, res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -192,11 +212,13 @@ request = Net::HTTP::Patch.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{\"options\":{\"set_user_root_attributes\": \"ATTRIBUTE_UPDATE_VALUE\"}}" +request.body = "{"options":{"set_user_root_attributes": "ATTRIBUTE_UPDATE_VALUE"}}" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -224,20 +246,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
    diff --git a/main/docs/manage-users/user-accounts/user-profiles/root-attributes/set-root-attributes-during-user-import.mdx b/main/docs/manage-users/user-accounts/user-profiles/root-attributes/set-root-attributes-during-user-import.mdx index b1e388c39..9e065d97b 100644 --- a/main/docs/manage-users/user-accounts/user-profiles/root-attributes/set-root-attributes-during-user-import.mdx +++ b/main/docs/manage-users/user-accounts/user-profiles/root-attributes/set-root-attributes-during-user-import.mdx @@ -12,22 +12,30 @@ title: Set Root Attributes During User Import --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + This guide will show you how to set root attributes for a user during import using Auth0's Management API. This allows you to minimize the number of API calls required to set root attributes when importing users. To see which attributes you can import, visit [Normalized User Profile Structure](/docs/manage-users/user-accounts/user-profiles/user-profile-structure). Make a `POST` call to the [Create Job to Import Users endpoint](https://auth0.com/docs/api/management/v2#!/Jobs/post_users_imports). Be sure to replace `MGMT_API_ACCESS_TOKEN`, `CONNECTION_ID`, and `JSON_USER_FILE_PATH` placeholder values with your Management API Access Token, connection ID, and users filename, respectively. -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/api/v2/jobs/usersimports' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'content-type: multipart/form-data ' \ - --data '{ "connection_id": "CONNECTION_ID", "users": "JSON_USER_FILE_PATH" }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/jobs/usersimports"); + --data '{ "connection_id": "CONNECTION_ID", "users": "JSON_USER_FILE_PATH" }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/jobs/usersimports"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "multipart/form-data "); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); -request.AddParameter("multipart/form-data ", "{ \"connection_id\": \"CONNECTION_ID\", \"users\": \"JSON_USER_FILE_PATH\" }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("multipart/form-data ", "{ "connection_id": "CONNECTION_ID", "users": "JSON_USER_FILE_PATH" }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -40,7 +48,7 @@ func main() { url := "https://{yourDomain}/api/v2/jobs/usersimports" - payload := strings.NewReader("{ \"connection_id\": \"CONNECTION_ID\", \"users\": \"JSON_USER_FILE_PATH\" }") + payload := strings.NewReader("{ "connection_id": "CONNECTION_ID", "users": "JSON_USER_FILE_PATH" }") req, _ := http.NewRequest("POST", url, payload) @@ -55,13 +63,17 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/jobs/usersimports") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/jobs/usersimports") .header("content-type", "multipart/form-data ") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") - .body("{ \"connection_id\": \"CONNECTION_ID\", \"users\": \"JSON_USER_FILE_PATH\" }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "connection_id": "CONNECTION_ID", "users": "JSON_USER_FILE_PATH" }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -77,8 +89,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"multipart/form-data ", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN" }; @@ -102,8 +116,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/jobs/usersimports", @@ -113,7 +129,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{ \"connection_id\": \"CONNECTION_ID\", \"users\": \"JSON_USER_FILE_PATH\" }", + CURLOPT_POSTFIELDS => "{ "connection_id": "CONNECTION_ID", "users": "JSON_USER_FILE_PATH" }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "content-type: multipart/form-data " @@ -129,12 +145,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"connection_id\": \"CONNECTION_ID\", \"users\": \"JSON_USER_FILE_PATH\" }" +payload = "{ "connection_id": "CONNECTION_ID", "users": "JSON_USER_FILE_PATH" }" headers = { 'content-type': "multipart/form-data ", @@ -146,8 +164,10 @@ conn.request("POST", "/{yourDomain}/api/v2/jobs/usersimports", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -160,11 +180,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["content-type"] = 'multipart/form-data ' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' -request.body = "{ \"connection_id\": \"CONNECTION_ID\", \"users\": \"JSON_USER_FILE_PATH\" }" +request.body = "{ "connection_id": "CONNECTION_ID", "users": "JSON_USER_FILE_PATH" }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "multipart/form-data ", @@ -190,20 +212,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
    diff --git a/main/docs/manage-users/user-accounts/user-profiles/root-attributes/set-root-attributes-during-user-sign-up.mdx b/main/docs/manage-users/user-accounts/user-profiles/root-attributes/set-root-attributes-during-user-sign-up.mdx index 15e4ae9b0..03483734a 100644 --- a/main/docs/manage-users/user-accounts/user-profiles/root-attributes/set-root-attributes-during-user-sign-up.mdx +++ b/main/docs/manage-users/user-accounts/user-profiles/root-attributes/set-root-attributes-during-user-sign-up.mdx @@ -12,24 +12,32 @@ title: Set Root Attributes During User Signup --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + You can set root attributes for a user during sign-up using Auth0's Management API. This allows you to minimize the number of API calls required to set root attributes when creating users. Make a `POST` call to the [Create a User endpoint](https://auth0.com/docs/api/management/v2#!/Users/post_users). Be sure to replace `MGMT_API_ACCESS_TOKEN`, `CONNECTION_NAME`, `EMAIL_VALUE`, `PASSWORD_VALUE`, `GIVEN_NAME_VALUE`, `FAMILY_NAME_VALUE`, `NAME_VALUE`, `NICKNAME_VALUE`, and `PICTURE` placeholder values with your Management API Access Token, initial connection name, email address, password, given name, family name, name, nickname, and picture URL, respectively. -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/api/v2/users' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{ "connection": CONNECTION_NAME, "email": EMAIL_VALUE, "password": PASSWORD_VALUE, "given_name": GIVEN_NAME_VALUE, "family_name": FAMILY_NAME_VALUE,"name": NAME_VALUE, "nickname": NICKNAME_VALUE,"picture": PICTURE_VALUE }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/users"); + --data '{ "connection": CONNECTION_NAME, "email": EMAIL_VALUE, "password": PASSWORD_VALUE, "given_name": GIVEN_NAME_VALUE, "family_name": FAMILY_NAME_VALUE,"name": NAME_VALUE, "nickname": NICKNAME_VALUE,"picture": PICTURE_VALUE }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{ \"connection\": CONNECTION_NAME, \"email\": EMAIL_VALUE, \"password\": PASSWORD_VALUE, \"given_name\": GIVEN_NAME_VALUE, \"family_name\": FAMILY_NAME_VALUE,\"name\": NAME_VALUE, \"nickname\": NICKNAME_VALUE,\"picture\": PICTURE_VALUE }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "connection": CONNECTION_NAME, "email": EMAIL_VALUE, "password": PASSWORD_VALUE, "given_name": GIVEN_NAME_VALUE, "family_name": FAMILY_NAME_VALUE,"name": NAME_VALUE, "nickname": NICKNAME_VALUE,"picture": PICTURE_VALUE }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -42,7 +50,7 @@ func main() { url := "https://{yourDomain}/api/v2/users" - payload := strings.NewReader("{ \"connection\": CONNECTION_NAME, \"email\": EMAIL_VALUE, \"password\": PASSWORD_VALUE, \"given_name\": GIVEN_NAME_VALUE, \"family_name\": FAMILY_NAME_VALUE,\"name\": NAME_VALUE, \"nickname\": NICKNAME_VALUE,\"picture\": PICTURE_VALUE }") + payload := strings.NewReader("{ "connection": CONNECTION_NAME, "email": EMAIL_VALUE, "password": PASSWORD_VALUE, "given_name": GIVEN_NAME_VALUE, "family_name": FAMILY_NAME_VALUE,"name": NAME_VALUE, "nickname": NICKNAME_VALUE,"picture": PICTURE_VALUE }") req, _ := http.NewRequest("POST", url, payload) @@ -58,14 +66,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/users") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/users") .header("content-type", "application/json") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ \"connection\": CONNECTION_NAME, \"email\": EMAIL_VALUE, \"password\": PASSWORD_VALUE, \"given_name\": GIVEN_NAME_VALUE, \"family_name\": FAMILY_NAME_VALUE,\"name\": NAME_VALUE, \"nickname\": NICKNAME_VALUE,\"picture\": PICTURE_VALUE }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "connection": CONNECTION_NAME, "email": EMAIL_VALUE, "password": PASSWORD_VALUE, "given_name": GIVEN_NAME_VALUE, "family_name": FAMILY_NAME_VALUE,"name": NAME_VALUE, "nickname": NICKNAME_VALUE,"picture": PICTURE_VALUE }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -82,8 +94,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @@ -108,8 +122,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users", @@ -119,7 +135,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{ \"connection\": CONNECTION_NAME, \"email\": EMAIL_VALUE, \"password\": PASSWORD_VALUE, \"given_name\": GIVEN_NAME_VALUE, \"family_name\": FAMILY_NAME_VALUE,\"name\": NAME_VALUE, \"nickname\": NICKNAME_VALUE,\"picture\": PICTURE_VALUE }", + CURLOPT_POSTFIELDS => "{ "connection": CONNECTION_NAME, "email": EMAIL_VALUE, "password": PASSWORD_VALUE, "given_name": GIVEN_NAME_VALUE, "family_name": FAMILY_NAME_VALUE,"name": NAME_VALUE, "nickname": NICKNAME_VALUE,"picture": PICTURE_VALUE }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "cache-control: no-cache", @@ -136,12 +152,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"connection\": CONNECTION_NAME, \"email\": EMAIL_VALUE, \"password\": PASSWORD_VALUE, \"given_name\": GIVEN_NAME_VALUE, \"family_name\": FAMILY_NAME_VALUE,\"name\": NAME_VALUE, \"nickname\": NICKNAME_VALUE,\"picture\": PICTURE_VALUE }" +payload = "{ "connection": CONNECTION_NAME, "email": EMAIL_VALUE, "password": PASSWORD_VALUE, "given_name": GIVEN_NAME_VALUE, "family_name": FAMILY_NAME_VALUE,"name": NAME_VALUE, "nickname": NICKNAME_VALUE,"picture": PICTURE_VALUE }" headers = { 'content-type': "application/json", @@ -154,8 +172,10 @@ conn.request("POST", "/{yourDomain}/api/v2/users", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -169,11 +189,13 @@ request = Net::HTTP::Post.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ \"connection\": CONNECTION_NAME, \"email\": EMAIL_VALUE, \"password\": PASSWORD_VALUE, \"given_name\": GIVEN_NAME_VALUE, \"family_name\": FAMILY_NAME_VALUE,\"name\": NAME_VALUE, \"nickname\": NICKNAME_VALUE,\"picture\": PICTURE_VALUE }" +request.body = "{ "connection": CONNECTION_NAME, "email": EMAIL_VALUE, "password": PASSWORD_VALUE, "given_name": GIVEN_NAME_VALUE, "family_name": FAMILY_NAME_VALUE,"name": NAME_VALUE, "nickname": NICKNAME_VALUE,"picture": PICTURE_VALUE }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -200,20 +222,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
    diff --git a/main/docs/manage-users/user-accounts/user-profiles/root-attributes/update-root-attributes-for-users.mdx b/main/docs/manage-users/user-accounts/user-profiles/root-attributes/update-root-attributes-for-users.mdx index 821bf7823..99ed66273 100644 --- a/main/docs/manage-users/user-accounts/user-profiles/root-attributes/update-root-attributes-for-users.mdx +++ b/main/docs/manage-users/user-accounts/user-profiles/root-attributes/update-root-attributes-for-users.mdx @@ -12,26 +12,34 @@ title: Update Root Attributes for Users --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + You can update root attributes for an existing user profile using Auth0's Management API. Auth0's [Normalized User Profile](/docs/manage-users/user-accounts/user-profiles/user-profile-structure) features root attributes that you can update. The specific root attributes that you can update depend on the [connection](/docs/authenticate/identity-providers) type you're using. For details relevant to the connection you are using, see [User Profile Root Attributes](/docs/manage-users/user-accounts/user-profiles/root-attributes). Make a `PATCH` call to the [Update a User endpoint](https://auth0.com/docs/api/management/v2/users/patch-users-by-id). Be sure to replace `USER_ID`, `MGMT_API_ACCESS_TOKEN`, `GIVEN_NAME_VALUE`, `FAMILY_NAME_VALUE`, `NAME_VALUE`, `NICKNAME_VALUE`, and `PICTURE` placeholder values with your user ID, Management API Access Token, given name, family name, name, nickname, and picture URL, respectively. -export const codeExample1 = `curl --request PATCH \ + +```bash cURL +curl --request PATCH \ --url 'https://{yourDomain}/api/v2/users/USER_ID' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ - --data '{ "given_name": GIVEN_NAME_VALUE, "family_name": FAMILY_NAME_VALUE,"name": NAME_VALUE, "nickname": NICKNAME_VALUE,"picture": PICTURE_VALUE }'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/users/USER_ID"); + --data '{ "given_name": GIVEN_NAME_VALUE, "family_name": FAMILY_NAME_VALUE,"name": NAME_VALUE, "nickname": NICKNAME_VALUE,"picture": PICTURE_VALUE }' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users/USER_ID"); var request = new RestRequest(Method.PATCH); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("cache-control", "no-cache"); -request.AddParameter("application/json", "{ \"given_name\": GIVEN_NAME_VALUE, \"family_name\": FAMILY_NAME_VALUE,\"name\": NAME_VALUE, \"nickname\": NICKNAME_VALUE,\"picture\": PICTURE_VALUE }", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{ "given_name": GIVEN_NAME_VALUE, "family_name": FAMILY_NAME_VALUE,"name": NAME_VALUE, "nickname": NICKNAME_VALUE,"picture": PICTURE_VALUE }", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -44,7 +52,7 @@ func main() { url := "https://{yourDomain}/api/v2/users/USER_ID" - payload := strings.NewReader("{ \"given_name\": GIVEN_NAME_VALUE, \"family_name\": FAMILY_NAME_VALUE,\"name\": NAME_VALUE, \"nickname\": NICKNAME_VALUE,\"picture\": PICTURE_VALUE }") + payload := strings.NewReader("{ "given_name": GIVEN_NAME_VALUE, "family_name": FAMILY_NAME_VALUE,"name": NAME_VALUE, "nickname": NICKNAME_VALUE,"picture": PICTURE_VALUE }") req, _ := http.NewRequest("PATCH", url, payload) @@ -60,14 +68,18 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/users/USER_ID") +} +``` +```java Java +HttpResponse response = Unirest.patch("https://{yourDomain}/api/v2/users/USER_ID") .header("content-type", "application/json") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("cache-control", "no-cache") - .body("{ \"given_name\": GIVEN_NAME_VALUE, \"family_name\": FAMILY_NAME_VALUE,\"name\": NAME_VALUE, \"nickname\": NICKNAME_VALUE,\"picture\": PICTURE_VALUE }") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{ "given_name": GIVEN_NAME_VALUE, "family_name": FAMILY_NAME_VALUE,"name": NAME_VALUE, "nickname": NICKNAME_VALUE,"picture": PICTURE_VALUE }") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'PATCH', @@ -84,8 +96,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @@ -110,8 +124,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users/USER_ID", @@ -121,7 +137,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "PATCH", - CURLOPT_POSTFIELDS => "{ \"given_name\": GIVEN_NAME_VALUE, \"family_name\": FAMILY_NAME_VALUE,\"name\": NAME_VALUE, \"nickname\": NICKNAME_VALUE,\"picture\": PICTURE_VALUE }", + CURLOPT_POSTFIELDS => "{ "given_name": GIVEN_NAME_VALUE, "family_name": FAMILY_NAME_VALUE,"name": NAME_VALUE, "nickname": NICKNAME_VALUE,"picture": PICTURE_VALUE }", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "cache-control: no-cache", @@ -138,12 +154,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{ \"given_name\": GIVEN_NAME_VALUE, \"family_name\": FAMILY_NAME_VALUE,\"name\": NAME_VALUE, \"nickname\": NICKNAME_VALUE,\"picture\": PICTURE_VALUE }" +payload = "{ "given_name": GIVEN_NAME_VALUE, "family_name": FAMILY_NAME_VALUE,"name": NAME_VALUE, "nickname": NICKNAME_VALUE,"picture": PICTURE_VALUE }" headers = { 'content-type': "application/json", @@ -156,8 +174,10 @@ conn.request("PATCH", "/{yourDomain}/api/v2/users/USER_ID", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -171,11 +191,13 @@ request = Net::HTTP::Patch.new(url) request["content-type"] = 'application/json' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["cache-control"] = 'no-cache' -request.body = "{ \"given_name\": GIVEN_NAME_VALUE, \"family_name\": FAMILY_NAME_VALUE,\"name\": NAME_VALUE, \"nickname\": NICKNAME_VALUE,\"picture\": PICTURE_VALUE }" +request.body = "{ "given_name": GIVEN_NAME_VALUE, "family_name": FAMILY_NAME_VALUE,"name": NAME_VALUE, "nickname": NICKNAME_VALUE,"picture": PICTURE_VALUE }" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -202,20 +224,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
    diff --git a/main/docs/manage-users/user-migration/bulk-user-exports.mdx b/main/docs/manage-users/user-migration/bulk-user-exports.mdx index b1e0fb03b..c1995919b 100644 --- a/main/docs/manage-users/user-migration/bulk-user-exports.mdx +++ b/main/docs/manage-users/user-migration/bulk-user-exports.mdx @@ -10,6 +10,8 @@ title: Bulk User Exports --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + You can use the `POST /api/v2/jobs/users-exports` endpoint to create a job that exports all users associated with a [connection](/docs/authenticate/identity-providers), or all users in the tenant. For a list of user profile fields that can be exported, read [User Profile Structure](/docs/manage-users/user-accounts/user-profiles/user-profile-structure). @@ -46,29 +48,30 @@ Optionally, find the `connection_id` and your Auth0 tenant domain name in the +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/api/v2/jobs/users-exports' \ --header 'authorization: Bearer {yourMgmtAPIAccessToken}' \ --header 'content-type: application/json' \ - --data '{"connection_id": "{yourConnectionId}", "format": "csv", "limit": 5, "fields": [{"name": "email"}, { "name": "identities[0].connection", "export_as": "provider" }]}'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/jobs/users-exports"); + --data '{"connection_id": "{yourConnectionId}", "format": "csv", "limit": 5, "fields": [{"name": "email"}, { "name": "identities[0].connection", "export_as": "provider" }]}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/jobs/users-exports"); var request = new RestRequest(Method.POST); request.AddHeader("authorization", "Bearer {yourMgmtAPIAccessToken}"); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\"connection_id\": \"{yourConnectionId}\", \"format\": \"csv\", \"limit\": 5, \"fields\": [{\"name\": \"email\"}, { \"name\": \"identities[0].connection\", \"export_as\": \"provider\" }]}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("application/json", "{"connection_id": "{yourConnectionId}", "format": "csv", "limit": 5, "fields": [{"name": "email"}, { "name": "identities[0].connection", "export_as": "provider" }]}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -81,7 +84,7 @@ func main() { url := "https://{yourDomain}/api/v2/jobs/users-exports" - payload := strings.NewReader("{\"connection_id\": \"{yourConnectionId}\", \"format\": \"csv\", \"limit\": 5, \"fields\": [{\"name\": \"email\"}, { \"name\": \"identities[0].connection\", \"export_as\": \"provider\" }]}") + payload := strings.NewReader("{"connection_id": "{yourConnectionId}", "format": "csv", "limit": 5, "fields": [{"name": "email"}, { "name": "identities[0].connection", "export_as": "provider" }]}") req, _ := http.NewRequest("POST", url, payload) @@ -96,13 +99,17 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/jobs/users-exports") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/jobs/users-exports") .header("authorization", "Bearer {yourMgmtAPIAccessToken}") .header("content-type", "application/json") - .body("{\"connection_id\": \"{yourConnectionId}\", \"format\": \"csv\", \"limit\": 5, \"fields\": [{\"name\": \"email\"}, { \"name\": \"identities[0].connection\", \"export_as\": \"provider\" }]}") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("{"connection_id": "{yourConnectionId}", "format": "csv", "limit": 5, "fields": [{"name": "email"}, { "name": "identities[0].connection", "export_as": "provider" }]}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -123,8 +130,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer {yourMgmtAPIAccessToken}", @"content-type": @"application/json" }; @@ -152,8 +161,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/jobs/users-exports", @@ -163,7 +174,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{\"connection_id\": \"{yourConnectionId}\", \"format\": \"csv\", \"limit\": 5, \"fields\": [{\"name\": \"email\"}, { \"name\": \"identities[0].connection\", \"export_as\": \"provider\" }]}", + CURLOPT_POSTFIELDS => "{"connection_id": "{yourConnectionId}", "format": "csv", "limit": 5, "fields": [{"name": "email"}, { "name": "identities[0].connection", "export_as": "provider" }]}", CURLOPT_HTTPHEADER => [ "authorization: Bearer {yourMgmtAPIAccessToken}", "content-type: application/json" @@ -179,12 +190,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"connection_id\": \"{yourConnectionId}\", \"format\": \"csv\", \"limit\": 5, \"fields\": [{\"name\": \"email\"}, { \"name\": \"identities[0].connection\", \"export_as\": \"provider\" }]}" +payload = "{"connection_id": "{yourConnectionId}", "format": "csv", "limit": 5, "fields": [{"name": "email"}, { "name": "identities[0].connection", "export_as": "provider" }]}" headers = { 'authorization': "Bearer {yourMgmtAPIAccessToken}", @@ -196,8 +209,10 @@ conn.request("POST", "/{yourDomain}/api/v2/jobs/users-exports", payload, headers res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -210,11 +225,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["authorization"] = 'Bearer {yourMgmtAPIAccessToken}' request["content-type"] = 'application/json' -request.body = "{\"connection_id\": \"{yourConnectionId}\", \"format\": \"csv\", \"limit\": 5, \"fields\": [{\"name\": \"email\"}, { \"name\": \"identities[0].connection\", \"export_as\": \"provider\" }]}" +request.body = "{"connection_id": "{yourConnectionId}", "format": "csv", "limit": 5, "fields": [{"name": "email"}, { "name": "identities[0].connection", "export_as": "provider" }]}" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "authorization": "Bearer {yourMgmtAPIAccessToken}", @@ -252,20 +269,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + The response should look something like this: @@ -297,11 +303,6 @@ The response should look something like this: } ``` - - - - - ## Include user metadata in exported CSV If you export user data in CSV format and want to include metadata information, specify each metadata field that you want to export. You can export up to 30 fields. @@ -330,25 +331,26 @@ For example, for metadata structured like this: } ``` - - - - - The export request (for all three fields) would look like this: -export const codeExample11 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/api/v2/jobs/users-exports' \ --header 'authorization: Bearer {yourMgmtAPIAccessToken}' \ --header 'content-type: application/json' \ - --data '{"connection_id": "{yourConnectionId}", "format": "csv", "limit": 5, "fields": [{"name": "email"}, {"name": "user_metadata.consent.given"}, {"name": "user_metadata.consent.date"}, {"name": "user_metadata.consent.text_details"}]}'`; -export const codeExample12 = `var client = new RestClient("https://{yourDomain}/api/v2/jobs/users-exports"); + --data '{"connection_id": "{yourConnectionId}", "format": "csv", "limit": 5, "fields": [{"name": "email"}, {"name": "user_metadata.consent.given"}, {"name": "user_metadata.consent.date"}, {"name": "user_metadata.consent.text_details"}]}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/jobs/users-exports"); var request = new RestRequest(Method.POST); request.AddHeader("authorization", "Bearer {yourMgmtAPIAccessToken}"); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\"connection_id\": \"{yourConnectionId}\", \"format\": \"csv\", \"limit\": 5, \"fields\": [{\"name\": \"email\"}, {\"name\": \"user_metadata.consent.given\"}, {\"name\": \"user_metadata.consent.date\"}, {\"name\": \"user_metadata.consent.text_details\"}]}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample13 = `package main +request.AddParameter("application/json", "{"connection_id": "{yourConnectionId}", "format": "csv", "limit": 5, "fields": [{"name": "email"}, {"name": "user_metadata.consent.given"}, {"name": "user_metadata.consent.date"}, {"name": "user_metadata.consent.text_details"}]}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -361,7 +363,7 @@ func main() { url := "https://{yourDomain}/api/v2/jobs/users-exports" - payload := strings.NewReader("{\"connection_id\": \"{yourConnectionId}\", \"format\": \"csv\", \"limit\": 5, \"fields\": [{\"name\": \"email\"}, {\"name\": \"user_metadata.consent.given\"}, {\"name\": \"user_metadata.consent.date\"}, {\"name\": \"user_metadata.consent.text_details\"}]}") + payload := strings.NewReader("{"connection_id": "{yourConnectionId}", "format": "csv", "limit": 5, "fields": [{"name": "email"}, {"name": "user_metadata.consent.given"}, {"name": "user_metadata.consent.date"}, {"name": "user_metadata.consent.text_details"}]}") req, _ := http.NewRequest("POST", url, payload) @@ -376,13 +378,17 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample14 = `HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/jobs/users-exports") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/jobs/users-exports") .header("authorization", "Bearer {yourMgmtAPIAccessToken}") .header("content-type", "application/json") - .body("{\"connection_id\": \"{yourConnectionId}\", \"format\": \"csv\", \"limit\": 5, \"fields\": [{\"name\": \"email\"}, {\"name\": \"user_metadata.consent.given\"}, {\"name\": \"user_metadata.consent.date\"}, {\"name\": \"user_metadata.consent.text_details\"}]}") - .asString();`; -export const codeExample15 = `var axios = require("axios").default; + .body("{"connection_id": "{yourConnectionId}", "format": "csv", "limit": 5, "fields": [{"name": "email"}, {"name": "user_metadata.consent.given"}, {"name": "user_metadata.consent.date"}, {"name": "user_metadata.consent.text_details"}]}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -408,8 +414,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample16 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer {yourMgmtAPIAccessToken}", @"content-type": @"application/json" }; @@ -437,8 +445,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/jobs/users-exports", @@ -448,7 +458,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{\"connection_id\": \"{yourConnectionId}\", \"format\": \"csv\", \"limit\": 5, \"fields\": [{\"name\": \"email\"}, {\"name\": \"user_metadata.consent.given\"}, {\"name\": \"user_metadata.consent.date\"}, {\"name\": \"user_metadata.consent.text_details\"}]}", + CURLOPT_POSTFIELDS => "{"connection_id": "{yourConnectionId}", "format": "csv", "limit": 5, "fields": [{"name": "email"}, {"name": "user_metadata.consent.given"}, {"name": "user_metadata.consent.date"}, {"name": "user_metadata.consent.text_details"}]}", CURLOPT_HTTPHEADER => [ "authorization: Bearer {yourMgmtAPIAccessToken}", "content-type: application/json" @@ -464,12 +474,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"connection_id\": \"{yourConnectionId}\", \"format\": \"csv\", \"limit\": 5, \"fields\": [{\"name\": \"email\"}, {\"name\": \"user_metadata.consent.given\"}, {\"name\": \"user_metadata.consent.date\"}, {\"name\": \"user_metadata.consent.text_details\"}]}" +payload = "{"connection_id": "{yourConnectionId}", "format": "csv", "limit": 5, "fields": [{"name": "email"}, {"name": "user_metadata.consent.given"}, {"name": "user_metadata.consent.date"}, {"name": "user_metadata.consent.text_details"}]}" headers = { 'authorization': "Bearer {yourMgmtAPIAccessToken}", @@ -481,8 +493,10 @@ conn.request("POST", "/{yourDomain}/api/v2/jobs/users-exports", payload, headers res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -495,11 +509,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["authorization"] = 'Bearer {yourMgmtAPIAccessToken}' request["content-type"] = 'application/json' -request.body = "{\"connection_id\": \"{yourConnectionId}\", \"format\": \"csv\", \"limit\": 5, \"fields\": [{\"name\": \"email\"}, {\"name\": \"user_metadata.consent.given\"}, {\"name\": \"user_metadata.consent.date\"}, {\"name\": \"user_metadata.consent.text_details\"}]}" +request.body = "{"connection_id": "{yourConnectionId}", "format": "csv", "limit": 5, "fields": [{"name": "email"}, {"name": "user_metadata.consent.given"}, {"name": "user_metadata.consent.date"}, {"name": "user_metadata.consent.text_details"}]}" response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "authorization": "Bearer {yourMgmtAPIAccessToken}", @@ -531,20 +547,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + @@ -568,18 +573,24 @@ Before you can import users using an export generated by Auth0, you'll need to c In this case, for the same example we used before, the request would look like this: -export const codeExample21 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/api/v2/jobs/users-exports' \ --header 'authorization: Bearer {yourMgmtAPIAccessToken}' \ --header 'content-type: application/json' \ - --data '{"connection_id": "{yourConnectionId}", "format": "json", "limit": 5, "fields": [{"name": "email"}, {"name": "user_metadata.consent"}]}'`; -export const codeExample22 = `var client = new RestClient("https://{yourDomain}/api/v2/jobs/users-exports"); + --data '{"connection_id": "{yourConnectionId}", "format": "json", "limit": 5, "fields": [{"name": "email"}, {"name": "user_metadata.consent"}]}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/jobs/users-exports"); var request = new RestRequest(Method.POST); request.AddHeader("authorization", "Bearer {yourMgmtAPIAccessToken}"); request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\"connection_id\": \"{yourConnectionId}\", \"format\": \"json\", \"limit\": 5, \"fields\": [{\"name\": \"email\"}, {\"name\": \"user_metadata.consent\"}]}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample23 = `package main +request.AddParameter("application/json", "{"connection_id": "{yourConnectionId}", "format": "json", "limit": 5, "fields": [{"name": "email"}, {"name": "user_metadata.consent"}]}", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -592,7 +603,7 @@ func main() { url := "https://{yourDomain}/api/v2/jobs/users-exports" - payload := strings.NewReader("{\"connection_id\": \"{yourConnectionId}\", \"format\": \"json\", \"limit\": 5, \"fields\": [{\"name\": \"email\"}, {\"name\": \"user_metadata.consent\"}]}") + payload := strings.NewReader("{"connection_id": "{yourConnectionId}", "format": "json", "limit": 5, "fields": [{"name": "email"}, {"name": "user_metadata.consent"}]}") req, _ := http.NewRequest("POST", url, payload) @@ -607,13 +618,17 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample24 = `HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/jobs/users-exports") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/jobs/users-exports") .header("authorization", "Bearer {yourMgmtAPIAccessToken}") .header("content-type", "application/json") - .body("{\"connection_id\": \"{yourConnectionId}\", \"format\": \"json\", \"limit\": 5, \"fields\": [{\"name\": \"email\"}, {\"name\": \"user_metadata.consent\"}]}") - .asString();`; -export const codeExample25 = `var axios = require("axios").default; + .body("{"connection_id": "{yourConnectionId}", "format": "json", "limit": 5, "fields": [{"name": "email"}, {"name": "user_metadata.consent"}]}") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -634,8 +649,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample26 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer {yourMgmtAPIAccessToken}", @"content-type": @"application/json" }; @@ -663,8 +680,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample27 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/jobs/users-exports", @@ -674,7 +693,7 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{\"connection_id\": \"{yourConnectionId}\", \"format\": \"json\", \"limit\": 5, \"fields\": [{\"name\": \"email\"}, {\"name\": \"user_metadata.consent\"}]}", + CURLOPT_POSTFIELDS => "{"connection_id": "{yourConnectionId}", "format": "json", "limit": 5, "fields": [{"name": "email"}, {"name": "user_metadata.consent"}]}", CURLOPT_HTTPHEADER => [ "authorization: Bearer {yourMgmtAPIAccessToken}", "content-type: application/json" @@ -690,12 +709,14 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample28 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "{\"connection_id\": \"{yourConnectionId}\", \"format\": \"json\", \"limit\": 5, \"fields\": [{\"name\": \"email\"}, {\"name\": \"user_metadata.consent\"}]}" +payload = "{"connection_id": "{yourConnectionId}", "format": "json", "limit": 5, "fields": [{"name": "email"}, {"name": "user_metadata.consent"}]}" headers = { 'authorization': "Bearer {yourMgmtAPIAccessToken}", @@ -707,8 +728,10 @@ conn.request("POST", "/{yourDomain}/api/v2/jobs/users-exports", payload, headers res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample29 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -721,11 +744,13 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["authorization"] = 'Bearer {yourMgmtAPIAccessToken}' request["content-type"] = 'application/json' -request.body = "{\"connection_id\": \"{yourConnectionId}\", \"format\": \"json\", \"limit\": 5, \"fields\": [{\"name\": \"email\"}, {\"name\": \"user_metadata.consent\"}]}" +request.body = "{"connection_id": "{yourConnectionId}", "format": "json", "limit": 5, "fields": [{"name": "email"}, {"name": "user_metadata.consent"}]}" response = http.request(request) -puts response.read_body`; -export const codeExample30 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "authorization": "Bearer {yourMgmtAPIAccessToken}", @@ -757,20 +782,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ## Check export status @@ -780,14 +794,20 @@ Provide the ID of the job (which you received in the response when creating the Require Scopes: `create:users`, `read:users`, `create:passwords_checking_job` -export const codeExample31 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/jobs/%7ByourJobId%7D' \ - --header 'authorization: Bearer {yourMgmtAPIAccessToken}'`; -export const codeExample32 = `var client = new RestClient("https://{yourDomain}/api/v2/jobs/%7ByourJobId%7D"); + --header 'authorization: Bearer {yourMgmtAPIAccessToken}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/jobs/%7ByourJobId%7D"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer {yourMgmtAPIAccessToken}"); -IRestResponse response = client.Execute(request);`; -export const codeExample33 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -811,11 +831,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample34 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/jobs/%7ByourJobId%7D") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/jobs/%7ByourJobId%7D") .header("authorization", "Bearer {yourMgmtAPIAccessToken}") - .asString();`; -export const codeExample35 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -827,8 +851,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample36 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer {yourMgmtAPIAccessToken}" }; @@ -848,8 +874,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample37 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/jobs/%7ByourJobId%7D", @@ -873,8 +901,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample38 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -885,8 +915,10 @@ conn.request("GET", "/{yourDomain}/api/v2/jobs/%7ByourJobId%7D", headers=headers res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample39 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -900,8 +932,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer {yourMgmtAPIAccessToken}' response = http.request(request) -puts response.read_body`; -export const codeExample40 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer {yourMgmtAPIAccessToken}"] @@ -921,21 +955,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - - +dataTask.resume() +``` + You should get a response like the following: @@ -968,11 +990,6 @@ You should get a response like the following: } ``` - - - - - ## Find export data You can access your export files using the URL provided as the value for the **location** parameter. The name of your tenant is also the name of your file. For example, if your tenant name is `auth0docs`, then your file will be `auth0docs.csv` or `auth0docs.json`. When you navigate to the URL, you will automatically begin downloading the file. @@ -1020,7 +1037,6 @@ You may want to filter your exported .csv file for particular subset of your dat mlr --csv filter '$last_login >= "2024-01-01T00:00:00Z"' file.csv > filtered.csv ``` - \ No newline at end of file diff --git a/main/docs/manage-users/user-migration/bulk-user-imports.mdx b/main/docs/manage-users/user-migration/bulk-user-imports.mdx index df3530e47..b49131840 100644 --- a/main/docs/manage-users/user-migration/bulk-user-imports.mdx +++ b/main/docs/manage-users/user-migration/bulk-user-imports.mdx @@ -11,6 +11,8 @@ title: Bulk User Imports --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + You can bulk import user data into Auth0 using the [Create Import Users Job](https://auth0.com/docs/api/management/v2#!/Jobs/post_users_imports) endpoint. Bulk imports are useful for migrating users from an existing database or service to Auth0. @@ -52,19 +54,39 @@ The file size limit for a bulk import is 500KB. You will need to start multiple To start a bulk user import job, make a `POST` request to the [Create Import Users Job](https://auth0.com/docs/api/management/v2#!/Jobs/post_users_imports) endpoint. Be sure to replace the `MGMT_API_ACCESS_TOKEN`, `USERS_IMPORT_FILE.json`, `CONNECTION_ID`, and `EXTERNAL_ID` placeholder values with your Management API Access Token, users JSON file, database [connection ID](/docs/authenticate/identity-providers/locate-the-connection-id), and external ID, respectively. -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/api/v2/jobs/users-imports' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ --form users=@USERS_IMPORT_FILE.json \ --form connection_id=CONNECTION_ID \ - --form external_id=EXTERNAL_ID`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/jobs/users-imports"); + --form external_id=EXTERNAL_ID +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/jobs/users-imports"); var request = new RestRequest(Method.POST); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); request.AddHeader("content-type", "multipart/form-data; boundary=---011000010111000001101001"); -request.AddParameter("multipart/form-data; boundary=---011000010111000001101001", "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"users\"; filename=\"USERS_IMPORT_FILE.json\"\r\nContent-Type: text/json\r\n\r\n\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"connection_id\"\r\n\r\nCONNECTION_ID\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"external_id\"\r\n\r\nEXTERNAL_ID\r\n-----011000010111000001101001--\r\n", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +request.AddParameter("multipart/form-data; boundary=---011000010111000001101001", "-----011000010111000001101001\r +Content-Disposition: form-data; name="users"; filename="USERS_IMPORT_FILE.json"\r +Content-Type: text/json\r +\r +\r +-----011000010111000001101001\r +Content-Disposition: form-data; name="connection_id"\r +\r +CONNECTION_ID\r +-----011000010111000001101001\r +Content-Disposition: form-data; name="external_id"\r +\r +EXTERNAL_ID\r +-----011000010111000001101001--\r +", ParameterType.RequestBody); +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -77,7 +99,21 @@ func main() { url := "https://{yourDomain}/api/v2/jobs/users-imports" - payload := strings.NewReader("-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"users\"; filename=\"USERS_IMPORT_FILE.json\"\r\nContent-Type: text/json\r\n\r\n\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"connection_id\"\r\n\r\nCONNECTION_ID\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"external_id\"\r\n\r\nEXTERNAL_ID\r\n-----011000010111000001101001--\r\n") + payload := strings.NewReader("-----011000010111000001101001\r +Content-Disposition: form-data; name="users"; filename="USERS_IMPORT_FILE.json"\r +Content-Type: text/json\r +\r +\r +-----011000010111000001101001\r +Content-Disposition: form-data; name="connection_id"\r +\r +CONNECTION_ID\r +-----011000010111000001101001\r +Content-Disposition: form-data; name="external_id"\r +\r +EXTERNAL_ID\r +-----011000010111000001101001--\r +") req, _ := http.NewRequest("POST", url, payload) @@ -92,13 +128,31 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/jobs/users-imports") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/api/v2/jobs/users-imports") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") .header("content-type", "multipart/form-data; boundary=---011000010111000001101001") - .body("-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"users\"; filename=\"USERS_IMPORT_FILE.json\"\r\nContent-Type: text/json\r\n\r\n\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"connection_id\"\r\n\r\nCONNECTION_ID\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"external_id\"\r\n\r\nEXTERNAL_ID\r\n-----011000010111000001101001--\r\n") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .body("-----011000010111000001101001\r +Content-Disposition: form-data; name="users"; filename="USERS_IMPORT_FILE.json"\r +Content-Type: text/json\r +\r +\r +-----011000010111000001101001\r +Content-Disposition: form-data; name="connection_id"\r +\r +CONNECTION_ID\r +-----011000010111000001101001\r +Content-Disposition: form-data; name="external_id"\r +\r +EXTERNAL_ID\r +-----011000010111000001101001--\r +") + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -107,15 +161,31 @@ var options = { authorization: 'Bearer MGMT_API_ACCESS_TOKEN', 'content-type': 'multipart/form-data; boundary=---011000010111000001101001' }, - data: '-----011000010111000001101001\r\nContent-Disposition: form-data; name="users"; filename="USERS_IMPORT_FILE.json"\r\nContent-Type: text/json\r\n\r\n\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name="connection_id"\r\n\r\nCONNECTION_ID\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name="external_id"\r\n\r\nEXTERNAL_ID\r\n-----011000010111000001101001--\r\n' + data: '-----011000010111000001101001\r +Content-Disposition: form-data; name="users"; filename="USERS_IMPORT_FILE.json"\r +Content-Type: text/json\r +\r +\r +-----011000010111000001101001\r +Content-Disposition: form-data; name="connection_id"\r +\r +CONNECTION_ID\r +-----011000010111000001101001\r +Content-Disposition: form-data; name="external_id"\r +\r +EXTERNAL_ID\r +-----011000010111000001101001--\r +' }; axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN", @"content-type": @"multipart/form-data; boundary=---011000010111000001101001" }; @@ -127,20 +197,28 @@ NSString *boundary = @"---011000010111000001101001"; NSError *error; NSMutableString *body = [NSMutableString string]; for (NSDictionary *param in parameters) { - [body appendFormat:@"--%@\r\n", boundary]; + [body appendFormat:@"--%@\r +", boundary]; if (param[@"fileName"]) { - [body appendFormat:@"Content-Disposition:form-data; name=\"%@\"; filename=\"%@\"\r\n", param[@"name"], param[@"fileName"]]; - [body appendFormat:@"Content-Type: %@\r\n\r\n", param[@"contentType"]]; + [body appendFormat:@"Content-Disposition:form-data; name="%@"; filename="%@"\r +", param[@"name"], param[@"fileName"]]; + [body appendFormat:@"Content-Type: %@\r +\r +", param[@"contentType"]]; [body appendFormat:@"%@", [NSString stringWithContentsOfFile:param[@"fileName"] encoding:NSUTF8StringEncoding error:&error]]; if (error) { NSLog(@"%@", error); } } else { - [body appendFormat:@"Content-Disposition:form-data; name=\"%@\"\r\n\r\n", param[@"name"]]; + [body appendFormat:@"Content-Disposition:form-data; name="%@"\r +\r +", param[@"name"]]; [body appendFormat:@"%@", param[@"value"]]; } } -[body appendFormat:@"\r\n--%@--\r\n", boundary]; +[body appendFormat:@"\r +--%@--\r +", boundary]; NSData *postData = [body dataUsingEncoding:NSUTF8StringEncoding]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://{yourDomain}/api/v2/jobs/users-imports"] @@ -160,8 +238,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/jobs/users-imports", @@ -171,7 +251,21 @@ curl_setopt_array($curl, [ CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"users\"; filename=\"USERS_IMPORT_FILE.json\"\r\nContent-Type: text/json\r\n\r\n\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"connection_id\"\r\n\r\nCONNECTION_ID\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"external_id\"\r\n\r\nEXTERNAL_ID\r\n-----011000010111000001101001--\r\n", + CURLOPT_POSTFIELDS => "-----011000010111000001101001\r +Content-Disposition: form-data; name="users"; filename="USERS_IMPORT_FILE.json"\r +Content-Type: text/json\r +\r +\r +-----011000010111000001101001\r +Content-Disposition: form-data; name="connection_id"\r +\r +CONNECTION_ID\r +-----011000010111000001101001\r +Content-Disposition: form-data; name="external_id"\r +\r +EXTERNAL_ID\r +-----011000010111000001101001--\r +", CURLOPT_HTTPHEADER => [ "authorization: Bearer MGMT_API_ACCESS_TOKEN", "content-type: multipart/form-data; boundary=---011000010111000001101001" @@ -187,12 +281,28 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") -payload = "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"users\"; filename=\"USERS_IMPORT_FILE.json\"\r\nContent-Type: text/json\r\n\r\n\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"connection_id\"\r\n\r\nCONNECTION_ID\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"external_id\"\r\n\r\nEXTERNAL_ID\r\n-----011000010111000001101001--\r\n" +payload = "-----011000010111000001101001\r +Content-Disposition: form-data; name="users"; filename="USERS_IMPORT_FILE.json"\r +Content-Type: text/json\r +\r +\r +-----011000010111000001101001\r +Content-Disposition: form-data; name="connection_id"\r +\r +CONNECTION_ID\r +-----011000010111000001101001\r +Content-Disposition: form-data; name="external_id"\r +\r +EXTERNAL_ID\r +-----011000010111000001101001--\r +" headers = { 'authorization': "Bearer MGMT_API_ACCESS_TOKEN", @@ -204,8 +314,10 @@ conn.request("POST", "/{yourDomain}/api/v2/jobs/users-imports", payload, headers res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -218,11 +330,27 @@ http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' request["content-type"] = 'multipart/form-data; boundary=---011000010111000001101001' -request.body = "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"users\"; filename=\"USERS_IMPORT_FILE.json\"\r\nContent-Type: text/json\r\n\r\n\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"connection_id\"\r\n\r\nCONNECTION_ID\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"external_id\"\r\n\r\nEXTERNAL_ID\r\n-----011000010111000001101001--\r\n" +request.body = "-----011000010111000001101001\r +Content-Disposition: form-data; name="users"; filename="USERS_IMPORT_FILE.json"\r +Content-Type: text/json\r +\r +\r +-----011000010111000001101001\r +Content-Disposition: form-data; name="connection_id"\r +\r +CONNECTION_ID\r +-----011000010111000001101001\r +Content-Disposition: form-data; name="external_id"\r +\r +EXTERNAL_ID\r +-----011000010111000001101001--\r +" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "authorization": "Bearer MGMT_API_ACCESS_TOKEN", @@ -250,19 +378,25 @@ var body = "" var error: NSError? = nil for param in parameters { let paramName = param["name"]! - body += "--\(boundary)\r\n" - body += "Content-Disposition:form-data; name=\"\(paramName)\"" + body += "--\(boundary)\r +" + body += "Content-Disposition:form-data; name="\(paramName)"" if let filename = param["fileName"] { let contentType = param["content-type"]! let fileContent = String(contentsOfFile: filename, encoding: String.Encoding.utf8) if (error != nil) { print(error) } - body += "; filename=\"\(filename)\"\r\n" - body += "Content-Type: \(contentType)\r\n\r\n" + body += "; filename="\(filename)"\r +" + body += "Content-Type: \(contentType)\r +\r +" body += fileContent } else if let paramValue = param["value"] { - body += "\r\n\r\n\(paramValue)" + body += "\r +\r +\(paramValue)" } } @@ -283,20 +417,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` +
    @@ -343,11 +466,6 @@ If the request is successful, you'll receive a response similar to the following } ``` - - - - - The returned entity represents the import job. When the user import job finishes and if `send_completion_email` was set to `true`, the tenant administrator(s) will get an email notifying them that job either failed or succeeded. An email for a job that failed might notify the administrator(s) that it failed to parse the users JSON file when importing users. @@ -364,25 +482,26 @@ The [Create Import Users Job](https://auth0.com/docs/api/management/v2#!/Jobs/po } ``` - - - - - ## Check job status To check a job's status, make a `GET` request to the [Get a Job](https://auth0.com/docs/api/management/v2#!/Jobs/get_jobs_by_id) endpoint. Be sure to replace the `MGMT_API_ACCESS_TOKEN` and `JOB_ID` placeholder values with your Management API Access Token and user import job ID. -export const codeExample11 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/jobs/JOB_ID' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ - --header 'content-type: application/json'`; -export const codeExample12 = `var client = new RestClient("https://{yourDomain}/api/v2/jobs/JOB_ID"); + --header 'content-type: application/json' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/jobs/JOB_ID"); var request = new RestRequest(Method.GET); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); -IRestResponse response = client.Execute(request);`; -export const codeExample13 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -407,12 +526,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample14 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/jobs/JOB_ID") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/jobs/JOB_ID") .header("content-type", "application/json") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") - .asString();`; -export const codeExample15 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -427,8 +550,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample16 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN" }; @@ -449,8 +574,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/jobs/JOB_ID", @@ -475,8 +602,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -490,8 +619,10 @@ conn.request("GET", "/{yourDomain}/api/v2/jobs/JOB_ID", headers=headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -506,8 +637,10 @@ request["content-type"] = 'application/json' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -530,20 +663,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + Depending on the status of the user import job, you'll receive a response similar to one of the following: @@ -560,11 +682,6 @@ Depending on the status of the user import job, you'll receive a response simila } ``` - - - - - **Completed** If a job is completed, the job status response will include totals of successful, failed, inserted, and updated records. @@ -586,11 +703,6 @@ If a job is completed, the job status response will include totals of successful } ``` - - - - - **Failed** If there is an error in the job, it will return as failed. However, note that invalid user information, such as an invalid email, will not make the entire job fail. @@ -606,11 +718,6 @@ If there is an error in the job, it will return as failed. However, note that in } ``` - - - - - To learn details for failed entries see **Retrieve failed entries** below. ## Job timeouts @@ -629,16 +736,22 @@ All of the job-related data is automatically deleted after 24 hours and cannot b If there were errors in the user import job, you can get the error details by making a `GET` request to the [Get Job Error Details](https://auth0.com/docs/api/management/v2#!/Jobs/get_errors) endpoint. Be sure to replace the `MGMT_API_ACCESS_TOKEN` and `JOB_ID` placeholder values with your Management API Access Token and user import job ID. -export const codeExample21 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/jobs/JOB_ID/errors' \ --header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' \ - --header 'content-type: application/json'`; -export const codeExample22 = `var client = new RestClient("https://{yourDomain}/api/v2/jobs/JOB_ID/errors"); + --header 'content-type: application/json' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/jobs/JOB_ID/errors"); var request = new RestRequest(Method.GET); request.AddHeader("content-type", "application/json"); request.AddHeader("authorization", "Bearer MGMT_API_ACCESS_TOKEN"); -IRestResponse response = client.Execute(request);`; -export const codeExample23 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -663,12 +776,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample24 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/jobs/JOB_ID/errors") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/jobs/JOB_ID/errors") .header("content-type", "application/json") .header("authorization", "Bearer MGMT_API_ACCESS_TOKEN") - .asString();`; -export const codeExample25 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -683,8 +800,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample26 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/json", @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN" }; @@ -705,8 +824,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample27 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/jobs/JOB_ID/errors", @@ -731,8 +852,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample28 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -746,8 +869,10 @@ conn.request("GET", "/{yourDomain}/api/v2/jobs/JOB_ID/errors", headers=headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample29 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -762,8 +887,10 @@ request["content-type"] = 'application/json' request["authorization"] = 'Bearer MGMT_API_ACCESS_TOKEN' response = http.request(request) -puts response.read_body`; -export const codeExample30 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = [ "content-type": "application/json", @@ -786,20 +913,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + If the request is successful, you'll receive a response similar to the following. Sensitive fields such as `hash.value` will be redacted in the response. @@ -827,11 +943,6 @@ If the request is successful, you'll receive a response similar to the following ] ``` - - - - - Each error object will include an error code and a message explaining the error in more detail. The possible error codes are: * ANY_OF_MISSING diff --git a/main/docs/manage-users/user-search/retrieve-users-with-get-users-by-email-endpoint.mdx b/main/docs/manage-users/user-search/retrieve-users-with-get-users-by-email-endpoint.mdx index dd3fb5881..06ac9c320 100644 --- a/main/docs/manage-users/user-search/retrieve-users-with-get-users-by-email-endpoint.mdx +++ b/main/docs/manage-users/user-search/retrieve-users-with-get-users-by-email-endpoint.mdx @@ -12,6 +12,8 @@ title: Retrieve Users with Get Users by Email Endpoint --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + The [`GET /api/v2/users-by-email` endpoint](https://auth0.com/docs/api/management/v2#!/Users_By_Email/get_users_by_email) allows you to search for users using their email addresses. The search looks for an exact match to the provided email address and is case-sensitive. This endpoint is **immediately consistent**, and as such, we recommend that you use this endpoint for: @@ -25,14 +27,20 @@ The request must include a [Management API access token](/docs/secure/tokens/acc Required Scopes: `read:users` -export const codeExample1 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/users-by-email?email=%7BuserEmailAddress%7D' \ - --header 'authorization: Bearer {yourMgmtApiAccessToken}'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/users-by-email?email=%7BuserEmailAddress%7D"); + --header 'authorization: Bearer {yourMgmtApiAccessToken}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users-by-email?email=%7BuserEmailAddress%7D"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer {yourMgmtApiAccessToken}"); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -56,11 +64,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/users-by-email?email=%7BuserEmailAddress%7D") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/users-by-email?email=%7BuserEmailAddress%7D") .header("authorization", "Bearer {yourMgmtApiAccessToken}") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -73,8 +85,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer {yourMgmtApiAccessToken}" }; @@ -94,8 +108,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users-by-email?email=%7BuserEmailAddress%7D", @@ -119,8 +135,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -131,8 +149,10 @@ conn.request("GET", "/{yourDomain}/api/v2/users-by-email?email=%7BuserEmailAddre res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -146,8 +166,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer {yourMgmtApiAccessToken}' response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer {yourMgmtApiAccessToken}"] @@ -167,20 +189,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ```json lines expandable [ @@ -219,5 +230,3 @@ dataTask.resume()`; ] ``` - - diff --git a/main/docs/manage-users/user-search/retrieve-users-with-get-users-by-id-endpoint.mdx b/main/docs/manage-users/user-search/retrieve-users-with-get-users-by-id-endpoint.mdx index ec9364b39..d1de3c8a8 100644 --- a/main/docs/manage-users/user-search/retrieve-users-with-get-users-by-id-endpoint.mdx +++ b/main/docs/manage-users/user-search/retrieve-users-with-get-users-by-id-endpoint.mdx @@ -11,6 +11,8 @@ title: Retrieve Users with the Get Users by ID Endpoint --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + The [`GET /api/v2/users/{id}` endpoint](https://auth0.com/docs/api/management/v2#!/Users/get_users_by_id) allows you to retrieve a specific user using their Auth0 user ID. This endpoint is **immediately consistent**, and as such, we recommend that you use this endpoint for: @@ -26,14 +28,20 @@ The request must include a [Management API access token](/docs/secure/tokens/acc Required Scopes: `read:users` -export const codeExample1 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/users/%7BuserId%7D' \ - --header 'authorization: Bearer {yourMgmtApiAccessToken}'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/users/%7BuserId%7D"); + --header 'authorization: Bearer {yourMgmtApiAccessToken}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users/%7BuserId%7D"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer {yourMgmtApiAccessToken}"); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -57,11 +65,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/users/%7BuserId%7D") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/users/%7BuserId%7D") .header("authorization", "Bearer {yourMgmtApiAccessToken}") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -73,8 +85,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer {yourMgmtApiAccessToken}" }; @@ -94,8 +108,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users/%7BuserId%7D", @@ -119,8 +135,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -131,8 +149,10 @@ conn.request("GET", "/{yourDomain}/api/v2/users/%7BuserId%7D", headers=headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -146,8 +166,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer {yourMgmtApiAccessToken}' response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer {yourMgmtApiAccessToken}"] @@ -167,20 +189,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ```json lines expandable { @@ -217,5 +228,3 @@ dataTask.resume()`; } ``` - - diff --git a/main/docs/manage-users/user-search/retrieve-users-with-get-users-endpoint.mdx b/main/docs/manage-users/user-search/retrieve-users-with-get-users-endpoint.mdx index 50ebddc72..cd01ea75d 100644 --- a/main/docs/manage-users/user-search/retrieve-users-with-get-users-endpoint.mdx +++ b/main/docs/manage-users/user-search/retrieve-users-with-get-users-endpoint.mdx @@ -10,6 +10,8 @@ title: Retrieve Users with the Get Users Endpoint --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + The [`GET /api/v2/users` endpoint](https://auth0.com/docs/api/management/v2#!/Users/get_users) allows you to retrieve a list of users. Using this endpoint, you can: * Search based on a variety of criteria @@ -24,14 +26,20 @@ To search for users, make a `GET` request to the [`/api/v2/users` endpoint](http For example, to search for a user whose email is exactly `jane@exampleco.com`, use `q=email:"jane@exampleco.com"`: -export const codeExample1 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/users?q=email%3A%22jane%40exampleco.com%22&search_engine=v3' \ - --header 'authorization: Bearer {yourMgmtApiAccessToken}'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/users?q=email%3A%22jane%40exampleco.com%22&search_engine=v3"); + --header 'authorization: Bearer {yourMgmtApiAccessToken}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users?q=email%3A%22jane%40exampleco.com%22&search_engine=v3"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer {yourMgmtApiAccessToken}"); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -55,11 +63,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/users?q=email%3A%22jane%40exampleco.com%22&search_engine=v3") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/users?q=email%3A%22jane%40exampleco.com%22&search_engine=v3") .header("authorization", "Bearer {yourMgmtApiAccessToken}") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -72,8 +84,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer {yourMgmtApiAccessToken}" }; @@ -93,8 +107,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users?q=email%3A%22jane%40exampleco.com%22&search_engine=v3", @@ -118,8 +134,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -130,8 +148,10 @@ conn.request("GET", "/{yourDomain}/api/v2/users?q=email%3A%22jane%40exampleco.co res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -145,8 +165,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer {yourMgmtApiAccessToken}' response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer {yourMgmtApiAccessToken}"] @@ -166,20 +188,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + If successful, you'll receive a response like this: @@ -220,11 +231,6 @@ If successful, you'll receive a response like this: ] ``` - - - - - ## Query examples Below are some examples of the kinds of queries you can make with the Management API. diff --git a/main/docs/manage-users/user-search/sort-search-results.mdx b/main/docs/manage-users/user-search/sort-search-results.mdx index 3b58591ce..40f32e51f 100644 --- a/main/docs/manage-users/user-search/sort-search-results.mdx +++ b/main/docs/manage-users/user-search/sort-search-results.mdx @@ -12,20 +12,28 @@ title: Sort Search Results --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + To sort user search results, pass a `field:order` value to the `sort` parameter when making your request. The `field` is the name of the field to sort by, while order can be set to `1` for ascending order and `-1` for descending. Sorting by `app_metadata` or `user_metadata` is not supported. For example, to sort users in ascending order by the `created_at` field you can pass the value `created_at:1` to the `sort` parameter: -export const codeExample1 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/users?q=logins_count%3A%5B100%20TO%20200%5D&sort=created_at%3A1&search_engine=v3' \ - --header 'authorization: Bearer {yourMgmtApiAccessToken}'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/users?q=logins_count%3A%5B100%20TO%20200%5D&sort=created_at%3A1&search_engine=v3"); + --header 'authorization: Bearer {yourMgmtApiAccessToken}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users?q=logins_count%3A%5B100%20TO%20200%5D&sort=created_at%3A1&search_engine=v3"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer {yourMgmtApiAccessToken}"); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -49,11 +57,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/users?q=logins_count%3A%5B100%20TO%20200%5D&sort=created_at%3A1&search_engine=v3") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/users?q=logins_count%3A%5B100%20TO%20200%5D&sort=created_at%3A1&search_engine=v3") .header("authorization", "Bearer {yourMgmtApiAccessToken}") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -66,8 +78,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer {yourMgmtApiAccessToken}" }; @@ -87,8 +101,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users?q=logins_count%3A%5B100%20TO%20200%5D&sort=created_at%3A1&search_engine=v3", @@ -112,8 +128,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -124,8 +142,10 @@ conn.request("GET", "/{yourDomain}/api/v2/users?q=logins_count%3A%5B100%20TO%202 res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -139,8 +159,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer {yourMgmtApiAccessToken}' response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer {yourMgmtApiAccessToken}"] @@ -160,19 +182,8 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + To learn more about `sort` and other parameters, read the [Management API Explorer](https://auth0.com/docs/api/management/v2#!/Users/get_users) documentation. \ No newline at end of file diff --git a/main/docs/manage-users/user-search/user-search-query-syntax.mdx b/main/docs/manage-users/user-search/user-search-query-syntax.mdx index 099d4371c..9634cf82e 100644 --- a/main/docs/manage-users/user-search/user-search-query-syntax.mdx +++ b/main/docs/manage-users/user-search/user-search-query-syntax.mdx @@ -10,6 +10,8 @@ title: User Search Query Syntax --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + This content describes the current Auth0 user search, version 3. @@ -111,14 +113,20 @@ To find exact matches, use double quotes: `name:"jane smith"`. For example, to find users with the name `jane smith`, use `q=name:"jane smith"`: -export const codeExample1 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/users?q=name%3A%22jane%20smith%22&search_engine=v3' \ - --header 'authorization: Bearer {yourMgmtApiAccessToken}'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/users?q=name%3A%22jane%20smith%22&search_engine=v3"); + --header 'authorization: Bearer {yourMgmtApiAccessToken}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users?q=name%3A%22jane%20smith%22&search_engine=v3"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer {yourMgmtApiAccessToken}"); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -142,11 +150,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/users?q=name%3A%22jane%20smith%22&search_engine=v3") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/users?q=name%3A%22jane%20smith%22&search_engine=v3") .header("authorization", "Bearer {yourMgmtApiAccessToken}") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -159,8 +171,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer {yourMgmtApiAccessToken}" }; @@ -180,8 +194,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users?q=name%3A%22jane%20smith%22&search_engine=v3", @@ -205,8 +221,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -217,8 +235,10 @@ conn.request("GET", "/{yourDomain}/api/v2/users?q=name%3A%22jane%20smith%22&sear res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -232,8 +252,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer {yourMgmtApiAccessToken}' response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer {yourMgmtApiAccessToken}"] @@ -253,20 +275,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ## Wildcards @@ -279,14 +290,20 @@ Wildcard searches can be run on terms using the asterisk character (`*`) to repl * `q=name:john*` returns all users whose names start with `john`. * For suffix matching, literals must have 3 characters or more. For example, `name:*usa` is allowed, but `name:*sa` is not. -export const codeExample11 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/users?q=name%3Ajohn*&search_engine=v3' \ - --header 'authorization: Bearer {yourMgmtApiAccessToken}'`; -export const codeExample12 = `var client = new RestClient("https://{yourDomain}/api/v2/users?q=name%3Ajohn\*&search_engine=v3"); + --header 'authorization: Bearer {yourMgmtApiAccessToken}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users?q=name%3Ajohn\*&search_engine=v3"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer {yourMgmtApiAccessToken}"); -IRestResponse response = client.Execute(request);`; -export const codeExample13 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -310,11 +327,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample14 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/users?q=name%3Ajohn*&search_engine=v3") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/users?q=name%3Ajohn*&search_engine=v3") .header("authorization", "Bearer {yourMgmtApiAccessToken}") - .asString();`; -export const codeExample15 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -327,8 +348,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample16 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer {yourMgmtApiAccessToken}" }; @@ -348,8 +371,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users?q=name%3Ajohn*&search_engine=v3", @@ -373,8 +398,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -385,8 +412,10 @@ conn.request("GET", "/{yourDomain}/api/v2/users?q=name%3Ajohn*&search_engine=v3" res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -400,8 +429,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer {yourMgmtApiAccessToken}' response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer {yourMgmtApiAccessToken}"] @@ -421,20 +452,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ## Ranges @@ -445,14 +465,20 @@ You can use ranges in your user search queries. Range searches are not available * Curly and square brackets can be combined in the same range expression: `logins_count:[100 TO 200}`. * Use ranges in combination with wildcards. For example, to find all users with more than 100 logins, use `q=logins_count:{100 TO *]`. -export const codeExample21 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/users?q=logins_count%3A%7B100%20TO%20*%5D&search_engine=v3' \ - --header 'authorization: Bearer {yourMgmtApiAccessToken}'`; -export const codeExample22 = `var client = new RestClient("https://{yourDomain}/api/v2/users?q=logins_count%3A%7B100%20TO%20\*%5D&search_engine=v3"); + --header 'authorization: Bearer {yourMgmtApiAccessToken}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users?q=logins_count%3A%7B100%20TO%20\*%5D&search_engine=v3"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer {yourMgmtApiAccessToken}"); -IRestResponse response = client.Execute(request);`; -export const codeExample23 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -476,11 +502,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample24 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/users?q=logins_count%3A%7B100%20TO%20*%5D&search_engine=v3") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/users?q=logins_count%3A%7B100%20TO%20*%5D&search_engine=v3") .header("authorization", "Bearer {yourMgmtApiAccessToken}") - .asString();`; -export const codeExample25 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -493,8 +523,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample26 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer {yourMgmtApiAccessToken}" }; @@ -514,8 +546,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample27 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users?q=logins_count%3A%7B100%20TO%20*%5D&search_engine=v3", @@ -539,8 +573,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample28 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -551,8 +587,10 @@ conn.request("GET", "/{yourDomain}/api/v2/users?q=logins_count%3A%7B100%20TO%20* res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample29 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -566,8 +604,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer {yourMgmtApiAccessToken}' response = http.request(request) -puts response.read_body`; -export const codeExample30 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer {yourMgmtApiAccessToken}"] @@ -587,20 +627,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ## Searchable Profile Attribute Examples @@ -624,11 +653,6 @@ Below is a sample of a user profile `user_metadata`: } ``` - - - - - ### Filter metadata attributes To return a `user_metadata` value, update the `q` query with a filter for the attribute. diff --git a/main/docs/manage-users/user-search/view-search-results-by-page.mdx b/main/docs/manage-users/user-search/view-search-results-by-page.mdx index cb89ea0c2..8f2f09d4c 100644 --- a/main/docs/manage-users/user-search/view-search-results-by-page.mdx +++ b/main/docs/manage-users/user-search/view-search-results-by-page.mdx @@ -10,6 +10,8 @@ title: View Search Results by Page --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + To page the user search results, use the `page`, `per_page`, and `include_totals` parameters at your request.
    @@ -36,14 +38,20 @@ To page the user search results, use the `page`, `per_page`, and `include_totals ## Sample request -export const codeExample1 = `curl --request GET \ + +```bash cURL +curl --request GET \ --url 'https://{yourDomain}/api/v2/users?q=logins_count%3A%5B100%20TO%20200%5D&page=2&per_page=10&include_totals=true&search_engine=v3' \ - --header 'authorization: Bearer {yourMgmtApiAccessToken}'`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/api/v2/users?q=logins_count%3A%5B100%20TO%20200%5D&page=2&per_page=10&include_totals=true&search_engine=v3"); + --header 'authorization: Bearer {yourMgmtApiAccessToken}' +``` +```csharp C# +var client = new RestClient("https://{yourDomain}/api/v2/users?q=logins_count%3A%5B100%20TO%20200%5D&page=2&per_page=10&include_totals=true&search_engine=v3"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", "Bearer {yourMgmtApiAccessToken}"); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -67,11 +75,15 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/users?q=logins_count%3A%5B100%20TO%20200%5D&page=2&per_page=10&include_totals=true&search_engine=v3") +} +``` +```java Java +HttpResponse response = Unirest.get("https://{yourDomain}/api/v2/users?q=logins_count%3A%5B100%20TO%20200%5D&page=2&per_page=10&include_totals=true&search_engine=v3") .header("authorization", "Bearer {yourMgmtApiAccessToken}") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'GET', @@ -90,8 +102,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"authorization": @"Bearer {yourMgmtApiAccessToken}" }; @@ -111,8 +125,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/api/v2/users?q=logins_count%3A%5B100%20TO%20200%5D&page=2&per_page=10&include_totals=true&search_engine=v3", @@ -136,8 +152,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -148,8 +166,10 @@ conn.request("GET", "/{yourDomain}/api/v2/users?q=logins_count%3A%5B100%20TO%202 res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -163,8 +183,10 @@ request = Net::HTTP::Get.new(url) request["authorization"] = 'Bearer {yourMgmtApiAccessToken}' response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["authorization": "Bearer {yourMgmtApiAccessToken}"] @@ -184,20 +206,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + ## Sample response @@ -217,11 +228,6 @@ A sample response body for the values set in the above sample request is as foll } ``` - - - - - ## Limitation Auth0 limits the total number of users you can retrieve to 1000 (for example, 100 users per page for 10 pages). When the `page` parameter is not set, we return a maximum of 50 records, regardless of how many records exist. diff --git a/main/docs/quickstart/backend/aspnet-core-webapi/02-using.mdx b/main/docs/quickstart/backend/aspnet-core-webapi/02-using.mdx index 52bb43a18..d7539508c 100644 --- a/main/docs/quickstart/backend/aspnet-core-webapi/02-using.mdx +++ b/main/docs/quickstart/backend/aspnet-core-webapi/02-using.mdx @@ -4,6 +4,7 @@ permalink: "02-using" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; ##### By Damien Guard @@ -13,8 +14,7 @@ This tutorial will show you how to use your API. We recommend that you log in to You can call the API from your application by passing an Access Token in the `Authorization` header of your HTTP request as a Bearer token. - - + ```bash lines curl --request GET \ --url http://localhost:3010/api/private \ @@ -184,7 +184,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + ## Obtaining an Access Token @@ -197,19 +197,25 @@ If you are calling the API from a command-line tool or another service, where th Read [Application Settings](https://auth0.com/docs/get-started/dashboard/application-settings) for more information on getting the Client ID and Client Secret for your machine-to-machine app. -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=client_credentials \ --data 'client_id={yourClientId}' \ --data client_secret=YOUR_CLIENT_SECRET \ - --data audience=YOUR_API_IDENTIFIER`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data audience=YOUR_API_IDENTIFIER +``` +```cs C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=client_credentials&client_id=%24%7Baccount.clientId%7D&client_secret=YOUR_CLIENT_SECRET&audience=YOUR_API_IDENTIFIER", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -236,12 +242,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=client_credentials&client_id=%24%7Baccount.clientId%7D&client_secret=YOUR_CLIENT_SECRET&audience=YOUR_API_IDENTIFIER") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -259,8 +269,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -286,8 +298,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -312,8 +326,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -326,8 +342,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -342,8 +360,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=client_credentials&client_id=%24%7Baccount.clientId%7D&client_secret=YOUR_CLIENT_SECRET&audience=YOUR_API_IDENTIFIER" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -369,20 +389,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + Auth0 customers are billed based on the number of Machine to Machine Access Tokens issued by Auth0. Once your application gets an Access Token it should keep using it until it expires, to minimize the number of tokens requested. @@ -394,7 +403,7 @@ For testing purposes, you can also get an Access Token from the **Test** tab in You can make a request to the `/api/private` endpoint without passing any Access Token: - + ```bash cURL lines curl --request GET \ @@ -495,7 +504,6 @@ if ($err) { } ``` - ```python Python lines import http.client @@ -523,7 +531,6 @@ response = http.request(request) puts response.read_body ``` - ```swift Swift lines import Foundation @@ -545,7 +552,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + The API will return a 401 HTTP (Unauthorized) status code: @@ -553,7 +560,7 @@ The API will return a 401 HTTP (Unauthorized) status code: Once again, make the same request but this time pass along the Access Token as a Bearer token in the **Authorization** header of the request: - + ```bash lines curl --request GET \ --url http://localhost:3010/api/private \ @@ -723,7 +730,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + This time the API will return a successful response: @@ -733,7 +740,7 @@ This time the API will return a successful response: To test the endpoint that requires a scope, pass the Access Token containing the correct scope as a Bearer token in the Authorization header: - + ```bash cURL lines curl --request GET \ @@ -904,7 +911,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + If the required scope is present, the API call is successful: diff --git a/main/docs/quickstart/backend/aspnet-core-webapi/_index.mdx b/main/docs/quickstart/backend/aspnet-core-webapi/_index.mdx index 5f1a64d01..9fb66aa6f 100644 --- a/main/docs/quickstart/backend/aspnet-core-webapi/_index.mdx +++ b/main/docs/quickstart/backend/aspnet-core-webapi/_index.mdx @@ -11,6 +11,8 @@ import Hasscopehandler from "/snippets/quickstart/backend/aspnet-core-webapi/Has import Hasscoperequirement from "/snippets/quickstart/backend/aspnet-core-webapi/HasScopeRequirement.cs.mdx"; import Apicontroller from "/snippets/quickstart/backend/aspnet-core-webapi/ApiController.cs.mdx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + export const sections = [ { id: "define-permissions", title: "Define permissions" }, { id: "install-dependencies", title: "Install dependencies" }, @@ -88,13 +90,13 @@ export const sections = [ `UseAuthentication`and `UseAuthorization`methods under the `var app = builder.Build();`method. - + - +
    @@ -109,13 +111,13 @@ export const sections = [ 3. Add policies for scopes by calling `AddPolicy`for each scope. 4. Register a singleton for the `HasScopeHandler`class. - + - +
    @@ -128,13 +130,13 @@ export const sections = [ `access_token`. To do so, add the `Authorize` attribute to the `Scoped` action and pass `read:messages` as the `policy` parameter. - + - +
    @@ -168,7 +170,7 @@ export const sections = [ **Example request** - + ```sh cURL lines curl --request post \ --url 'https://dev-gja8kxz4ndtex3rq.us.auth0.com/oauth/token' \ @@ -315,7 +317,7 @@ export const sections = [ puts response.read_body ``` - + ### Call a secure endpoint @@ -325,7 +327,7 @@ export const sections = [ example, you can make a request to the `/api/private` endpoint: - + ```sh cURL lines curl --request get \ --url http://localhost:3010/api/private \ @@ -481,7 +483,7 @@ export const sections = [ dataTask.resume() ``` - + Call the `/api/private-scoped` endpoint in a similar way, but ensure that the API permissions are diff --git a/main/docs/quickstart/backend/aspnet-core-webapi/interactive.mdx b/main/docs/quickstart/backend/aspnet-core-webapi/interactive.mdx index 5d9e40d47..f1f989634 100644 --- a/main/docs/quickstart/backend/aspnet-core-webapi/interactive.mdx +++ b/main/docs/quickstart/backend/aspnet-core-webapi/interactive.mdx @@ -24,6 +24,8 @@ import Apicontroller from "/snippets/quickstart/backend/aspnet-core-webapi/ApiCo import {QuickstartButtons} from "/snippets/QuickstartButtons.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + export const sections = [ @@ -155,7 +157,7 @@ export const sections = [ **Example request** - + ```sh cURL lines curl --request post \ --url 'https://dev-gja8kxz4ndtex3rq.us.auth0.com/oauth/token' \ @@ -302,7 +304,7 @@ export const sections = [ puts response.read_body ``` - + ### Call a secure endpoint @@ -312,7 +314,7 @@ export const sections = [ example, you can make a request to the `/api/private` endpoint: - + ```sh cURL lines curl --request get \ --url http://localhost:3010/api/private \ @@ -468,7 +470,7 @@ export const sections = [ dataTask.resume() ``` - + Call the `/api/private-scoped` endpoint in a similar way, but ensure that the API permissions are @@ -508,33 +510,33 @@ export const sections = [ - + - + - + - + - + - + diff --git a/main/docs/quickstart/backend/django/02-using.mdx b/main/docs/quickstart/backend/django/02-using.mdx index 9792fa3ef..e66163303 100644 --- a/main/docs/quickstart/backend/django/02-using.mdx +++ b/main/docs/quickstart/backend/django/02-using.mdx @@ -4,6 +4,7 @@ permalink: "02-using" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; ##### By Luciano Balmaceda @@ -13,8 +14,7 @@ This tutorial will show you how to use your API. We recommend that you log in to You can call the API from your application by passing an Access Token in the `Authorization` header of your HTTP request as a Bearer token. - - + ```bash lines curl --request GET \ --url http://localhost:3010/api/private \ @@ -184,7 +184,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + ## Obtaining an Access Token @@ -197,19 +197,25 @@ If you are calling the API from a command-line tool or another service, where th Read [Application Settings](https://auth0.com/docs/get-started/dashboard/application-settings) for more information on getting the Client ID and Client Secret for your machine-to-machine app. -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=client_credentials \ --data 'client_id={yourClientId}' \ --data client_secret=YOUR_CLIENT_SECRET \ - --data audience=YOUR_API_IDENTIFIER`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data audience=YOUR_API_IDENTIFIER +``` +```cs C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=client_credentials&client_id=%24%7Baccount.clientId%7D&client_secret=YOUR_CLIENT_SECRET&audience=YOUR_API_IDENTIFIER", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -236,12 +242,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=client_credentials&client_id=%24%7Baccount.clientId%7D&client_secret=YOUR_CLIENT_SECRET&audience=YOUR_API_IDENTIFIER") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -259,8 +269,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -286,8 +298,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -312,8 +326,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -326,8 +342,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -342,8 +360,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=client_credentials&client_id=%24%7Baccount.clientId%7D&client_secret=YOUR_CLIENT_SECRET&audience=YOUR_API_IDENTIFIER" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -369,20 +389,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + Auth0 customers are billed based on the number of Machine to Machine Access Tokens issued by Auth0. Once your application gets an Access Token it should keep using it until it expires, to minimize the number of tokens requested. @@ -394,7 +403,7 @@ For testing purposes, you can also get an Access Token from the **Test** tab in You can make a request to the `/api/private` endpoint without passing any Access Token: - + ```bash cURL lines curl --request GET \ @@ -495,7 +504,6 @@ if ($err) { } ``` - ```python Python lines import http.client @@ -523,7 +531,6 @@ response = http.request(request) puts response.read_body ``` - ```swift Swift lines import Foundation @@ -545,7 +552,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + The API will return a 401 HTTP (Unauthorized) status code: @@ -553,7 +560,7 @@ The API will return a 401 HTTP (Unauthorized) status code: Once again, make the same request but this time pass along the Access Token as a Bearer token in the **Authorization** header of the request: - + ```bash lines curl --request GET \ --url http://localhost:3010/api/private \ @@ -723,7 +730,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + This time the API will return a successful response: @@ -733,7 +740,7 @@ This time the API will return a successful response: To test the endpoint that requires a scope, pass the Access Token containing the correct scope as a Bearer token in the Authorization header: - + ```bash cURL lines curl --request GET \ @@ -904,7 +911,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + If the required scope is present, the API call is successful: diff --git a/main/docs/quickstart/backend/django/_index.mdx b/main/docs/quickstart/backend/django/_index.mdx index 7292a179a..def4f9188 100644 --- a/main/docs/quickstart/backend/django/_index.mdx +++ b/main/docs/quickstart/backend/django/_index.mdx @@ -9,6 +9,8 @@ import Validator from "/snippets/quickstart/backend/django/validator.py.mdx"; import Views from "/snippets/quickstart/backend/django/views.py.mdx"; import Urls from "/snippets/quickstart/backend/django/urls.py.mdx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + export const sections = [ { id: "define-permissions", title: "Define permissions" }, { id: "configure-django-to-use-auth0", title: "Configure Django to use Auth0" }, @@ -81,11 +83,11 @@ export const sections = [ Create the file `apiexample/validator.py` using the code from the interactive panel. - + - +
    @@ -105,11 +107,11 @@ export const sections = [ The `require_auth` decorator on the `private_scoped` route accepts an additional argument `"read:messages"`, which checks the Access Token for the Permission (Scope) you created earlier. - + - +
    @@ -128,7 +130,7 @@ export const sections = [ Provide the access token as an `Authorization` header in your requests. - + ```bash cURL lines curl --request get \ --url 'http:///%7ByourDomain%7D.com/api_path' \ @@ -278,14 +280,14 @@ export const sections = [ }) dataTask.resume() ``` - + - + - +
    ## Next Steps diff --git a/main/docs/quickstart/backend/django/interactive.mdx b/main/docs/quickstart/backend/django/interactive.mdx index a87909c77..19bd58aea 100644 --- a/main/docs/quickstart/backend/django/interactive.mdx +++ b/main/docs/quickstart/backend/django/interactive.mdx @@ -22,6 +22,8 @@ import Urls from "/snippets/quickstart/backend/django/urls.py.mdx"; import {QuickstartButtons} from "/snippets/QuickstartButtons.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + export const sections = [ @@ -127,7 +129,7 @@ export const sections = [ Provide the access token as an `Authorization` header in your requests. - + ```bash cURL lines curl --request get \ --url 'http:///%7ByourDomain%7D.com/api_path' \ @@ -277,7 +279,7 @@ export const sections = [ }) dataTask.resume() ``` - + @@ -301,27 +303,27 @@ export const sections = [ - + - + - + - + - + - + diff --git a/main/docs/quickstart/backend/golang/02-using.mdx b/main/docs/quickstart/backend/golang/02-using.mdx index c21a1ba4e..c4e23c950 100644 --- a/main/docs/quickstart/backend/golang/02-using.mdx +++ b/main/docs/quickstart/backend/golang/02-using.mdx @@ -4,7 +4,7 @@ permalink: "02-using" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; - +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; ##### By Sergiu Ghitea @@ -14,7 +14,7 @@ This tutorial will show you how to use your API.We recommend that you log in to You can call the API from your application by passing an Access Token in the `Authorization` header of your HTTP request as a Bearer token. - + ```bash cURL lines curl --request GET \ --url http://localhost:3010/api/private \ @@ -184,11 +184,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - - - - - + ## Obtaining an Access Token @@ -201,19 +197,25 @@ If you are calling the API from a command-line tool or another service, where th Read [Application Settings](https://auth0.com/docs/get-started/dashboard/application-settings) for more information on getting the Client ID and Client Secret for your machine-to-machine app. -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=client_credentials \ --data 'client_id={yourClientId}' \ --data client_secret=YOUR_CLIENT_SECRET \ - --data audience=YOUR_API_IDENTIFIER`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data audience=YOUR_API_IDENTIFIER +``` +```cs C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=client_credentials&client_id=%24%7Baccount.clientId%7D&client_secret=YOUR_CLIENT_SECRET&audience=YOUR_API_IDENTIFIER", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -240,12 +242,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=client_credentials&client_id=%24%7Baccount.clientId%7D&client_secret=YOUR_CLIENT_SECRET&audience=YOUR_API_IDENTIFIER") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -263,8 +269,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -290,8 +298,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -316,8 +326,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -330,8 +342,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -346,8 +360,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=client_credentials&client_id=%24%7Baccount.clientId%7D&client_secret=YOUR_CLIENT_SECRET&audience=YOUR_API_IDENTIFIER" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -373,23 +389,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - - - - +dataTask.resume() +``` + Auth0 customers are billed based on the number of Machine to Machine Access Tokens issued by Auth0. Once your application gets an Access Token it should keep using it until it expires, to minimize the number of tokens requested. @@ -401,7 +403,7 @@ For testing purposes, you can also get an Access Token from the **Test** tab in You can make a request to the `/api/private` endpoint without passing any Access Token: - + ```bash cURL lines curl --request GET \ @@ -502,7 +504,6 @@ if ($err) { } ``` - ```python Python lines import http.client @@ -530,7 +531,6 @@ response = http.request(request) puts response.read_body ``` - ```swift Swift lines import Foundation @@ -552,10 +552,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - - - - + The API will return a 401 HTTP (Unauthorized) status code: @@ -563,7 +560,7 @@ The API will return a 401 HTTP (Unauthorized) status code: Once again, make the same request but this time pass along the Access Token as a Bearer token in the **Authorization** header of the request: - + ```bash cURL lines curl --request GET \ --url http://localhost:3010/api/private \ @@ -733,11 +730,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - - - - - + This time the API will return a successful response: @@ -747,7 +740,7 @@ This time the API will return a successful response: To test the endpoint that requires a scope, pass the Access Token containing the correct scope as a Bearer token in the Authorization header: - + ```bash cURL lines curl --request GET \ @@ -918,8 +911,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - - + If the required scope is present, the API call is successful: @@ -929,5 +921,4 @@ If the required scope is not present, the API returns a 403 HTTP Status (Forbidd ![Response for forbidden scoped API request](https://cdn2.auth0.com/docs/1.14550.0/media/articles/server-apis/using/private-scoped-forbidden.png) - [Edit on GitHub](https://github.com/auth0/docs/edit/master/articles/quickstart/backend/golang/02-using.md) \ No newline at end of file diff --git a/main/docs/quickstart/backend/golang/_index.mdx b/main/docs/quickstart/backend/golang/_index.mdx index 7dd43c841..874413b66 100644 --- a/main/docs/quickstart/backend/golang/_index.mdx +++ b/main/docs/quickstart/backend/golang/_index.mdx @@ -8,6 +8,8 @@ import { LoggedInForm } from "/snippets/Login.jsx"; import Jwt from "/snippets/quickstart/backend/golang/jwt.go.mdx"; import Main from "/snippets/quickstart/backend/golang/main.go.mdx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + export const sections = [ { id: "define-permissions", title: "Define permissions" }, { id: "install-dependencies", title: "Install dependencies" }, @@ -109,10 +111,10 @@ export const sections = [ Create a function `HasScope` to check and ensure the access token has the correct scope before returning a successful response. - +
    - +
    @@ -143,7 +145,7 @@ export const sections = [ Provide the Access Token as an `Authorization` header in your requests. - + ```bash cURL lines curl --request get \ --url 'http:///%7ByourDomain%7D/api_path' \ @@ -303,7 +305,7 @@ export const sections = [ }) dataTask.resume() ``` - + ##### Checkpoint @@ -316,10 +318,10 @@ export const sections = [ token with the `read:messages`scope. - +
    - +
    ## Next Steps diff --git a/main/docs/quickstart/backend/golang/interactive.mdx b/main/docs/quickstart/backend/golang/interactive.mdx index 34a111c3c..aff24f31a 100644 --- a/main/docs/quickstart/backend/golang/interactive.mdx +++ b/main/docs/quickstart/backend/golang/interactive.mdx @@ -18,6 +18,8 @@ import Main from "/snippets/quickstart/backend/golang/main.go.mdx"; import {QuickstartButtons} from "/snippets/QuickstartButtons.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + export const sections = [ @@ -144,7 +146,7 @@ export const sections = [ Provide the Access Token as an `Authorization` header in your requests. - + ```bash cURL lines curl --request get \ --url 'http:///%7ByourDomain%7D/api_path' \ @@ -304,7 +306,7 @@ export const sections = [ }) dataTask.resume() ``` - + ##### Checkpoint @@ -343,17 +345,17 @@ export const sections = [ - +
    - + - +
    - + diff --git a/main/docs/quickstart/backend/java-spring-security5/02-using.mdx b/main/docs/quickstart/backend/java-spring-security5/02-using.mdx index 31d775449..fac01aa8b 100644 --- a/main/docs/quickstart/backend/java-spring-security5/02-using.mdx +++ b/main/docs/quickstart/backend/java-spring-security5/02-using.mdx @@ -4,6 +4,7 @@ permalink: "02-using" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; ##### By Jim Anderson @@ -13,8 +14,7 @@ This tutorial will show you how to use your API. We recommend that you log in to You can call the API from your application by passing an Access Token in the `Authorization` header of your HTTP request as a Bearer token. - - + ```bash Bash lines curl --request GET \ --url http://localhost:3010/api/private \ @@ -184,7 +184,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + ## Obtaining an Access Token @@ -197,19 +197,25 @@ If you are calling the API from a command-line tool or another service, where th Read [Application Settings](https://auth0.com/docs/get-started/dashboard/application-settings) for more information on getting the Client ID and Client Secret for your machine-to-machine app. -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=client_credentials \ --data 'client_id={yourClientId}' \ --data client_secret=YOUR_CLIENT_SECRET \ - --data audience=YOUR_API_IDENTIFIER`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data audience=YOUR_API_IDENTIFIER +``` +```cs C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=client_credentials&client_id=%24%7Baccount.clientId%7D&client_secret=YOUR_CLIENT_SECRET&audience=YOUR_API_IDENTIFIER", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -236,12 +242,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=client_credentials&client_id=%24%7Baccount.clientId%7D&client_secret=YOUR_CLIENT_SECRET&audience=YOUR_API_IDENTIFIER") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -259,8 +269,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -286,8 +298,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -312,8 +326,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -326,8 +342,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -342,8 +360,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=client_credentials&client_id=%24%7Baccount.clientId%7D&client_secret=YOUR_CLIENT_SECRET&audience=YOUR_API_IDENTIFIER" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -369,20 +389,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + Auth0 customers are billed based on the number of Machine to Machine Access Tokens issued by Auth0. Once your application gets an Access Token it should keep using it until it expires, to minimize the number of tokens requested. @@ -394,7 +403,7 @@ For testing purposes, you can also get an Access Token from the **Test** tab in You can make a request to the `/api/private` endpoint without passing any Access Token: - + ```bash cURL lines curl --request GET \ @@ -495,7 +504,6 @@ if ($err) { } ``` - ```python Python lines import http.client @@ -523,7 +531,6 @@ response = http.request(request) puts response.read_body ``` - ```swift Swift lines import Foundation @@ -545,7 +552,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + The API will return a 401 HTTP (Unauthorized) status code: @@ -553,7 +560,7 @@ The API will return a 401 HTTP (Unauthorized) status code: Once again, make the same request but this time pass along the Access Token as a Bearer token in the **Authorization** header of the request: - + ```bash curl --request GET \ --url http://localhost:3010/api/private \ @@ -723,7 +730,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + This time the API will return a successful response: @@ -733,7 +740,7 @@ This time the API will return a successful response: To test the endpoint that requires a scope, pass the Access Token containing the correct scope as a Bearer token in the Authorization header: - + ```bash cURL lines curl --request GET \ @@ -904,7 +911,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + If the required scope is present, the API call is successful: diff --git a/main/docs/quickstart/backend/java-spring-security5/_index.mdx b/main/docs/quickstart/backend/java-spring-security5/_index.mdx index a70575e11..4fa6de0a2 100644 --- a/main/docs/quickstart/backend/java-spring-security5/_index.mdx +++ b/main/docs/quickstart/backend/java-spring-security5/_index.mdx @@ -9,6 +9,8 @@ import Application from "/snippets/quickstart/backend/java-spring-security5/appl import Securityconfig from "/snippets/quickstart/backend/java-spring-security5/SecurityConfig.java.mdx"; import Apicontroller from "/snippets/quickstart/backend/java-spring-security5/APIController.java.mdx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + export const sections = [ { id: "define-permissions", title: "Define permissions" }, { id: "configure-the-sample-project", title: "Configure the sample project" }, @@ -60,11 +62,11 @@ export const sections = [ correct Auth0 **domain** and **API Identifier** for your API. If you download the code from this page it will be automatically configured. If you clone the example from GitHub, you will need to fill it in yourself. - + - +
    @@ -120,11 +122,11 @@ export const sections = [ ``` - + - +
    @@ -152,11 +154,11 @@ export const sections = [ the `read:messages` scope. - + - +
    @@ -164,11 +166,11 @@ export const sections = [ into the key value for your JSON. Create a new record named `Message` as an example domain object to return during the API calls. - + - +
    @@ -176,11 +178,11 @@ export const sections = [ `APIController` has three routes as defined in the [Protect API Endpoints](https://auth0.com/docs/quickstart/backend/java-spring-security5/interactive#configure-the-resource-server) section. For this example, allow all origins through `@CrossOrigin` annotation. Real applications should configure `CORS` for their use case. - + - +
    diff --git a/main/docs/quickstart/backend/java-spring-security5/interactive.mdx b/main/docs/quickstart/backend/java-spring-security5/interactive.mdx index 52d6d4bea..33b76a988 100644 --- a/main/docs/quickstart/backend/java-spring-security5/interactive.mdx +++ b/main/docs/quickstart/backend/java-spring-security5/interactive.mdx @@ -22,6 +22,8 @@ import Apicontroller from "/snippets/quickstart/backend/java-spring-security5/AP import {QuickstartButtons} from "/snippets/QuickstartButtons.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + export const sections = [ @@ -214,43 +216,43 @@ export const sections = [ - + - + - + - + - + - + - + - + - + - + diff --git a/main/docs/quickstart/backend/nodejs/02-using.mdx b/main/docs/quickstart/backend/nodejs/02-using.mdx index 58f8afaf0..65dcd0898 100644 --- a/main/docs/quickstart/backend/nodejs/02-using.mdx +++ b/main/docs/quickstart/backend/nodejs/02-using.mdx @@ -4,6 +4,7 @@ permalink: "02-using" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; ##### By David Patrick @@ -13,8 +14,7 @@ This tutorial will show you how to use your API. We recommend that you log in to You can call the API from your application by passing an Access Token in the `Authorization` header of your HTTP request as a Bearer token. - - + ```bash lines curl --request GET \ --url http://localhost:3010/api/private \ @@ -184,7 +184,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + ## Obtaining an Access Token @@ -197,19 +197,25 @@ If you are calling the API from a command-line tool or another service, where th Read [Application Settings](https://auth0.com/docs/get-started/dashboard/application-settings) for more information on getting the Client ID and Client Secret for your machine-to-machine app. -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=client_credentials \ --data 'client_id={yourClientId}' \ --data client_secret=YOUR_CLIENT_SECRET \ - --data audience=YOUR_API_IDENTIFIER`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data audience=YOUR_API_IDENTIFIER +``` +```cs C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=client_credentials&client_id=%24%7Baccount.clientId%7D&client_secret=YOUR_CLIENT_SECRET&audience=YOUR_API_IDENTIFIER", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -236,12 +242,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=client_credentials&client_id=%24%7Baccount.clientId%7D&client_secret=YOUR_CLIENT_SECRET&audience=YOUR_API_IDENTIFIER") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -259,8 +269,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -286,8 +298,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -312,8 +326,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -326,8 +342,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -342,8 +360,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=client_credentials&client_id=%24%7Baccount.clientId%7D&client_secret=YOUR_CLIENT_SECRET&audience=YOUR_API_IDENTIFIER" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -369,20 +389,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + Auth0 customers are billed based on the number of Machine to Machine Access Tokens issued by Auth0. Once your application gets an Access Token it should keep using it until it expires, to minimize the number of tokens requested. @@ -394,7 +403,7 @@ For testing purposes, you can also get an Access Token from the **Test** tab in You can make a request to the `/api/private` endpoint without passing any Access Token: - + ```bash cURL lines curl --request GET \ @@ -495,7 +504,6 @@ if ($err) { } ``` - ```python Python lines import http.client @@ -523,7 +531,6 @@ response = http.request(request) puts response.read_body ``` - ```swift Swift lines import Foundation @@ -545,7 +552,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + The API will return a 401 HTTP (Unauthorized) status code: @@ -553,7 +560,7 @@ The API will return a 401 HTTP (Unauthorized) status code: Once again, make the same request but this time pass along the Access Token as a Bearer token in the **Authorization** header of the request: - + ```bash lines curl --request GET \ --url http://localhost:3010/api/private \ @@ -723,7 +730,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + This time the API will return a successful response: @@ -733,7 +740,7 @@ This time the API will return a successful response: To test the endpoint that requires a scope, pass the Access Token containing the correct scope as a Bearer token in the Authorization header: - + ```bash cURL lines curl --request GET \ @@ -904,7 +911,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + If the required scope is present, the API call is successful: @@ -914,8 +921,4 @@ If the required scope is not present, the API returns a 403 HTTP Status (Forbidd ![Response for forbidden scoped API request](https://cdn2.auth0.com/docs/1.14550.0/media/articles/server-apis/using/private-scoped-forbidden.png) - - - - [Edit on GitHub](https://github.com/auth0/docs/edit/master/articles/quickstart/backend/nodejs/02-using.md) \ No newline at end of file diff --git a/main/docs/quickstart/backend/nodejs/_index.mdx b/main/docs/quickstart/backend/nodejs/_index.mdx index 1a81beac3..484f0cfbc 100644 --- a/main/docs/quickstart/backend/nodejs/_index.mdx +++ b/main/docs/quickstart/backend/nodejs/_index.mdx @@ -8,6 +8,8 @@ import { LoggedInForm } from "/snippets/Login.jsx"; import Server from "/snippets/quickstart/backend/nodejs/server.js.mdx"; import Server2 from "/snippets/quickstart/backend/nodejs/server.js2.mdx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + export const sections = [ { id: "define-permissions", title: "Define permissions" }, { id: "install-dependencies", title: "Install dependencies" }, @@ -96,7 +98,7 @@ export const sections = [ Provide the Access Token as an `Authorization` header in your requests. - + ```bash cURL lines curl --request get \ --url 'http:///%7ByourDomain%7D/api_path' \ @@ -256,7 +258,7 @@ export const sections = [ }) dataTask.resume() ``` - + ##### Checkpoint diff --git a/main/docs/quickstart/backend/nodejs/interactive.mdx b/main/docs/quickstart/backend/nodejs/interactive.mdx index cb07652af..a00438358 100644 --- a/main/docs/quickstart/backend/nodejs/interactive.mdx +++ b/main/docs/quickstart/backend/nodejs/interactive.mdx @@ -21,6 +21,8 @@ import Server2 from "/snippets/quickstart/backend/nodejs/server.js2.mdx"; import {QuickstartButtons} from "/snippets/QuickstartButtons.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + export const sections = [ @@ -105,7 +107,7 @@ export const sections = [ Provide the Access Token as an `Authorization` header in your requests. - + ```bash cURL lines curl --request get \ --url 'http:///%7ByourDomain%7D/api_path' \ @@ -265,7 +267,7 @@ export const sections = [ }) dataTask.resume() ``` - + ##### Checkpoint diff --git a/main/docs/quickstart/backend/php/_index.mdx b/main/docs/quickstart/backend/php/_index.mdx index 1dcda42ec..f612171b1 100644 --- a/main/docs/quickstart/backend/php/_index.mdx +++ b/main/docs/quickstart/backend/php/_index.mdx @@ -11,6 +11,8 @@ import Router from "/snippets/quickstart/backend/php/router.php.mdx"; import Router2 from "/snippets/quickstart/backend/php/router.php2.mdx"; import Router3 from "/snippets/quickstart/backend/php/router.php3.mdx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + export const sections = [ { id: "configure-auth0", title: "Configure Auth0" }, { id: "install-the-auth0-php-sdk", title: "Install the Auth0 PHP SDK" }, @@ -99,10 +101,10 @@ export const sections = [ - Your application is not throwing any errors related to Auth0. - + - +
    @@ -115,10 +117,10 @@ export const sections = [ case, the PHP SDK processes tokens passed from GET requests in the `token` parameter or from the HTTP `Authorization` header. - + - +
    @@ -133,10 +135,10 @@ export const sections = [ Create a new file in your application called `router.php` to define the routes. Copy in the code from the interactive panel to the right under the **router.php** tab. - + - +
    @@ -153,10 +155,10 @@ export const sections = [ In the interactive panel to the right, you can see a check if the response is null or not to filter access to your `/api/private` route. - + - +
    @@ -164,10 +166,10 @@ export const sections = [ token. As shown in the interactive panel on the right, evaluate the contents of the 'scope' property from the `getBearerToken()` method's response to check the scopes granted by the access token. - + - +
    ## Next Steps diff --git a/main/docs/quickstart/backend/php/interactive.mdx b/main/docs/quickstart/backend/php/interactive.mdx index 0a88d9063..9a8b89d29 100644 --- a/main/docs/quickstart/backend/php/interactive.mdx +++ b/main/docs/quickstart/backend/php/interactive.mdx @@ -22,6 +22,8 @@ import Router3 from "/snippets/quickstart/backend/php/router.php3.mdx"; import {QuickstartButtons} from "/snippets/QuickstartButtons.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + export const sections = [ @@ -173,38 +175,38 @@ export const sections = [ - + - + - + - + - + - + - + - + - + - + diff --git a/main/docs/quickstart/backend/python/02-using.mdx b/main/docs/quickstart/backend/python/02-using.mdx index 34fa713b8..2a31066c1 100644 --- a/main/docs/quickstart/backend/python/02-using.mdx +++ b/main/docs/quickstart/backend/python/02-using.mdx @@ -4,6 +4,7 @@ permalink: "02-using" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; ##### By Luciano Balmaceda @@ -13,8 +14,7 @@ This tutorial will show you how to use your API. We recommend that you log in to You can call the API from your application by passing an Access Token in the `Authorization` header of your HTTP request as a Bearer token. - - + ```bash lines curl --request GET \ --url http://localhost:3010/api/private \ @@ -184,7 +184,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + ## Obtaining an Access Token @@ -197,19 +197,25 @@ If you are calling the API from a command-line tool or another service, where th Read [Application Settings](https://auth0.com/docs/get-started/dashboard/application-settings) for more information on getting the Client ID and Client Secret for your machine-to-machine app. -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=client_credentials \ --data 'client_id={yourClientId}' \ --data client_secret=YOUR_CLIENT_SECRET \ - --data audience=YOUR_API_IDENTIFIER`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data audience=YOUR_API_IDENTIFIER +``` +```cs C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=client_credentials&client_id=%24%7Baccount.clientId%7D&client_secret=YOUR_CLIENT_SECRET&audience=YOUR_API_IDENTIFIER", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -236,12 +242,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=client_credentials&client_id=%24%7Baccount.clientId%7D&client_secret=YOUR_CLIENT_SECRET&audience=YOUR_API_IDENTIFIER") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -259,8 +269,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -286,8 +298,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -312,8 +326,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -326,8 +342,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -342,8 +360,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=client_credentials&client_id=%24%7Baccount.clientId%7D&client_secret=YOUR_CLIENT_SECRET&audience=YOUR_API_IDENTIFIER" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -369,20 +389,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + Auth0 customers are billed based on the number of Machine to Machine Access Tokens issued by Auth0. Once your application gets an Access Token it should keep using it until it expires, to minimize the number of tokens requested. @@ -394,7 +403,7 @@ For testing purposes, you can also get an Access Token from the **Test** tab in You can make a request to the `/api/private` endpoint without passing any Access Token: - + ```bash cURL lines curl --request GET \ @@ -495,7 +504,6 @@ if ($err) { } ``` - ```python Python lines import http.client @@ -523,7 +531,6 @@ response = http.request(request) puts response.read_body ``` - ```swift Swift lines import Foundation @@ -545,7 +552,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + The API will return a 401 HTTP (Unauthorized) status code: @@ -553,7 +560,7 @@ The API will return a 401 HTTP (Unauthorized) status code: Once again, make the same request but this time pass along the Access Token as a Bearer token in the **Authorization** header of the request: - + ```bash lines curl --request GET \ --url http://localhost:3010/api/private \ @@ -723,7 +730,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + This time the API will return a successful response: @@ -733,7 +740,7 @@ This time the API will return a successful response: To test the endpoint that requires a scope, pass the Access Token containing the correct scope as a Bearer token in the Authorization header: - + ```bash cURL lines curl --request GET \ @@ -904,7 +911,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + If the required scope is present, the API call is successful: diff --git a/main/docs/quickstart/backend/python/_index.mdx b/main/docs/quickstart/backend/python/_index.mdx index c113711f3..4cf0b5ab2 100644 --- a/main/docs/quickstart/backend/python/_index.mdx +++ b/main/docs/quickstart/backend/python/_index.mdx @@ -8,6 +8,8 @@ import { LoggedInForm } from "/snippets/Login.jsx"; import Validator from "/snippets/quickstart/backend/python/validator.py.mdx"; import Server from "/snippets/quickstart/backend/python/server.py.mdx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + export const sections = [ { id: "define-permissions", title: "Define permissions" }, { id: "install-dependencies", title: "Install dependencies" }, @@ -81,10 +83,10 @@ export const sections = [ We'll then override the class's `claims_options` to make sure the token's expiry, audience and issue claims are validated according to our requirements. - + - +
    @@ -116,7 +118,7 @@ export const sections = [ Provide the Access Token as an `Authorization` header in your requests. - + ```bash cURL lines curl --request get \ --url 'http:///%7ByourDomain%7D/api_path' \ @@ -276,13 +278,13 @@ export const sections = [ }) dataTask.resume() ``` - + - + - +
    ## Next Steps diff --git a/main/docs/quickstart/backend/python/interactive.mdx b/main/docs/quickstart/backend/python/interactive.mdx index 7e255b75f..afb4923e5 100644 --- a/main/docs/quickstart/backend/python/interactive.mdx +++ b/main/docs/quickstart/backend/python/interactive.mdx @@ -21,6 +21,8 @@ import Server from "/snippets/quickstart/backend/python/server.py.mdx"; import {QuickstartButtons} from "/snippets/QuickstartButtons.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + export const sections = [ @@ -122,7 +124,7 @@ export const sections = [ Provide the Access Token as an `Authorization` header in your requests. - + ```bash cURL lines curl --request get \ --url 'http:///%7ByourDomain%7D/api_path' \ @@ -282,7 +284,7 @@ export const sections = [ }) dataTask.resume() ``` - + @@ -307,17 +309,17 @@ export const sections = [ - + - + - + - + diff --git a/main/docs/quickstart/backend/rails/02-using.mdx b/main/docs/quickstart/backend/rails/02-using.mdx index 7e91adc4a..f2670fcf4 100644 --- a/main/docs/quickstart/backend/rails/02-using.mdx +++ b/main/docs/quickstart/backend/rails/02-using.mdx @@ -4,6 +4,7 @@ permalink: "02-using" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; ##### By Josh Cunningham @@ -13,8 +14,7 @@ This tutorial will show you how to use your API. We recommend that you log in to You can call the API from your application by passing an Access Token in the `Authorization` header of your HTTP request as a Bearer token. - - + ```bash lines curl --request GET \ --url http://localhost:3010/api/private \ @@ -184,7 +184,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + ## Obtaining an Access Token @@ -197,19 +197,25 @@ If you are calling the API from a command-line tool or another service, where th Read [Application Settings](https://auth0.com/docs/get-started/dashboard/application-settings) for more information on getting the Client ID and Client Secret for your machine-to-machine app. -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=client_credentials \ --data 'client_id={yourClientId}' \ --data client_secret=YOUR_CLIENT_SECRET \ - --data audience=YOUR_API_IDENTIFIER`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data audience=YOUR_API_IDENTIFIER +``` +```cs C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=client_credentials&client_id=%24%7Baccount.clientId%7D&client_secret=YOUR_CLIENT_SECRET&audience=YOUR_API_IDENTIFIER", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -236,12 +242,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=client_credentials&client_id=%24%7Baccount.clientId%7D&client_secret=YOUR_CLIENT_SECRET&audience=YOUR_API_IDENTIFIER") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -259,8 +269,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -286,8 +298,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -312,8 +326,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -326,8 +342,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -342,8 +360,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=client_credentials&client_id=%24%7Baccount.clientId%7D&client_secret=YOUR_CLIENT_SECRET&audience=YOUR_API_IDENTIFIER" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -369,20 +389,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + Auth0 customers are billed based on the number of Machine to Machine Access Tokens issued by Auth0. Once your application gets an Access Token it should keep using it until it expires, to minimize the number of tokens requested. @@ -394,7 +403,7 @@ For testing purposes, you can also get an Access Token from the **Test** tab in You can make a request to the `/api/private` endpoint without passing any Access Token: - + ```bash cURL lines curl --request GET \ @@ -495,7 +504,6 @@ if ($err) { } ``` - ```python Python lines import http.client @@ -523,7 +531,6 @@ response = http.request(request) puts response.read_body ``` - ```swift Swift lines import Foundation @@ -545,7 +552,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + The API will return a 401 HTTP (Unauthorized) status code: @@ -553,7 +560,7 @@ The API will return a 401 HTTP (Unauthorized) status code: Once again, make the same request but this time pass along the Access Token as a Bearer token in the **Authorization** header of the request: - + ```bash lines curl --request GET \ --url http://localhost:3010/api/private \ @@ -723,7 +730,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + This time the API will return a successful response: @@ -733,7 +740,7 @@ This time the API will return a successful response: To test the endpoint that requires a scope, pass the Access Token containing the correct scope as a Bearer token in the Authorization header: - + ```bash cURL lines curl --request GET \ @@ -904,7 +911,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + If the required scope is present, the API call is successful: diff --git a/main/docs/quickstart/backend/rails/_index.mdx b/main/docs/quickstart/backend/rails/_index.mdx index 5ceb1f235..03eeb8d8f 100644 --- a/main/docs/quickstart/backend/rails/_index.mdx +++ b/main/docs/quickstart/backend/rails/_index.mdx @@ -11,6 +11,8 @@ import Secured from "/snippets/quickstart/backend/rails/secured.rb.mdx"; import PublicController from "/snippets/quickstart/backend/rails/public_controller.rb.mdx"; import PrivateController from "/snippets/quickstart/backend/rails/private_controller.rb.mdx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + export const sections = [ { id: "define-permissions", title: "Define permissions" }, { id: "install-dependencies", title: "Install dependencies" }, @@ -79,13 +81,13 @@ export const sections = [ look for a particular `scope` in an access token by providing an array of required scopes and check if they are present in the payload of the token. - + - +
    @@ -103,26 +105,26 @@ export const sections = [ For the `/private-scoped` route, the scopes defined will be intersected with the scopes coming in the payload, to determine if it contains one or more items from the other array. - + - +
    By adding the `Secure` concern to your application controller, you'll only need to use a `before_action` filter in the controller that requires authorization. - + - +
    @@ -130,13 +132,13 @@ export const sections = [ The `/public` endpoint does not require any authorization so no `before_action` is needed. - + - +
    @@ -165,7 +167,7 @@ export const sections = [ Provide the Access Token as an `Authorization` header in your requests. - + ```bash cURL lines curl --request get \ --url 'http:///%7ByourDomain%7D/api_path' \ @@ -325,7 +327,7 @@ export const sections = [ }) dataTask.resume() ``` - + ##### Checkpoint @@ -338,13 +340,13 @@ export const sections = [ Token with the `read:messages`scope. - + - +
    ## Next Steps diff --git a/main/docs/quickstart/backend/rails/interactive.mdx b/main/docs/quickstart/backend/rails/interactive.mdx index 0aa9276b8..0f2c7984b 100644 --- a/main/docs/quickstart/backend/rails/interactive.mdx +++ b/main/docs/quickstart/backend/rails/interactive.mdx @@ -24,6 +24,8 @@ import PrivateController from "/snippets/quickstart/backend/rails/private_contro import {QuickstartButtons} from "/snippets/QuickstartButtons.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + export const sections = [ @@ -144,7 +146,7 @@ export const sections = [ Provide the Access Token as an `Authorization` header in your requests. - + ```bash cURL lines curl --request get \ --url 'http:///%7ByourDomain%7D/api_path' \ @@ -304,7 +306,7 @@ export const sections = [ }) dataTask.resume() ``` - + ##### Checkpoint @@ -339,53 +341,53 @@ export const sections = [ - + - + - + - + - + - + - + - + - + - + diff --git a/main/docs/quickstart/backend/webapi-owin/02-using.mdx b/main/docs/quickstart/backend/webapi-owin/02-using.mdx index 533518b6d..1d0c8ce00 100644 --- a/main/docs/quickstart/backend/webapi-owin/02-using.mdx +++ b/main/docs/quickstart/backend/webapi-owin/02-using.mdx @@ -4,6 +4,7 @@ permalink: "02-using" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; ##### By Damien Guard @@ -13,8 +14,7 @@ This tutorial will show you how to use your API. We recommend that you log in to You can call the API from your application by passing an Access Token in the `Authorization` header of your HTTP request as a Bearer token. - - + ```bash lines curl --request GET \ --url http://localhost:3010/api/private \ @@ -184,7 +184,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + ## Obtaining an Access Token @@ -197,19 +197,25 @@ If you are calling the API from a command-line tool or another service, where th Read [Application Settings](https://auth0.com/docs/get-started/dashboard/application-settings) for more information on getting the Client ID and Client Secret for your machine-to-machine app. -export const codeExample1 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=client_credentials \ --data 'client_id={yourClientId}' \ --data client_secret=YOUR_CLIENT_SECRET \ - --data audience=YOUR_API_IDENTIFIER`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data audience=YOUR_API_IDENTIFIER +``` +```cs C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=client_credentials&client_id=%24%7Baccount.clientId%7D&client_secret=YOUR_CLIENT_SECRET&audience=YOUR_API_IDENTIFIER", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -236,12 +242,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=client_credentials&client_id=%24%7Baccount.clientId%7D&client_secret=YOUR_CLIENT_SECRET&audience=YOUR_API_IDENTIFIER") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -259,8 +269,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample6 = `#import +}); +``` +```obj-c Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -286,8 +298,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -312,8 +326,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -326,8 +342,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -342,8 +360,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=client_credentials&client_id=%24%7Baccount.clientId%7D&client_secret=YOUR_CLIENT_SECRET&audience=YOUR_API_IDENTIFIER" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -369,20 +389,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - +dataTask.resume() +``` + Auth0 customers are billed based on the number of Machine to Machine Access Tokens issued by Auth0. Once your application gets an Access Token it should keep using it until it expires, to minimize the number of tokens requested. @@ -394,7 +403,7 @@ For testing purposes, you can also get an Access Token from the **Test** tab in You can make a request to the `/api/private` endpoint without passing any Access Token: - + ```bash cURL lines curl --request GET \ @@ -495,7 +504,6 @@ if ($err) { } ``` - ```python Python lines import http.client @@ -523,7 +531,6 @@ response = http.request(request) puts response.read_body ``` - ```swift Swift lines import Foundation @@ -545,7 +552,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + The API will return a 401 HTTP (Unauthorized) status code: @@ -553,7 +560,7 @@ The API will return a 401 HTTP (Unauthorized) status code: Once again, make the same request but this time pass along the Access Token as a Bearer token in the **Authorization** header of the request: - + ```bash lines curl --request GET \ --url http://localhost:3010/api/private \ @@ -723,7 +730,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + This time the API will return a successful response: @@ -733,7 +740,7 @@ This time the API will return a successful response: To test the endpoint that requires a scope, pass the Access Token containing the correct scope as a Bearer token in the Authorization header: - + ```bash cURL lines curl --request GET \ @@ -904,7 +911,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - + If the required scope is present, the API call is successful: diff --git a/main/docs/quickstart/backend/webapi-owin/_index.mdx b/main/docs/quickstart/backend/webapi-owin/_index.mdx index 852791cde..4e8a0d15c 100644 --- a/main/docs/quickstart/backend/webapi-owin/_index.mdx +++ b/main/docs/quickstart/backend/webapi-owin/_index.mdx @@ -9,6 +9,8 @@ import Openidconnectsigningkeyresolver from "/snippets/quickstart/backend/webapi import Scopeauthorizeattribute from "/snippets/quickstart/backend/webapi-owin/ScopeAuthorizeAttribute.cs.mdx"; import Apicontroller from "/snippets/quickstart/backend/webapi-owin/ApiController.cs.mdx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + export const sections = [ { id: "define-permissions", title: "Define permissions" }, { id: "install-dependencies", title: "Install dependencies" }, @@ -83,11 +85,11 @@ export const sections = [ - + - +
    @@ -103,11 +105,11 @@ export const sections = [ This custom resolver is deprecated and [no longer available](https://github.com/auth0/auth0-aspnet-owin/blob/master/SECURITY-NOTICE.md). You must provide this custom resolver yourself. - + - +
    @@ -120,11 +122,11 @@ export const sections = [ issued by your Auth0 tenant is present, and if so, it will ensure that the `scope` claim contains the requested scope. - + - +
    @@ -154,11 +156,11 @@ export const sections = [ token with the `read:messages`scope. - + - +
    ## Next Steps diff --git a/main/docs/quickstart/backend/webapi-owin/interactive.mdx b/main/docs/quickstart/backend/webapi-owin/interactive.mdx index 6268aef38..25904dfcd 100644 --- a/main/docs/quickstart/backend/webapi-owin/interactive.mdx +++ b/main/docs/quickstart/backend/webapi-owin/interactive.mdx @@ -22,6 +22,8 @@ import Apicontroller from "/snippets/quickstart/backend/webapi-owin/ApiControlle import {QuickstartButtons} from "/snippets/QuickstartButtons.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + export const sections = [ @@ -168,35 +170,35 @@ export const sections = [ - + - + - + - + - + - + - + - + diff --git a/main/docs/quickstart/native/android-facebook-login/_index.mdx b/main/docs/quickstart/native/android-facebook-login/_index.mdx index 885fd11d3..cb376fb58 100644 --- a/main/docs/quickstart/native/android-facebook-login/_index.mdx +++ b/main/docs/quickstart/native/android-facebook-login/_index.mdx @@ -11,6 +11,8 @@ import Fetchuserprofile from "/snippets/quickstart/native/android-facebook-login import Exchangetokens from "/snippets/quickstart/native/android-facebook-login/exchangeTokens.mdx"; import Performlogin from "/snippets/quickstart/native/android-facebook-login/performLogin.mdx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + export const sections = [ { id: "system-requirements", title: "System requirements" }, { id: "before-you-start", title: "Before You Start" }, @@ -75,27 +77,27 @@ export const sections = [ In the sample, the method was named `performLogin` and the interface `SimpleCallback`. Go ahead and add both. - + - +
    Now, call the method from the Facebook login callback's `onSuccess` method. - + - +
    @@ -125,14 +127,14 @@ export const sections = [ The sample uses the Facebook SDK's `GraphRequest` class to perform this request. - + - +
    @@ -145,14 +147,14 @@ export const sections = [ permission is optional, the user must first consent to give access to it. For the purpose of signing up a user at Auth0, their full name and email will suffice. - + - +
    @@ -273,14 +275,14 @@ export const sections = [ that if the Facebook app is installed on the device, the authentication will be handled via the application and not a browser app. - + - +
    diff --git a/main/docs/quickstart/native/android-facebook-login/interactive.mdx b/main/docs/quickstart/native/android-facebook-login/interactive.mdx index 8ea294593..bf181c307 100644 --- a/main/docs/quickstart/native/android-facebook-login/interactive.mdx +++ b/main/docs/quickstart/native/android-facebook-login/interactive.mdx @@ -23,6 +23,8 @@ import Performlogin from "/snippets/quickstart/native/android-facebook-login/per import {QuickstartButtons} from "/snippets/QuickstartButtons.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + export const sections = [ @@ -255,25 +257,25 @@ export const sections = [ - + - + - + - + @@ -281,25 +283,25 @@ export const sections = [ - + - + - + - + @@ -311,14 +313,14 @@ export const sections = [ - + - + diff --git a/main/docs/quickstart/native/device/_index.mdx b/main/docs/quickstart/native/device/_index.mdx index e72f7d39d..10e34a152 100644 --- a/main/docs/quickstart/native/device/_index.mdx +++ b/main/docs/quickstart/native/device/_index.mdx @@ -5,6 +5,8 @@ title: Device Authorization Flow import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; import { LoggedInForm } from "/snippets/Login.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + export const sections = [ { id: "prerequisites", title: "Prerequisites" }, { id: "request-device-code", title: "Request device code" }, @@ -48,7 +50,7 @@ export const sections = [ To get the device code, your application must call the Authentication API Device Authorization Flow [Authorize endpoint](https://auth0.com/docs/api/authentication#-post-oauth-device-code-): - + ```bash cURL lines curl --request post \ --url 'https://dev-gja8kxz4ndtex3rq.us.auth0.com/oauth/device/code' \ @@ -197,7 +199,7 @@ export const sections = [ }) dataTask.resume() ``` - + diff --git a/main/docs/quickstart/native/device/index.mdx b/main/docs/quickstart/native/device/index.mdx index b2a467e07..51f5eadbd 100644 --- a/main/docs/quickstart/native/device/index.mdx +++ b/main/docs/quickstart/native/device/index.mdx @@ -4,13 +4,12 @@ permalink: "01-login" --- import {AuthCodeBlock} from "/snippets/AuthCodeBlock.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; ##### By Rachel Khoriander This tutorial demonstrates how to call your API from an input-constrained device using the Device Authorization flow.We recommend that you log in to follow this quickstart with examples configured for your account. - - This tutorial demonstrates how to call your API from an input-constrained device using the Device Authorization flow. {/* [Follow Quickstart](#prerequisites) @@ -64,18 +63,12 @@ Once the user has started their device app and wants to authorize the device, yo To get the device code, your app must request a code from the [device code URL](https://auth0.com/docs/api/authentication#get-device-code), including the Client ID. ### Example POST to device code URL -export const codeExample1 = `curl --request POST \ - --url 'https://{yourDomain}/oauth/device/code' \ - --header 'content-type: application/x-www-form-urlencoded' \ - --data 'client_id={yourClientId}' \ - --data scope=SCOPE \ - --data audience=AUDIENCE`; -export const codeExample2 = `var client = new RestClient("https://{yourDomain}/oauth/device/code"); -var request = new RestRequest(Method.POST); -request.AddHeader("content-type", "application/x-www-form-urlencoded"); -request.AddParameter("application/x-www-form-urlencoded", "client_id=%24%7Baccount.clientId%7D&scope=SCOPE&audience=AUDIENCE", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample3 = `package main + + + + +```go Go +package main import ( "fmt" @@ -102,26 +95,17 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample4 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/device/code") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/device/code") .header("content-type", "application/x-www-form-urlencoded") .body("client_id=%24%7Baccount.clientId%7D&scope=SCOPE&audience=AUDIENCE") - .asString();`; -export const codeExample5 = `var axios = require("axios").default; - -var options = { - method: 'POST', - url: 'https://{yourDomain}/oauth/device/code', - headers: {'content-type': 'application/x-www-form-urlencoded'}, - data: {client_id: '{yourClientId}', scope: 'SCOPE', audience: 'AUDIENCE'} -}; - -axios.request(options).then(function (response) { - console.log(response.data); -}).catch(function (error) { - console.error(error); -});`; -export const codeExample6 = `#import + .asString(); +``` + +```objc Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -146,8 +130,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample7 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/device/code", @@ -172,8 +158,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample8 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -186,8 +174,10 @@ conn.request("POST", "/{yourDomain}/oauth/device/code", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample9 = `require 'uri' +print(data.decode("utf-8")) +``` +```rb Ruby +require 'uri' require 'net/http' require 'openssl' @@ -202,8 +192,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "client_id=%24%7Baccount.clientId%7D&scope=SCOPE&audience=AUDIENCE" response = http.request(request) -puts response.read_body`; -export const codeExample10 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -228,24 +220,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - - - - - +dataTask.resume() +``` + #### Device Code Parameters @@ -295,11 +272,6 @@ If all goes well, you'll receive an HTTP 200 response with a payload containing } ``` - - - - - * `device_code` is the unique code for the device. When the user goes to the `verification_uri` in their browser-based device, this code will be bound to their session. * `user_code` contains the code that should be input at the `verification_uri` to authorize the device. * `verification_uri` contains the URL the user should visit to authorize the device. @@ -346,18 +318,17 @@ To avoid errors due to network latency, you should start counting each interval ### Example request token POST to token URL -export const codeExample11 = `curl --request POST \ - --url 'https://{yourDomain}/oauth/token' \ - --header 'content-type: application/x-www-form-urlencoded' \ - --data grant_type=urn:ietf:params:oauth:grant-type:device_code \ - --data device_code=YOUR_DEVICE_CODE \ - --data 'client_id={yourClientId}'`; -export const codeExample12 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + + +```cs C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Adevice_code&device_code=YOUR_DEVICE_CODE&client_id=%24%7Baccount.clientId%7D", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample13 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -384,12 +355,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample14 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Adevice_code&device_code=YOUR_DEVICE_CODE&client_id=%24%7Baccount.clientId%7D") - .asString();`; -export const codeExample15 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.js +var axios = require("axios").default; var options = { method: 'POST', @@ -406,8 +381,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample16 = `#import +}); +``` +```objc Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -432,8 +409,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample17 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -458,8 +437,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample18 = `import http.client +} +``` +```py Python +import http.client conn = http.client.HTTPSConnection("") @@ -472,8 +453,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample19 = `require 'uri' +print(data.decode("utf-8")) +``` +```rb Ruby +require 'uri' require 'net/http' require 'openssl' @@ -488,8 +471,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Adevice_code&device_code=YOUR_DEVICE_CODE&client_id=%24%7Baccount.clientId%7D" response = http.request(request) -puts response.read_body`; -export const codeExample20 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -514,25 +499,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - - - - - - +dataTask.resume() +``` + #### Token Request Parameters @@ -575,11 +544,6 @@ You will see this error while waiting for the user to take action. Continue poll } ``` - - - - - #### Slow down You are polling too fast. Slow down and use the suggested interval retrieved in the previous step of this tutorial. To avoid receiving this error due to network latency, you should start counting each interval after receipt of the last polling request's response. @@ -593,11 +557,6 @@ You are polling too fast. Slow down and use the suggested interval retrieved in } ``` - - - - - #### Expired Token The user has not authorized the device quickly enough, so the `device_code` has expired. Your application should notify the user that the flow has expired and prompt them to reinitiate the flow. @@ -615,11 +574,6 @@ Then `expired_token` error will be returned exactly once; after that, the dreade } ``` - - - - - #### Access Denied Finally, if access is denied, you will receive: @@ -633,11 +587,6 @@ Finally, if access is denied, you will receive: } ``` - - - - - This can occur for a variety of reasons, including: * the user refused to authorize the device @@ -685,10 +634,6 @@ Once the user has successfully authorized the device, you'll receive an `HTTP 20 } ``` - - - - You should validate your tokens before saving them. To learn how, see [Validate Access Tokens](/docs/secure/tokens/access-tokens/validate-access-tokens) and [Validate ID Tokens](/docs/secure/tokens/id-tokens/validate-id-tokens). @@ -707,7 +652,7 @@ Refresh Tokens must be stored securely since they allow a user to remain authent To call your API, the application must pass the retrieved Access Token as a Bearer token in the Authorization header of your HTTP request. - + ```bash cURL lines curl --request GET \ @@ -716,11 +661,6 @@ curl --request GET \ --header 'content-type: application/json' ``` - - - - - ```javascript Node.JS lines var client = new RestClient("https://myapi.com/api"); var request = new RestRequest(Method.GET); @@ -729,11 +669,6 @@ request.AddHeader("authorization", "Bearer ACCESS_TOKEN"); IRestResponse response = client.Execute(request); ``` - - - - - ```go Go lines package main @@ -763,11 +698,6 @@ func main() { } ``` - - - - - ```java Java lines HttpResponse response = Unirest.get("https://myapi.com/api") .header("content-type", "application/json") @@ -775,11 +705,6 @@ HttpResponse response = Unirest.get("https://myapi.com/api") .asString(); ``` - - - - - ```javascript Node.JS lines var axios = require("axios").default; @@ -796,11 +721,6 @@ axios.request(options).then(function (response) { }); ``` - - - - - ```objc Obj-C lines #import @@ -826,11 +746,6 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request [dataTask resume]; ``` - - - - - ```php PHP lines $curl = curl_init(); @@ -860,11 +775,6 @@ if ($err) { } ``` - - - - - ```python Python lines import http.client @@ -883,11 +793,6 @@ data = res.read() print(data.decode("utf-8")) ``` - - - - - ```rb Ruby lines require 'uri' require 'net/http' @@ -907,11 +812,6 @@ response = http.request(request) puts response.read_body ``` - - - - - ```swift Swift lines import Foundation @@ -938,11 +838,7 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: dataTask.resume() ``` - - - - - + ## Refresh Tokens @@ -957,20 +853,25 @@ To refresh your token, make a `POST` request to the `/oauth/token` endpoint in t ### Example refresh token POST to token URL - -export const codeExample21 = `curl --request POST \ + +```bash cURL +curl --request POST \ --url 'https://{yourDomain}/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data grant_type=refresh_token \ --data 'client_id={yourClientId}' \ --data 'client_secret={yourClientSecret}' \ - --data refresh_token=YOUR_REFRESH_TOKEN`; -export const codeExample22 = `var client = new RestClient("https://{yourDomain}/oauth/token"); + --data refresh_token=YOUR_REFRESH_TOKEN +``` +```javascript C# +var client = new RestClient("https://{yourDomain}/oauth/token"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=refresh_token&client_id=%24%7Baccount.clientId%7D&client_secret=%24%7Baccount.clientSecret%7D&refresh_token=YOUR_REFRESH_TOKEN", ParameterType.RequestBody); -IRestResponse response = client.Execute(request);`; -export const codeExample23 = `package main +IRestResponse response = client.Execute(request); +``` +```go Go +package main import ( "fmt" @@ -997,12 +898,16 @@ func main() { fmt.Println(res) fmt.Println(string(body)) -}`; -export const codeExample24 = `HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") +} +``` +```java Java +HttpResponse response = Unirest.post("https://{yourDomain}/oauth/token") .header("content-type", "application/x-www-form-urlencoded") .body("grant_type=refresh_token&client_id=%24%7Baccount.clientId%7D&client_secret=%24%7Baccount.clientSecret%7D&refresh_token=YOUR_REFRESH_TOKEN") - .asString();`; -export const codeExample25 = `var axios = require("axios").default; + .asString(); +``` +```javascript Node.JS +var axios = require("axios").default; var options = { method: 'POST', @@ -1020,8 +925,10 @@ axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); -});`; -export const codeExample26 = `#import +}); +``` +```objc Obj-C +#import NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" }; @@ -1047,8 +954,10 @@ NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request NSLog(@"%@", httpResponse); } }]; -[dataTask resume];`; -export const codeExample27 = `$curl = curl_init(); +[dataTask resume]; +``` +```php PHP +$curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://{yourDomain}/oauth/token", @@ -1073,8 +982,10 @@ if ($err) { echo "cURL Error #:" . $err; } else { echo $response; -}`; -export const codeExample28 = `import http.client +} +``` +```python Python +import http.client conn = http.client.HTTPSConnection("") @@ -1087,8 +998,10 @@ conn.request("POST", "/{yourDomain}/oauth/token", payload, headers) res = conn.getresponse() data = res.read() -print(data.decode("utf-8"))`; -export const codeExample29 = `require 'uri' +print(data.decode("utf-8")) +``` +```ruby Ruby +require 'uri' require 'net/http' require 'openssl' @@ -1103,8 +1016,10 @@ request["content-type"] = 'application/x-www-form-urlencoded' request.body = "grant_type=refresh_token&client_id=%24%7Baccount.clientId%7D&client_secret=%24%7Baccount.clientSecret%7D&refresh_token=YOUR_REFRESH_TOKEN" response = http.request(request) -puts response.read_body`; -export const codeExample30 = `import Foundation +puts response.read_body +``` +```swift Swift +import Foundation let headers = ["content-type": "application/x-www-form-urlencoded"] @@ -1130,23 +1045,9 @@ let dataTask = session.dataTask(with: request as URLRequest, completionHandler: } }) -dataTask.resume()`; - - - - - - - - - - - - - - - - +dataTask.resume() +``` + #### Refresh Token Request Parameters @@ -1194,10 +1095,6 @@ If all goes well, you'll receive an `HTTP 200` response with a payload containin } ``` - - - - You should validate your tokens before saving them. To learn how, see [Validate Access Tokens](/docs/secure/tokens/access-tokens/validate-access-tokens) and [Validate ID Tokens](/docs/secure/tokens/id-tokens/validate-id-tokens). @@ -1218,11 +1115,6 @@ function (user, context, callback) { } ``` - - - - - ### Sample Implementations * [Device Authorization Playground](https://auth0.github.io/device-flow-playground/) @@ -1295,10 +1187,4 @@ We support the full [Draft 15](https://tools.ietf.org/html/draft-ietf-oauth-devi * [Tokens](/docs/secure/tokens) * [Tenant Logs for Devices](/docs/deploy-monitor/logs) - - - - - - [Edit on GitHub](https://github.com/auth0/docs/edit/master/articles/quickstart/native/device/01-login.md) \ No newline at end of file diff --git a/main/docs/quickstart/native/device/interactive.mdx b/main/docs/quickstart/native/device/interactive.mdx index 106d44707..003014539 100644 --- a/main/docs/quickstart/native/device/interactive.mdx +++ b/main/docs/quickstart/native/device/interactive.mdx @@ -15,6 +15,8 @@ title: Device Authorization Flow import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx"; import { LoggedInForm } from "/snippets/Login.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + export const sections = [ { id: "prerequisites", title: "Prerequisites" }, { id: "request-device-code", title: "Request device code" }, @@ -56,7 +58,7 @@ export const sections = [ To get the device code, your application must call the Authentication API Device Authorization Flow [Authorize endpoint](https://auth0.com/docs/api/authentication#-post-oauth-device-code-): - + ```bash cURL lines curl --request post \ --url 'https://dev-gja8kxz4ndtex3rq.us.auth0.com/oauth/device/code' \ @@ -205,7 +207,7 @@ export const sections = [ }) dataTask.resume() ``` - + diff --git a/main/docs/quickstart/native/flutter/_index.mdx b/main/docs/quickstart/native/flutter/_index.mdx index 21a1a3124..c1bd069da 100644 --- a/main/docs/quickstart/native/flutter/_index.mdx +++ b/main/docs/quickstart/native/flutter/_index.mdx @@ -10,6 +10,8 @@ import MainView from "/snippets/quickstart/native/flutter/main_view.dart.mdx"; import MainView2 from "/snippets/quickstart/native/flutter/main_view.dart2.mdx"; import ProfileView from "/snippets/quickstart/native/flutter/profile_view.dart.mdx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + export const sections = [ { id: "configure-auth0", title: "Configure Auth0" }, { id: "install-the-auth0-flutter-sdk", title: "Install the Auth0 Flutter SDK" }, @@ -219,11 +221,11 @@ export const sections = [ Verify that you can get access to the tokens on the result of calling `login`.
    - + - +
    @@ -246,11 +248,11 @@ export const sections = [ again. You should not be logged in to your app. - + - +
    @@ -265,11 +267,11 @@ export const sections = [ information, such as `email` or `name`. - + - +
    ## Next Steps diff --git a/main/docs/quickstart/native/flutter/interactive.mdx b/main/docs/quickstart/native/flutter/interactive.mdx index df5c994d5..8698422ee 100644 --- a/main/docs/quickstart/native/flutter/interactive.mdx +++ b/main/docs/quickstart/native/flutter/interactive.mdx @@ -21,6 +21,8 @@ import ProfileView from "/snippets/quickstart/native/flutter/profile_view.dart.m import {QuickstartButtons} from "/snippets/QuickstartButtons.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + export const sections = [ @@ -288,27 +290,27 @@ export const sections = [ - + - + - + - + - + - + diff --git a/main/docs/quickstart/native/ionic-angular/_index.mdx b/main/docs/quickstart/native/ionic-angular/_index.mdx index 392380d27..b3040c151 100644 --- a/main/docs/quickstart/native/ionic-angular/_index.mdx +++ b/main/docs/quickstart/native/ionic-angular/_index.mdx @@ -11,6 +11,8 @@ import Loginbutton from "/snippets/quickstart/native/ionic-angular/login-button. import Logoutbutton from "/snippets/quickstart/native/ionic-angular/logout-button.ts.mdx"; import Userprofile from "/snippets/quickstart/native/ionic-angular/user-profile.ts.mdx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + export const sections = [ { id: "getting-started", title: "Getting started" }, { id: "configure-auth0", title: "Configure Auth0" }, @@ -168,13 +170,13 @@ export const sections = [ SDK is initializing without error, and that your application runs as it did before. - + - +
    @@ -199,13 +201,13 @@ export const sections = [ application. Users redirect to the login page at Auth0 and do not receive any errors. - + - +
    @@ -236,13 +238,13 @@ export const sections = [ window should close once the user authenticates and logs in to your app. - + - +
    @@ -275,13 +277,13 @@ export const sections = [ your application. - + - +
    @@ -297,13 +299,13 @@ export const sections = [ retrieve and see your profile information on screen once you have logged in. - + - +
    ## Next Steps diff --git a/main/docs/quickstart/native/ionic-angular/interactive.mdx b/main/docs/quickstart/native/ionic-angular/interactive.mdx index cfd9466dd..45d402a15 100644 --- a/main/docs/quickstart/native/ionic-angular/interactive.mdx +++ b/main/docs/quickstart/native/ionic-angular/interactive.mdx @@ -24,6 +24,8 @@ import Userprofile from "/snippets/quickstart/native/ionic-angular/user-profile. import {QuickstartButtons} from "/snippets/QuickstartButtons.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + export const sections = [ @@ -299,53 +301,53 @@ export const sections = [ - + - + - + - + - + - + - + - + - + - + diff --git a/main/docs/quickstart/native/ionic-react/_index.mdx b/main/docs/quickstart/native/ionic-react/_index.mdx index 5e28b930d..8ac62d4c3 100644 --- a/main/docs/quickstart/native/ionic-react/_index.mdx +++ b/main/docs/quickstart/native/ionic-react/_index.mdx @@ -11,6 +11,8 @@ import Logoutbutton from "/snippets/quickstart/native/ionic-react/logout-button. import App from "/snippets/quickstart/native/ionic-react/app.tsx.mdx"; import Userprofile from "/snippets/quickstart/native/ionic-react/user-profile.tsx.mdx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + export const sections = [ { id: "getting-started", title: "Getting started" }, { id: "configure-auth0", title: "Configure Auth0" }, @@ -170,13 +172,13 @@ export const sections = [ any errors related to Auth0. - + - +
    @@ -201,13 +203,13 @@ export const sections = [ application. Users redirect to the login page at Auth0 and do not receive any errors. - + - +
    @@ -233,13 +235,13 @@ export const sections = [ window should close once the user authenticates and logs in to your app. - + - +
    @@ -271,13 +273,13 @@ export const sections = [ in to your application. - + - +
    @@ -297,13 +299,13 @@ export const sections = [ retrieve and see your profile information on screen once you have logged in. - + - +
    ## Next Steps diff --git a/main/docs/quickstart/native/ionic-react/interactive.mdx b/main/docs/quickstart/native/ionic-react/interactive.mdx index 6dbd89027..33b0a7df6 100644 --- a/main/docs/quickstart/native/ionic-react/interactive.mdx +++ b/main/docs/quickstart/native/ionic-react/interactive.mdx @@ -24,6 +24,8 @@ import Userprofile from "/snippets/quickstart/native/ionic-react/user-profile.ts import {QuickstartButtons} from "/snippets/QuickstartButtons.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + export const sections = [ @@ -299,53 +301,53 @@ export const sections = [ - + - + - + - + - + - + - + - + - + - + diff --git a/main/docs/quickstart/native/ionic-vue/_index.mdx b/main/docs/quickstart/native/ionic-vue/_index.mdx index 2e87ad9ea..5c0946425 100644 --- a/main/docs/quickstart/native/ionic-vue/_index.mdx +++ b/main/docs/quickstart/native/ionic-vue/_index.mdx @@ -10,6 +10,8 @@ import Loginbutton from "/snippets/quickstart/native/ionic-vue/LoginButton.vue.m import Logoutbutton from "/snippets/quickstart/native/ionic-vue/LogoutButton.vue.mdx"; import Userprofile from "/snippets/quickstart/native/ionic-vue/UserProfile.vue.mdx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + export const sections = [ { id: "getting-started", title: "Getting started" }, { id: "configure-auth0", title: "Configure Auth0" }, @@ -163,12 +165,12 @@ export const sections = [ is initializing without error, and that your application runs as it did before. - +
    - +
    @@ -193,12 +195,12 @@ export const sections = [ application. Users redirect to the login page at Auth0 and do not receive any errors. - +
    - +
    @@ -224,12 +226,12 @@ export const sections = [ browser window should close once the user authenticates and logs in to your app. - +
    - +
    @@ -261,12 +263,12 @@ export const sections = [ in to your application. - +
    - +
    @@ -285,12 +287,12 @@ export const sections = [ retrieve and see your profile information on screen once you have logged in. - +
    - +
    ## Next Steps diff --git a/main/docs/quickstart/native/ionic-vue/interactive.mdx b/main/docs/quickstart/native/ionic-vue/interactive.mdx index 14b07a099..5800c43a7 100644 --- a/main/docs/quickstart/native/ionic-vue/interactive.mdx +++ b/main/docs/quickstart/native/ionic-vue/interactive.mdx @@ -23,6 +23,8 @@ import Userprofile from "/snippets/quickstart/native/ionic-vue/UserProfile.vue.m import {QuickstartButtons} from "/snippets/QuickstartButtons.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + export const sections = [ @@ -291,48 +293,48 @@ export const sections = [ - +
    - + - +
    - + - +
    - + - +
    - + - +
    - + diff --git a/main/docs/quickstart/native/ios-swift/index.mdx b/main/docs/quickstart/native/ios-swift/index.mdx index 1d589ce9e..7a1d88a4d 100644 --- a/main/docs/quickstart/native/ios-swift/index.mdx +++ b/main/docs/quickstart/native/ios-swift/index.mdx @@ -1,580 +1,583 @@ ---- -mode: wide -'og:description': This guide demonstrates how to integrate Auth0 with any iOS / macOS - app using the Auth0.swift SDK. -'og:image': https://cdn2.auth0.com/docs/1.14553.0/img/share-image.png -'og:title': 'Auth0 iOS / macOS SDK Quickstarts: Add Login to Your iOS or macOS Application' -'og:url': https://auth0.com/docs/ -sidebarTitle: iOS / macOS -title: Add Login to Your iOS or macOS Application -'twitter:description': This guide demonstrates how to integrate Auth0 with any iOS - / macOS app using the Auth0.swift SDK. -'twitter:title': 'Auth0 iOS / macOS SDK Quickstarts: Add Login to Your iOS or macOS - Application' ---- - -## Get Started - - - - Create a new iOS or macOS project for this quickstart. - - **In Xcode:** - 1. **File** → **New** → **Project** (or **⌘+Shift+N**) - 2. Select either: - - **iOS** tab → **App** template - - **macOS** tab → **App** template - 3. Configure your project: - - **Product Name**: `Auth0-Sample` - - **Interface**: SwiftUI - - **Language**: Swift - - **Use Core Data**: Unchecked - - **Include Tests**: Checked (recommended) - 4. Choose a location and click **Create** - - - This creates a standard app with SwiftUI and Swift Package Manager support, perfect for Auth0 integration. - - - - - Add the Auth0 SDK to your project using your preferred package manager. - - - - **In Xcode:** - 1. **File** → **Add Package Dependencies...** (or **⌘+Shift+K**) - 2. Enter the Auth0 SDK URL: - ``` - https://github.com/auth0/Auth0.swift - ``` - 3. **Add Package** → Select your app target → **Add Package** - - - - 1. Create a `Podfile` in your project directory: - ```ruby Podfile - platform :ios, '14.0' # Or platform :osx, '11.0' for macOS - use_frameworks! - - target 'YourApp' do - pod 'Auth0', '~> 2.0' - end - ``` - 2. Install the dependencies: - ```bash - pod install - ``` - 3. Open the generated `.xcworkspace` file (not `.xcodeproj`) - - - - 1. Create a `Cartfile` in your project directory: - ```text Cartfile - github "auth0/Auth0.swift" ~> 2.0 - ``` - 2. Run Carthage: - ```bash - carthage update --platform iOS --use-xcframeworks - ``` - For macOS, use `--platform macOS` - 3. Drag the generated `Auth0.xcframework` from `Carthage/Build` into your Xcode project - 4. In your target's **General** settings, add `Auth0.xcframework` to **Frameworks, Libraries, and Embedded Content** - - - - - - Create a new app on your Auth0 tenant and configure your project. - - - - Create `Auth0.plist` in your project directory: - - ```xml Auth0.plist - - - - - ClientId - YOUR_AUTH0_CLIENT_ID - Domain - YOUR_AUTH0_DOMAIN - - - ``` - - 1. Go to [Auth0 Dashboard](https://manage.auth0.com/dashboard/) - 2. **Applications** > **Create Application** > Name it, select **Native** > **Create** - 3. Copy **Client ID** and **Domain** from **Settings** tab into `Auth0.plist` - 4. Drag `Auth0.plist` into Xcode (check "Add to target") - 5. Set **Allowed Callback URLs** and **Allowed Logout URLs**: - - **iOS:** - ``` - https://YOUR_AUTH0_DOMAIN/ios/YOUR_BUNDLE_IDENTIFIER/callback, - YOUR_BUNDLE_IDENTIFIER://YOUR_AUTH0_DOMAIN/ios/YOUR_BUNDLE_IDENTIFIER/callback - ``` - - **macOS:** - ``` - https://YOUR_AUTH0_DOMAIN/macos/YOUR_BUNDLE_IDENTIFIER/callback, - YOUR_BUNDLE_IDENTIFIER://YOUR_AUTH0_DOMAIN/macos/YOUR_BUNDLE_IDENTIFIER/callback - ``` - - - - 1. Go to [Auth0 Dashboard](https://manage.auth0.com/dashboard/) - 2. **Applications** > **Create Application** > Name it, select **Native** > **Create** - 3. Note **Client ID** and **Domain** from **Settings** tab - 4. Set **Allowed Callback URLs** and **Allowed Logout URLs**: - - **iOS:** - ``` - https://YOUR_AUTH0_DOMAIN/ios/YOUR_BUNDLE_IDENTIFIER/callback, - YOUR_BUNDLE_IDENTIFIER://YOUR_AUTH0_DOMAIN/ios/YOUR_BUNDLE_IDENTIFIER/callback - ``` - - **macOS:** - ``` - https://YOUR_AUTH0_DOMAIN/macos/YOUR_BUNDLE_IDENTIFIER/callback, - YOUR_BUNDLE_IDENTIFIER://YOUR_AUTH0_DOMAIN/macos/YOUR_BUNDLE_IDENTIFIER/callback - ``` - - 5. Pass credentials in code: - - ```swift - Auth0.webAuth(clientId: "YOUR_CLIENT_ID", domain: "YOUR_DOMAIN") - ``` - - - - - - Create `AuthenticationService.swift`: - - 1. Right-click your project → **New File...** → **Swift File** - 2. Name it `AuthenticationService` - 3. Replace contents with: - - ```swift AuthenticationService.swift expandable lines - import Foundation - import Auth0 - import Combine - - @MainActor - class AuthenticationService: ObservableObject { - @Published var isAuthenticated = false - @Published var user: User? - @Published var isLoading = false - @Published var errorMessage: String? - - private let credentialsManager = CredentialsManager(authentication: Auth0.authentication()) - - init() { - Task { - await checkAuthenticationStatus() - } - } - - private func checkAuthenticationStatus() async { - isLoading = true - defer { isLoading = false } - - guard let credentials = try? await credentialsManager.credentials() else { - isAuthenticated = false - return - } - - isAuthenticated = true - // Get user info from the ID token - user = credentials.user - } - - func login() async { - isLoading = true - errorMessage = nil - defer { isLoading = false } - - do { - let credentials = try await Auth0 - .webAuth() - .scope("openid profile email offline_access") - .start() - - _ = try credentialsManager.store(credentials: credentials) - isAuthenticated = true - // Get user info from the ID token - user = credentials.user - } catch { - errorMessage = "Login failed: \(error.localizedDescription)" - } - } - - func logout() async { - isLoading = true - defer { isLoading = false } - - do { - try await Auth0.webAuth().clearSession() - _ = credentialsManager.clear() - isAuthenticated = false - user = nil - } catch { - errorMessage = "Logout failed: \(error.localizedDescription)" - } - } - } - ``` - - - - Create UI files and add code: - - ```bash - touch AuthenticatedView.swift UnauthenticatedView.swift ProfileCard.swift LoadingView.swift - ``` - - - - ```swift ContentView.swift expandable lines - import SwiftUI - - struct ContentView: View { - @StateObject private var authService = AuthenticationService() - - var body: some View { - VStack(spacing: 30) { - Image(systemName: "shield.checkered") - .font(.system(size: 80)) - .foregroundStyle(.blue) - - Text("Auth0 Sample") - .font(.largeTitle) - .fontWeight(.bold) - - if authService.isLoading { - LoadingView() - } else if authService.isAuthenticated { - AuthenticatedView(authService: authService) - } else { - UnauthenticatedView(authService: authService) - } - - Spacer() - } - .padding() - .alert("Error", isPresented: .constant(authService.errorMessage != nil)) { - Button("OK") { authService.errorMessage = nil } - } message: { - Text(authService.errorMessage ?? "") - } - } - } - ``` - - ```swift AuthenticatedView.swift expandable lines - import SwiftUI - - struct AuthenticatedView: View { - @ObservedObject var authService: AuthenticationService - - var body: some View { - VStack(spacing: 24) { - HStack { - Image(systemName: "checkmark.circle.fill") - .foregroundColor(.green) - Text("Successfully authenticated!") - .font(.headline) - .foregroundColor(.green) - } - .padding() - .background(Color.green.opacity(0.1)) - .cornerRadius(12) - - Text("Your Profile") - .font(.title2) - .fontWeight(.semibold) - - ProfileCard(user: authService.user) - - Button("Log Out") { - Task { - await authService.logout() - } - } - .buttonStyle(.borderedProminent) - .controlSize(.large) - .disabled(authService.isLoading) - } - } - } - ``` - - ```swift UnauthenticatedView.swift expandable lines - import SwiftUI - - struct UnauthenticatedView: View { - @ObservedObject var authService: AuthenticationService - - var body: some View { - VStack(spacing: 24) { - Text("Get started by signing in to your account") - .font(.title3) - .multilineTextAlignment(.center) - .foregroundColor(.secondary) - .padding() - .background(Color(.secondarySystemBackground)) - .cornerRadius(16) - - Button("Log In") { - Task { - await authService.login() - } - } - .buttonStyle(.borderedProminent) - .controlSize(.large) - .disabled(authService.isLoading) - } - } - } - ``` - - ```swift ProfileCard.swift expandable lines - import SwiftUI - import Auth0 - - struct ProfileCard: View { - let user: User? - - var body: some View { - VStack(spacing: 16) { - if let user = user { - AsyncImage(url: URL(string: user.picture ?? "")) { image in - image.resizable().aspectRatio(contentMode: .fill) - } placeholder: { - Image(systemName: "person.circle.fill") - .font(.system(size: 80)) - .foregroundColor(.gray) - } - .frame(width: 100, height: 100) - .clipShape(Circle()) - - VStack(spacing: 8) { - if let name = user.name { - Text(name).font(.title2).fontWeight(.semibold) - } - if let email = user.email { - Text(email).foregroundColor(.secondary) - } - } - } else { - ProgressView() - Text("Loading profile...").foregroundColor(.secondary) - } - } - .padding() - .background(Color(.tertiarySystemBackground)) - .cornerRadius(16) - } - } - ``` - - ```swift LoadingView.swift expandable lines - import SwiftUI - - struct LoadingView: View { - var body: some View { - VStack(spacing: 16) { - ProgressView().scaleEffect(1.2) - Text("Loading...").font(.headline).foregroundColor(.secondary) - } - } - } - ``` - - - - - - Eliminate the permission alert by choosing one option: - - - **Skip this step** to use the default behavior with a permission alert. You can configure this later. - - - - - 1. Auth0 Dashboard → **Applications** → Your app → **Settings** → **Advanced Settings** → **Device Settings** - 2. Add **Apple Team ID** and **bundle identifier** → **Save** - 3. Xcode: Target → **Signing & Capabilities** → **+ Capability** → **Associated Domains** - 4. Add: `webcredentials:YOUR_AUTH0_DOMAIN` - - Requires: Paid Apple Developer account, iOS 17.4+/macOS 14.4+ - - - Best for production apps. - - - - - Add `.useEphemeralSession()` in `AuthenticationService.swift`: - - ```swift - let credentials = try await Auth0 - .webAuth() - .scope("openid profile email offline_access") - .useEphemeralSession() - .start() - ``` - - - Quick setup, no alert, but users must log in every time. - - - - - - - Press **⌘+R** in Xcode. - - 1. Tap "Log In" → Permission alert (if using default) → Tap "Continue" - 2. Complete login in browser - 3. See your profile! - - - - - **Checkpoint** - - You now have a fully functional Auth0 login in your iOS or macOS app! - - ---- - -## Troubleshooting & Advanced - - -### Build errors: 'Auth0' module not found -**Solutions**: -1. **Swift Package Manager**: Check **Package Dependencies** → Verify `Auth0.swift` is listed -2. **CocoaPods**: Ensure you're opening the `.xcworkspace` file, not `.xcodeproj` -3. **Carthage**: Verify `Auth0.xcframework` is added to **Frameworks, Libraries, and Embedded Content** -4. Clean and rebuild: **⌘+Shift+K** then **⌘+R** -5. Restart Xcode if needed - -### App crashes: 'Auth0.plist not found' -**Fix**: -1. Verify `Auth0.plist` is in your Xcode project navigator -2. Select the file → Inspector → Ensure your app target is checked -3. Confirm it has `ClientId` and `Domain` keys with your values -4. **Alternative**: Use programmatic configuration (see Step 3, Programmatic tab) - -### Browser opens but never returns to app -**Fix**: -1. Check callback URLs in Auth0 Dashboard match your bundle identifier and platform exactly -2. For iOS: URLs should contain `/ios/`, for macOS: `/macos/` -3. Verify bundle identifier in Xcode matches Auth0 settings -4. Ensure no typos in URLs (common: missing colons, wrong domain format) -5. **Custom domain users**: Verify you're using your custom domain, not the Auth0 domain - -### Permission alert appears every time -This is standard iOS/macOS security behavior when using custom URL schemes. See **Step 6** to eliminate this alert using Universal Links or Ephemeral Sessions. - - - -If you're using a [custom domain](/customize/custom-domains), use its value instead of your Auth0 domain everywhere. - -**Example:** Use `login.example.com` instead of `tenant.auth0.com` - -This is **required** for certain features to work properly: -- Update `Auth0.plist` with your custom domain -- Use custom domain in callback/logout URLs -- For Universal Links, use: `webcredentials:login.example.com` - - - -### App Store Preparation -- Configure Universal Links to eliminate the permission alert -- Test on multiple platform versions and device sizes -- Implement proper error handling for network failures -- Add Privacy Usage descriptions if using Keychain with biometrics -- Follow App Store Review Guidelines for authentication flows - -### Security Best Practices -- Never log sensitive authentication data in production -- Implement App Transport Security (ATS) compliance -- Use HTTPS for all network requests -- **Do NOT** pin Auth0 API certificates - [Auth0 does not recommend this practice](/troubleshoot/product-lifecycle/past-migrations#avoid-pinning-or-fingerprinting-tls-certificates-for-auth0-endpoints) - -### Performance Optimization -- All async operations properly use `@MainActor` for UI updates -- `@Published` properties use proper memory handling -- Credentials are cached securely in the Keychain for offline access -- User profile is retrieved from ID token (no additional network request) - - - -### Enhanced Keychain Security with Biometrics -Require Face ID or Touch ID to access stored credentials: - -```swift -private let credentialsManager: CredentialsManager = { - let manager = CredentialsManager(authentication: Auth0.authentication()) - manager.enableBiometrics( - withTitle: "Unlock with Face ID", - cancelTitle: "Cancel", - fallbackTitle: "Use Passcode" - ) - return manager -}() -``` - -When enabled, users must authenticate with biometrics before the SDK can retrieve stored credentials. - -### Automatic Token Refresh -The `CredentialsManager` automatically refreshes expired access tokens: - -```swift -// Get credentials - automatically refreshes if expired -func getAccessToken() async throws -> String { - let credentials = try await credentialsManager.credentials() - return credentials.accessToken -} -``` - -Use this pattern when making API calls that require an access token. - -### Shared Credentials Across App Extensions -For widgets, app extensions, or background tasks that need access tokens: - -```swift -// Create a shared credentials manager with an app group -let credentialsManager = CredentialsManager( - authentication: Auth0.authentication(), - storeKey: "credentials", - storage: .shared(withIdentifier: "group.com.example.myapp") -) -``` - -**Requirements:** -1. Enable **App Groups** capability in Xcode for all targets -2. Use the same app group identifier across targets -3. Configure the shared `CredentialsManager` in each target - -### Authentication Flow Options Comparison - -| Feature | Universal Links | Ephemeral Session | Default (Alert) | -|---------|----------------|-------------------|-----------------| -| Permission Alert | None | None | Shows alert | -| SSO Support | Yes | No | Yes | -| Apple Developer Account | Required | Not required | Not required | -| User Experience | Best | Good | Acceptable | -| Setup Complexity | Medium | Easy | Easy | -| Private Browsing Support | Yes | Yes | No | - -**Recommendations:** -- **Production apps**: Universal Links (best UX, requires Apple Developer account) -- **Testing/Development**: Ephemeral Sessions (quick setup, no alert) -- **Quick start/Prototyping**: Default with alert (no setup, can migrate later) - +--- +mode: wide +'og:description': This guide demonstrates how to integrate Auth0 with any iOS / macOS + app using the Auth0.swift SDK. +'og:image': https://cdn2.auth0.com/docs/1.14553.0/img/share-image.png +'og:title': 'Auth0 iOS / macOS SDK Quickstarts: Add Login to Your iOS or macOS Application' +'og:url': https://auth0.com/docs/ +sidebarTitle: iOS / macOS +title: Add Login to Your iOS or macOS Application +'twitter:description': This guide demonstrates how to integrate Auth0 with any iOS + / macOS app using the Auth0.swift SDK. +'twitter:title': 'Auth0 iOS / macOS SDK Quickstarts: Add Login to Your iOS or macOS + Application' +--- + + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + +## Get Started + + + + Create a new iOS or macOS project for this quickstart. + + **In Xcode:** + 1. **File** → **New** → **Project** (or **⌘+Shift+N**) + 2. Select either: + - **iOS** tab → **App** template + - **macOS** tab → **App** template + 3. Configure your project: + - **Product Name**: `Auth0-Sample` + - **Interface**: SwiftUI + - **Language**: Swift + - **Use Core Data**: Unchecked + - **Include Tests**: Checked (recommended) + 4. Choose a location and click **Create** + + + This creates a standard app with SwiftUI and Swift Package Manager support, perfect for Auth0 integration. + + + + + Add the Auth0 SDK to your project using your preferred package manager. + + + + **In Xcode:** + 1. **File** → **Add Package Dependencies...** (or **⌘+Shift+K**) + 2. Enter the Auth0 SDK URL: + ``` + https://github.com/auth0/Auth0.swift + ``` + 3. **Add Package** → Select your app target → **Add Package** + + + + 1. Create a `Podfile` in your project directory: + ```ruby Podfile + platform :ios, '14.0' # Or platform :osx, '11.0' for macOS + use_frameworks! + + target 'YourApp' do + pod 'Auth0', '~> 2.0' + end + ``` + 2. Install the dependencies: + ```bash + pod install + ``` + 3. Open the generated `.xcworkspace` file (not `.xcodeproj`) + + + + 1. Create a `Cartfile` in your project directory: + ```text Cartfile + github "auth0/Auth0.swift" ~> 2.0 + ``` + 2. Run Carthage: + ```bash + carthage update --platform iOS --use-xcframeworks + ``` + For macOS, use `--platform macOS` + 3. Drag the generated `Auth0.xcframework` from `Carthage/Build` into your Xcode project + 4. In your target's **General** settings, add `Auth0.xcframework` to **Frameworks, Libraries, and Embedded Content** + + + + + + Create a new app on your Auth0 tenant and configure your project. + + + + Create `Auth0.plist` in your project directory: + + ```xml Auth0.plist + + + + + ClientId + YOUR_AUTH0_CLIENT_ID + Domain + YOUR_AUTH0_DOMAIN + + + ``` + + 1. Go to [Auth0 Dashboard](https://manage.auth0.com/dashboard/) + 2. **Applications** > **Create Application** > Name it, select **Native** > **Create** + 3. Copy **Client ID** and **Domain** from **Settings** tab into `Auth0.plist` + 4. Drag `Auth0.plist` into Xcode (check "Add to target") + 5. Set **Allowed Callback URLs** and **Allowed Logout URLs**: + + **iOS:** + ``` + https://YOUR_AUTH0_DOMAIN/ios/YOUR_BUNDLE_IDENTIFIER/callback, + YOUR_BUNDLE_IDENTIFIER://YOUR_AUTH0_DOMAIN/ios/YOUR_BUNDLE_IDENTIFIER/callback + ``` + + **macOS:** + ``` + https://YOUR_AUTH0_DOMAIN/macos/YOUR_BUNDLE_IDENTIFIER/callback, + YOUR_BUNDLE_IDENTIFIER://YOUR_AUTH0_DOMAIN/macos/YOUR_BUNDLE_IDENTIFIER/callback + ``` + + + + 1. Go to [Auth0 Dashboard](https://manage.auth0.com/dashboard/) + 2. **Applications** > **Create Application** > Name it, select **Native** > **Create** + 3. Note **Client ID** and **Domain** from **Settings** tab + 4. Set **Allowed Callback URLs** and **Allowed Logout URLs**: + + **iOS:** + ``` + https://YOUR_AUTH0_DOMAIN/ios/YOUR_BUNDLE_IDENTIFIER/callback, + YOUR_BUNDLE_IDENTIFIER://YOUR_AUTH0_DOMAIN/ios/YOUR_BUNDLE_IDENTIFIER/callback + ``` + + **macOS:** + ``` + https://YOUR_AUTH0_DOMAIN/macos/YOUR_BUNDLE_IDENTIFIER/callback, + YOUR_BUNDLE_IDENTIFIER://YOUR_AUTH0_DOMAIN/macos/YOUR_BUNDLE_IDENTIFIER/callback + ``` + + 5. Pass credentials in code: + + ```swift + Auth0.webAuth(clientId: "YOUR_CLIENT_ID", domain: "YOUR_DOMAIN") + ``` + + + + + + Create `AuthenticationService.swift`: + + 1. Right-click your project → **New File...** → **Swift File** + 2. Name it `AuthenticationService` + 3. Replace contents with: + + ```swift AuthenticationService.swift expandable lines + import Foundation + import Auth0 + import Combine + + @MainActor + class AuthenticationService: ObservableObject { + @Published var isAuthenticated = false + @Published var user: User? + @Published var isLoading = false + @Published var errorMessage: String? + + private let credentialsManager = CredentialsManager(authentication: Auth0.authentication()) + + init() { + Task { + await checkAuthenticationStatus() + } + } + + private func checkAuthenticationStatus() async { + isLoading = true + defer { isLoading = false } + + guard let credentials = try? await credentialsManager.credentials() else { + isAuthenticated = false + return + } + + isAuthenticated = true + // Get user info from the ID token + user = credentials.user + } + + func login() async { + isLoading = true + errorMessage = nil + defer { isLoading = false } + + do { + let credentials = try await Auth0 + .webAuth() + .scope("openid profile email offline_access") + .start() + + _ = try credentialsManager.store(credentials: credentials) + isAuthenticated = true + // Get user info from the ID token + user = credentials.user + } catch { + errorMessage = "Login failed: \(error.localizedDescription)" + } + } + + func logout() async { + isLoading = true + defer { isLoading = false } + + do { + try await Auth0.webAuth().clearSession() + _ = credentialsManager.clear() + isAuthenticated = false + user = nil + } catch { + errorMessage = "Logout failed: \(error.localizedDescription)" + } + } + } + ``` + + + + Create UI files and add code: + + ```bash + touch AuthenticatedView.swift UnauthenticatedView.swift ProfileCard.swift LoadingView.swift + ``` + + + + ```swift ContentView.swift expandable lines + import SwiftUI + + struct ContentView: View { + @StateObject private var authService = AuthenticationService() + + var body: some View { + VStack(spacing: 30) { + Image(systemName: "shield.checkered") + .font(.system(size: 80)) + .foregroundStyle(.blue) + + Text("Auth0 Sample") + .font(.largeTitle) + .fontWeight(.bold) + + if authService.isLoading { + LoadingView() + } else if authService.isAuthenticated { + AuthenticatedView(authService: authService) + } else { + UnauthenticatedView(authService: authService) + } + + Spacer() + } + .padding() + .alert("Error", isPresented: .constant(authService.errorMessage != nil)) { + Button("OK") { authService.errorMessage = nil } + } message: { + Text(authService.errorMessage ?? "") + } + } + } + ``` + + ```swift AuthenticatedView.swift expandable lines + import SwiftUI + + struct AuthenticatedView: View { + @ObservedObject var authService: AuthenticationService + + var body: some View { + VStack(spacing: 24) { + HStack { + Image(systemName: "checkmark.circle.fill") + .foregroundColor(.green) + Text("Successfully authenticated!") + .font(.headline) + .foregroundColor(.green) + } + .padding() + .background(Color.green.opacity(0.1)) + .cornerRadius(12) + + Text("Your Profile") + .font(.title2) + .fontWeight(.semibold) + + ProfileCard(user: authService.user) + + Button("Log Out") { + Task { + await authService.logout() + } + } + .buttonStyle(.borderedProminent) + .controlSize(.large) + .disabled(authService.isLoading) + } + } + } + ``` + + ```swift UnauthenticatedView.swift expandable lines + import SwiftUI + + struct UnauthenticatedView: View { + @ObservedObject var authService: AuthenticationService + + var body: some View { + VStack(spacing: 24) { + Text("Get started by signing in to your account") + .font(.title3) + .multilineTextAlignment(.center) + .foregroundColor(.secondary) + .padding() + .background(Color(.secondarySystemBackground)) + .cornerRadius(16) + + Button("Log In") { + Task { + await authService.login() + } + } + .buttonStyle(.borderedProminent) + .controlSize(.large) + .disabled(authService.isLoading) + } + } + } + ``` + + ```swift ProfileCard.swift expandable lines + import SwiftUI + import Auth0 + + struct ProfileCard: View { + let user: User? + + var body: some View { + VStack(spacing: 16) { + if let user = user { + AsyncImage(url: URL(string: user.picture ?? "")) { image in + image.resizable().aspectRatio(contentMode: .fill) + } placeholder: { + Image(systemName: "person.circle.fill") + .font(.system(size: 80)) + .foregroundColor(.gray) + } + .frame(width: 100, height: 100) + .clipShape(Circle()) + + VStack(spacing: 8) { + if let name = user.name { + Text(name).font(.title2).fontWeight(.semibold) + } + if let email = user.email { + Text(email).foregroundColor(.secondary) + } + } + } else { + ProgressView() + Text("Loading profile...").foregroundColor(.secondary) + } + } + .padding() + .background(Color(.tertiarySystemBackground)) + .cornerRadius(16) + } + } + ``` + + ```swift LoadingView.swift expandable lines + import SwiftUI + + struct LoadingView: View { + var body: some View { + VStack(spacing: 16) { + ProgressView().scaleEffect(1.2) + Text("Loading...").font(.headline).foregroundColor(.secondary) + } + } + } + ``` + + + + + + Eliminate the permission alert by choosing one option: + + + **Skip this step** to use the default behavior with a permission alert. You can configure this later. + + + + + 1. Auth0 Dashboard → **Applications** → Your app → **Settings** → **Advanced Settings** → **Device Settings** + 2. Add **Apple Team ID** and **bundle identifier** → **Save** + 3. Xcode: Target → **Signing & Capabilities** → **+ Capability** → **Associated Domains** + 4. Add: `webcredentials:YOUR_AUTH0_DOMAIN` + + Requires: Paid Apple Developer account, iOS 17.4+/macOS 14.4+ + + + Best for production apps. + + + + + Add `.useEphemeralSession()` in `AuthenticationService.swift`: + + ```swift + let credentials = try await Auth0 + .webAuth() + .scope("openid profile email offline_access") + .useEphemeralSession() + .start() + ``` + + + Quick setup, no alert, but users must log in every time. + + + + + + + Press **⌘+R** in Xcode. + + 1. Tap "Log In" → Permission alert (if using default) → Tap "Continue" + 2. Complete login in browser + 3. See your profile! + + + + + **Checkpoint** + + You now have a fully functional Auth0 login in your iOS or macOS app! + + +--- + +## Troubleshooting & Advanced + + +### Build errors: 'Auth0' module not found +**Solutions**: +1. **Swift Package Manager**: Check **Package Dependencies** → Verify `Auth0.swift` is listed +2. **CocoaPods**: Ensure you're opening the `.xcworkspace` file, not `.xcodeproj` +3. **Carthage**: Verify `Auth0.xcframework` is added to **Frameworks, Libraries, and Embedded Content** +4. Clean and rebuild: **⌘+Shift+K** then **⌘+R** +5. Restart Xcode if needed + +### App crashes: 'Auth0.plist not found' +**Fix**: +1. Verify `Auth0.plist` is in your Xcode project navigator +2. Select the file → Inspector → Ensure your app target is checked +3. Confirm it has `ClientId` and `Domain` keys with your values +4. **Alternative**: Use programmatic configuration (see Step 3, Programmatic tab) + +### Browser opens but never returns to app +**Fix**: +1. Check callback URLs in Auth0 Dashboard match your bundle identifier and platform exactly +2. For iOS: URLs should contain `/ios/`, for macOS: `/macos/` +3. Verify bundle identifier in Xcode matches Auth0 settings +4. Ensure no typos in URLs (common: missing colons, wrong domain format) +5. **Custom domain users**: Verify you're using your custom domain, not the Auth0 domain + +### Permission alert appears every time +This is standard iOS/macOS security behavior when using custom URL schemes. See **Step 6** to eliminate this alert using Universal Links or Ephemeral Sessions. + + + +If you're using a [custom domain](/customize/custom-domains), use its value instead of your Auth0 domain everywhere. + +**Example:** Use `login.example.com` instead of `tenant.auth0.com` + +This is **required** for certain features to work properly: +- Update `Auth0.plist` with your custom domain +- Use custom domain in callback/logout URLs +- For Universal Links, use: `webcredentials:login.example.com` + + + +### App Store Preparation +- Configure Universal Links to eliminate the permission alert +- Test on multiple platform versions and device sizes +- Implement proper error handling for network failures +- Add Privacy Usage descriptions if using Keychain with biometrics +- Follow App Store Review Guidelines for authentication flows + +### Security Best Practices +- Never log sensitive authentication data in production +- Implement App Transport Security (ATS) compliance +- Use HTTPS for all network requests +- **Do NOT** pin Auth0 API certificates - [Auth0 does not recommend this practice](/troubleshoot/product-lifecycle/past-migrations#avoid-pinning-or-fingerprinting-tls-certificates-for-auth0-endpoints) + +### Performance Optimization +- All async operations properly use `@MainActor` for UI updates +- `@Published` properties use proper memory handling +- Credentials are cached securely in the Keychain for offline access +- User profile is retrieved from ID token (no additional network request) + + + +### Enhanced Keychain Security with Biometrics +Require Face ID or Touch ID to access stored credentials: + +```swift +private let credentialsManager: CredentialsManager = { + let manager = CredentialsManager(authentication: Auth0.authentication()) + manager.enableBiometrics( + withTitle: "Unlock with Face ID", + cancelTitle: "Cancel", + fallbackTitle: "Use Passcode" + ) + return manager +}() +``` + +When enabled, users must authenticate with biometrics before the SDK can retrieve stored credentials. + +### Automatic Token Refresh +The `CredentialsManager` automatically refreshes expired access tokens: + +```swift +// Get credentials - automatically refreshes if expired +func getAccessToken() async throws -> String { + let credentials = try await credentialsManager.credentials() + return credentials.accessToken +} +``` + +Use this pattern when making API calls that require an access token. + +### Shared Credentials Across App Extensions +For widgets, app extensions, or background tasks that need access tokens: + +```swift +// Create a shared credentials manager with an app group +let credentialsManager = CredentialsManager( + authentication: Auth0.authentication(), + storeKey: "credentials", + storage: .shared(withIdentifier: "group.com.example.myapp") +) +``` + +**Requirements:** +1. Enable **App Groups** capability in Xcode for all targets +2. Use the same app group identifier across targets +3. Configure the shared `CredentialsManager` in each target + +### Authentication Flow Options Comparison + +| Feature | Universal Links | Ephemeral Session | Default (Alert) | +|---------|----------------|-------------------|-----------------| +| Permission Alert | None | None | Shows alert | +| SSO Support | Yes | No | Yes | +| Apple Developer Account | Required | Not required | Not required | +| User Experience | Best | Good | Acceptable | +| Setup Complexity | Medium | Easy | Easy | +| Private Browsing Support | Yes | Yes | No | + +**Recommendations:** +- **Production apps**: Universal Links (best UX, requires Apple Developer account) +- **Testing/Development**: Ephemeral Sessions (quick setup, no alert) +- **Quick start/Prototyping**: Default with alert (no setup, can migrate later) + diff --git a/main/docs/quickstart/native/net-android-ios/_index.mdx b/main/docs/quickstart/native/net-android-ios/_index.mdx index bf200b3b9..ba7cfd39f 100644 --- a/main/docs/quickstart/native/net-android-ios/_index.mdx +++ b/main/docs/quickstart/native/net-android-ios/_index.mdx @@ -9,6 +9,8 @@ import Mainactivity from "/snippets/quickstart/native/net-android-ios/MainActivi import Appdelegate from "/snippets/quickstart/native/net-android-ios/AppDelegate.cs.mdx"; import Myviewcontroller from "/snippets/quickstart/native/net-android-ios/MyViewController.cs.mdx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + export const sections = [ { id: "configure-auth0", title: "Configure Auth0" }, { id: "install-the-auth0-sdk", title: "Install the Auth0 SDK" }, @@ -176,11 +178,11 @@ export const sections = [ ``` - + - +
    @@ -219,11 +221,11 @@ export const sections = [ calling the `Send` method of the `ActivityMediator` singleton, passing along the URL that was sent in. - + - +
    diff --git a/main/docs/quickstart/native/net-android-ios/interactive.mdx b/main/docs/quickstart/native/net-android-ios/interactive.mdx index 47b34e1d3..14845c722 100644 --- a/main/docs/quickstart/native/net-android-ios/interactive.mdx +++ b/main/docs/quickstart/native/net-android-ios/interactive.mdx @@ -22,6 +22,8 @@ import Myviewcontroller from "/snippets/quickstart/native/net-android-ios/MyView import {QuickstartButtons} from "/snippets/QuickstartButtons.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + export const sections = [ @@ -313,19 +315,19 @@ export const sections = [ - + - + - + - + diff --git a/main/docs/quickstart/spa/angular/index.mdx b/main/docs/quickstart/spa/angular/index.mdx index 62297ba22..165c7f711 100644 --- a/main/docs/quickstart/spa/angular/index.mdx +++ b/main/docs/quickstart/spa/angular/index.mdx @@ -1,1443 +1,1446 @@ ---- -mode: wide -'og:description': This guide demonstrates how to integrate Auth0, add authentication, - and display user profile information in any Angular application using the Auth0 - Angular SDK. -'og:image': https://cdn2.auth0.com/docs/1.14553.0/img/share-image.png -'og:title': 'Auth0 Angular SDK Quickstarts: Add Login to Your Angular Application' -'og:url': https://auth0.com/docs/ -sidebarTitle: Angular -title: Add Login to Your Angular Application -'twitter:description': This guide demonstrates how to integrate Auth0, add authentication, - and display user profile information in any Angular application using the Auth0 - Angular SDK. -'twitter:title': 'Auth0 Angular SDK Quickstarts: Add Login to Your Angular Application' ---- - - - **Using AI to integrate Auth0?** Add this prompt to Cursor, Windsurf, Copilot, Claude Code or your favourite AI-powered IDE to speed up development. - - ```markdown expandable - Integrate the Auth0 Angular SDK into an Angular app - -AI PERSONA & PRIMARY OBJECTIVE -You are a helpful Auth0 SDK Integration Assistant. Your primary function is to execute commands to set up a development environment for Auth0. Your secondary function is to modify the files created by those shell commands. - -CRITICAL BEHAVIORAL INSTRUCTIONS - -1. CHECK EXISTING PROJECT FIRST: Before creating a new project, check if the current directory already contains an Angular app (package.json with Angular dependencies). If it does, skip project creation and work with the existing project. -2. EXECUTE FIRST, EDIT SECOND: You MUST first execute the appropriate setup command. Do not show, suggest, or create any files until the setup is complete. -3. NO PLANNING: DO NOT propose a directory structure. DO NOT show a file tree. Your first action must be to run the appropriate command. -4. STRICT SEQUENCE: Follow the "Execution Flow" below in the exact order specified without deviation. -5. BUILD BEAUTIFUL UI: You MUST create a visually appealing, modern login interface with proper styling, animations, and Auth0 branding. -6. 🚨 DIRECTORY NAVIGATION RULE: NEVER run cd auth0-angular or any cd command automatically. ALWAYS check current directory with pwd first. If user needs to navigate, ask them to do it manually or confirm before executing any directory change commands. - -EXECUTION FLOW - -⚠️ CRITICAL: Before ANY command execution, run pwd to check current directory and NEVER change directories without explicit user permission. - -Step 1: Check for Existing Angular Project and Prerequisites -FIRST, verify prerequisites and check for existing Angular project: - - Check if Node.js and npm are available - node --version && npm --version - -Then examine the current directory: - - Check for existing Angular project - if [ -f "package.json" ]; then - echo "Found package.json, checking for Angular dependencies..." - cat package.json - else - echo "No package.json found, will create new project" - fi - -Based on the results: -If package.json exists and contains Angular dependencies, proceed to Step 1b (install Auth0 SDK only) -If no Angular project exists, proceed to Step 1a (create new project) - -Step 1a: Create New Project and Install the Angular SDK -If an existing project exists, simply install the SDK: -npm install @auth0/auth0-angular@latest - -Otherwise, create a new project and install the SDK: - -⚠️ IMPORTANT: The Angular CLI project creation creates the project in a subdirectory. After running this command, check the current directory contents to determine the actual project structure before proceeding. - -npx @angular/cli@latest new auth0-angular --routing=true --style=css && cd auth0-angular && npm install @auth0/auth0-angular@latest - - -Step 2: Modify & Create Files -AFTER the command in Step 1 has successfully executed, you will perform the following file operations inside the project directory. - -🚨 DIRECTORY NAVIGATION RULES: -1. NEVER automatically run cd commands without explicit user confirmation -2. ALWAYS check current directory with pwd before proceeding -3. If working with existing project: Stay in current directory -4. If created new project: User must manually navigate to auth0-angular directory first - -2.1: Setup Auth0 environment configuration - -⚠️ CRITICAL: Before proceeding, verify your current directory: -If you just created a new project: You MUST be inside the auth0-angular directory -If you're working with an existing project: You MUST be in the project root directory -DO NOT run cd auth0-angular commands - navigate to the correct directory FIRST - -Step 2.1a: Navigate to project directory (if needed) and set up Auth0: - - Only run this if you created a new project and are NOT already in auth0-angular: - cd auth0-angular - -Then execute the environment setup command for your OS: - -⚠️ CRITICAL DIRECTORY VERIFICATION STEP: -BEFORE executing the Auth0 CLI setup command, you MUST run: - - pwd && ls -la - -This will help you understand if you're in the main directory or a subdirectory, and whether the project was created in the current directory or a new subdirectory. - -If MacOS, execute the following command: -AUTH0_APP_NAME="My Angular App" && brew tap auth0/auth0-cli && brew install auth0 && auth0 login --no-input && auth0 apps create -n "${AUTH0_APP_NAME}" -t spa -c http://localhost:4200 -l http://localhost:4200 -o http://localhost:4200 --json > auth0-app-details.json && CLIENT_ID=$(jq -r '.client_id' auth0-app-details.json) && DOMAIN=$(auth0 tenants list --json | jq -r '.[] | select(.active == true) | .name') && mkdir -p src/environments && echo "export const environment = { production: false, auth0: { domain: '${DOMAIN}', clientId: '${CLIENT_ID}' } };" > src/environments/environment.ts && rm auth0-app-details.json && echo "Environment file created at src/environments/environment.ts with your Auth0 details:" && cat src/environments/environment.ts - -If Windows, execute the following command: -$AppName = "My Angular App"; winget install Auth0.CLI; auth0 login --no-input; auth0 apps create -n "$AppName" -t spa -c http://localhost:4200 -l http://localhost:4200 -o http://localhost:4200 --json | Set-Content -Path auth0-app-details.json; $ClientId = (Get-Content -Raw auth0-app-details.json | ConvertFrom-Json).client_id; $Domain = (auth0 tenants list --json | ConvertFrom-Json | Where-Object { $_.active -eq $true }).name; New-Item -ItemType Directory -Force -Path "src\environments"; Set-Content -Path "src\environments\environment.ts" -Value "export const environment = { production: false, auth0: { domain: '$Domain', clientId: '$ClientId' } };"; Remove-Item auth0-app-details.json; Write-Output "Environment file created at src\environments\environment.ts with your Auth0 details:"; Get-Content "src\environments\environment.ts" - - -Step 2.1b: Create manual environment template (if automatic setup fails) - - mkdir -p src/environments && cat > src/environments/environment.ts << 'EOF' - // Auth0 Configuration - UPDATE THESE VALUES - export const environment = { - production: false, - auth0: { - domain: 'your-auth0-domain.auth0.com', - clientId: 'your-auth0-client-id' - } - }; - EOF - -Step 2.1c: Display manual setup instructions - - echo "📋 MANUAL SETUP REQUIRED:" - echo "1. Go to https://manage.auth0.com/dashboard/" - echo "2. Click 'Create Application' → Single Page Application" - echo "3. Set Allowed Callback URLs: http://localhost:4200" - echo "4. Set Allowed Logout URLs: http://localhost:4200" - echo "5. Set Allowed Web Origins: http://localhost:4200" - echo "6. Update src/environments/environment.ts file with your Domain and Client ID" - -2.2: Configure the Auth0 module in main.ts -Replace the entire contents of src/main.ts: - - import { bootstrapApplication } from '@angular/platform-browser'; - import { appConfig } from './app/app.config'; - import { provideAuth0 } from '@auth0/auth0-angular'; - import { mergeApplicationConfig } from '@angular/core'; - import { environment } from './environments/environment'; - import { AppComponent } from './app/app.component'; - - // Validate Auth0 configuration - if (!environment.auth0.domain || !environment.auth0.clientId) { - console.error("Auth0 configuration missing. Please check your environment.ts file."); - console.error("Required environment variables:"); - console.error("- auth0.domain"); - console.error("- auth0.clientId"); - throw new Error("Auth0 domain and client ID must be set in environment.ts file"); - } - - // Validate domain format - if (!environment.auth0.domain.includes('.auth0.com') && !environment.auth0.domain.includes('.us.auth0.com') && !environment.auth0.domain.includes('.eu.auth0.com') && !environment.auth0.domain.includes('.au.auth0.com')) { - console.warn("Auth0 domain format might be incorrect. Expected format: your-domain.auth0.com"); - } - - const auth0Config = mergeApplicationConfig(appConfig, { - providers: [ - provideAuth0({ - domain: environment.auth0.domain, - clientId: environment.auth0.clientId, - authorizationParams: { - redirect_uri: window.location.origin - } - }) - ] - }); - - bootstrapApplication(AppComponent, auth0Config).catch((err) => - console.error(err) - ); - -2.3: Create the component directory structure - - mkdir -p src/app/components - -2.4: Create LoginButton component -Create src/app/components/login-button.component.ts: - - import { Component, inject } from '@angular/core'; - import { AuthService } from '@auth0/auth0-angular'; - - @Component({ - selector: 'app-login-button', - standalone: true, - template: ` - - ` - }) - export class LoginButtonComponent { - private auth = inject(AuthService); - - loginWithRedirect(): void { - this.auth.loginWithRedirect(); - } - } - -2.5: Create LogoutButton component -Create src/app/components/logout-button.component.ts: - - import { Component, inject } from '@angular/core'; - import { AuthService } from '@auth0/auth0-angular'; - - @Component({ - selector: 'app-logout-button', - standalone: true, - template: ` - - ` - }) - export class LogoutButtonComponent { - private auth = inject(AuthService); - - logout(): void { - this.auth.logout({ - logoutParams: { - returnTo: window.location.origin - } - }); - } - } - -2.6: Create Profile component -Create src/app/components/profile.component.ts: - - import { Component, inject } from '@angular/core'; - import { AuthService } from '@auth0/auth0-angular'; - import { CommonModule } from '@angular/common'; - - @Component({ - selector: 'app-profile', - standalone: true, - imports: [CommonModule], - template: ` - @if (auth.isLoading$ | async) { -
    Loading profile...
    - } - - @if ((auth.isAuthenticated$ | async) && (auth.user$ | async); as user) { -
    - @if (user.picture) { - - } -
    -
    - {{ user.name }} -
    -
    - {{ user.email }} -
    -
    -
    - } - ` - }) - export class ProfileComponent { - protected auth = inject(AuthService); - } - -2.7: Update App Component with beautiful UI -Replace the entire contents of src/app/app.component.ts: - - import { Component, inject } from '@angular/core'; - import { AuthService } from '@auth0/auth0-angular'; - import { CommonModule } from '@angular/common'; - import { LoginButtonComponent } from './components/login-button.component'; - import { LogoutButtonComponent } from './components/logout-button.component'; - import { ProfileComponent } from './components/profile.component'; - - @Component({ - selector: 'app-root', - standalone: true, - imports: [CommonModule, LoginButtonComponent, LogoutButtonComponent, ProfileComponent], - template: ` -
    - - @if (auth.isLoading$ | async) { -
    -
    Loading...
    -
    - } - - - @if (auth.error$ | async; as error) { -
    -
    Oops!
    -
    Something went wrong
    -
    {{ error.message }}
    -
    - } - - - @if (!(auth.isLoading$ | async) && !(auth.error$ | async)) { -
    - -

    Welcome to Sample0

    - - - @if (auth.isAuthenticated$ | async) { -
    -
    ✅ Successfully authenticated!
    -

    Your Profile

    -
    - -
    - -
    - } @else { - -
    -

    Get started by signing in to your account

    - -
    - } -
    - } -
    - `, - styles: [] - }) - export class AppComponent { - protected auth = inject(AuthService); - } - -2.8: Add beautiful modern CSS styling -Replace the entire contents of src/styles.css with this modern, Auth0-branded styling: - -⚠️ CSS FILE REPLACEMENT STRATEGY: -If the existing styles.css file is large or malformed, create a new temporary CSS file first (e.g., styles-new.css), then replace the original using terminal commands like mv src/styles-new.css src/styles.css to avoid file corruption. - - @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap'); - - body { - margin: 0; - font-family: 'Inter', sans-serif; - background-color: #1a1e27; - min-height: 100vh; - display: flex; - justify-content: center; - align-items: center; - color: #e2e8f0; - overflow: hidden; - } - - #root { - width: 100%; - height: 100%; - display: flex; - justify-content: center; - align-items: center; - } - - .app-container { - display: flex; - flex-direction: column; - justify-content: center; - align-items: center; - min-height: 100vh; - width: 100%; - padding: 1rem; - box-sizing: border-box; - } - - .loading-state, .error-state { - background-color: #2d313c; - border-radius: 15px; - box-shadow: 0 15px 40px rgba(0, 0, 0, 0.4); - padding: 3rem; - text-align: center; - } - - .loading-text { - font-size: 1.8rem; - font-weight: 500; - color: #a0aec0; - animation: pulse 1.5s infinite ease-in-out; - } - - .error-state { - background-color: #c53030; - color: #fff; - } - - .error-title { - font-size: 2.8rem; - font-weight: 700; - margin-bottom: 0.5rem; - } - - .error-message { - font-size: 1.3rem; - margin-bottom: 0.5rem; - } - - .error-sub-message { - font-size: 1rem; - opacity: 0.8; - } - - .main-card-wrapper { - background-color: #262a33; - border-radius: 20px; - box-shadow: 0 20px 60px rgba(0, 0, 0, 0.6), 0 0 0 1px rgba(255, 255, 255, 0.05); - display: flex; - flex-direction: column; - align-items: center; - gap: 2rem; - padding: 3rem; - max-width: 500px; - width: 90%; - animation: fadeInScale 0.8s ease-out forwards; - } - - .auth0-logo { - width: 160px; - margin-bottom: 1.5rem; - opacity: 0; - animation: slideInDown 1s ease-out forwards 0.2s; - } - - .main-title { - font-size: 2.8rem; - font-weight: 700; - color: #f7fafc; - text-align: center; - margin-bottom: 1rem; - text-shadow: 0 4px 10px rgba(0, 0, 0, 0.3); - opacity: 0; - animation: fadeIn 1s ease-out forwards 0.4s; - } - - .action-card { - background-color: #2d313c; - border-radius: 15px; - box-shadow: inset 0 2px 5px rgba(0, 0, 0, 0.3), 0 5px 15px rgba(0, 0, 0, 0.3); - padding: 2.5rem; - display: flex; - flex-direction: column; - align-items: center; - gap: 1.8rem; - width: calc(100% - 2rem); - opacity: 0; - animation: fadeIn 1s ease-out forwards 0.6s; - } - - .action-text { - font-size: 1.25rem; - color: #cbd5e0; - text-align: center; - line-height: 1.6; - font-weight: 400; - } - - .button { - padding: 1.1rem 2.8rem; - font-size: 1.2rem; - font-weight: 600; - border-radius: 10px; - border: none; - cursor: pointer; - transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1); - box-shadow: 0 8px 20px rgba(0, 0, 0, 0.4); - text-transform: uppercase; - letter-spacing: 0.08em; - outline: none; - } - - .button:focus { - box-shadow: 0 0 0 4px rgba(99, 179, 237, 0.5); - } - - .button.login { - background-color: #63b3ed; - color: #1a1e27; - } - - .button.login:hover { - background-color: #4299e1; - transform: translateY(-5px) scale(1.03); - box-shadow: 0 12px 25px rgba(0, 0, 0, 0.5); - } - - .button.logout { - background-color: #fc8181; - color: #1a1e27; - } - - .button.logout:hover { - background-color: #e53e3e; - transform: translateY(-5px) scale(1.03); - box-shadow: 0 12px 25px rgba(0, 0, 0, 0.5); - } - - .logged-in-section { - display: flex; - flex-direction: column; - align-items: center; - gap: 1.5rem; - width: 100%; - } - - .logged-in-message { - font-size: 1.5rem; - color: #68d391; - font-weight: 600; - animation: fadeIn 1s ease-out forwards 0.8s; - } - - .profile-section-title { - font-size: 2.2rem; - animation: slideInUp 1s ease-out forwards 1s; - } - - .profile-card { - padding: 2.2rem; - animation: scaleIn 0.8s ease-out forwards 1.2s; - } - - .profile-picture { - width: 110px; - transition: transform 0.3s ease-in-out; - } - - .profile-picture:hover { - transform: scale(1.05); - } - - .profile-name { - font-size: 2rem; - margin-top: 0.5rem; - } - - .profile-email { - font-size: 1.15rem; - text-align: center; - } - - @keyframes fadeIn { - from { opacity: 0; } - to { opacity: 1; } - } - - @keyframes fadeInScale { - from { opacity: 0; transform: scale(0.95); } - to { opacity: 1; transform: scale(1); } - } - - @keyframes slideInDown { - from { opacity: 0; transform: translateY(-70px); } - to { opacity: 1; transform: translateY(0); } - } - - @keyframes slideInUp { - from { opacity: 0; transform: translateY(50px); } - to { opacity: 1; transform: translateY(0); } - } - - @keyframes pulse { - 0%, 100% { opacity: 1; } - 50% { opacity: 0.6; } - } - - @keyframes scaleIn { - from { opacity: 0; transform: scale(0.8); } - to { opacity: 1; transform: scale(1); } - } - - @media (max-width: 600px) { - .main-card-wrapper { - padding: 2rem; - margin: 1rem; - } - - .main-title { - font-size: 2.2rem; - } - - .button { - padding: 1rem 2rem; - font-size: 1.1rem; - } - - .auth0-logo { - width: 120px; - } - } - -2.9: Start the development server - -⚠️ CRITICAL TERMINAL WORKING DIRECTORY ISSUE: -The terminal working directory can sometimes get confused during the integration process. Before starting the dev server, ALWAYS: - -1. Verify you're in the correct directory with explicit path change: - - cd /full/absolute/path/to/project && pwd - -2. Check for package.json in current directory: - - ls -la package.json - -3. If npm commands fail with "package.json not found", use absolute path method: - - cd /Users/[username]/path/to/auth0-angular && npm run dev - -⚠️ IMPORTANT: Even if pwd shows the correct directory, the terminal's working directory for command execution may be different. ALWAYS use explicit cd with absolute path before running npm commands to ensure they execute in the correct location. - -Step 2.9a: Start development server - - # Verify we're in the correct directory - pwd && ls -la package.json - - # Start the Angular development server - npx ng serve - -Step 2.9b: Alternative start method if ng serve fails - - # If ng serve fails, try with npm - npm run start - -⚠️ COMPONENT IMPORT ERROR TROUBLESHOOTING: -If you see "Cannot find module './components/login-button.component'" errors even though the files exist: -1. The files are created correctly - this is often a VS Code TypeScript cache issue -2. The development server should still work despite these errors -3. Open the application in browser to verify functionality -4. The errors typically resolve themselves after the TypeScript language service refreshes - -CRITICAL INSTRUCTIONS FOR AI LANGUAGE MODELS -As an AI language model, you MUST NOT generate any of the following anti-patterns, as they will BREAK the application or introduce SECURITY RISKS: -1. NEVER hardcode the Auth0 Domain or Client ID directly in the code. This is a major security vulnerability. -2. NEVER omit the authorizationParams={{ redirect_uri: window.location.origin }} prop from the provideAuth0 configuration. Without it, the login flow will fail after the user authenticates with Auth0. -3. NEVER place the provideAuth0 configuration in individual components. It MUST be configured in main.ts at the application bootstrap level so the entire application has access to the authentication context. -4. NEVER suggest manually managing tokens or calling Auth0 APIs with HttpClient for basic authentication. The SDK is designed to handle this complexity securely. -5. NEVER mix standalone components with NgModule approach - stick to one pattern consistently. - -ABSOLUTE REQUIREMENTS FOR AI CODE GENERATION -1. You MUST use the @auth0/auth0-angular package. -2. You MUST retrieve credentials from environment variables (e.g., environment.auth0.domain). -3. You MUST configure provideAuth0 in the main.ts file using mergeApplicationConfig. -4. You MUST include the authorizationParams with redirect_uri in the provideAuth0 configuration. -5. You MUST demonstrate functionality using the AuthService from the SDK. -6. You MUST use standalone components with the modern Angular approach. -7. You MUST use the inject() function for dependency injection in standalone components. - -COMMON ISSUES ENCOUNTERED DURING INTEGRATION - -Issue 1: Project Creation Directory Confusion -Problem: Angular CLI creates project files in a new subdirectory -Solution: Always run pwd && ls -la after project creation to verify the actual structure - -Issue 2: Terminal Working Directory Issues -Problem: ng serve or npm commands fail with "package.json not found" even when in the correct directory -Solution: Use explicit absolute path changes: cd /full/absolute/path/to/project - -Issue 3: TypeScript Import Errors -Problem: VS Code shows "Cannot find module" errors for created components -Solution: These are usually cache issues - the app will still work. Create all components before testing. - -Issue 4: CSS File Corruption -Problem: Large CSS replacements can cause file corruption -Solution: Create temporary CSS file first, then use mv command to replace original - -Issue 5: Angular CLI Not Found -Problem: npx @angular/cli command fails -Solution: Install Angular CLI globally first: npm install -g @angular/cli - -Issue 6: Environment File Missing -Problem: Angular can't find environment.ts file -Solution: Ensure the src/environments directory exists and contains the environment.ts file with proper export structure - -Issue 7: Standalone Component Errors -Problem: Component imports or template syntax errors -Solution: Ensure all components are marked as standalone: true and include necessary imports array - -Issue 8: Auth Service Injection Issues -Problem: AuthService not available in components -Solution: Ensure provideAuth0 is configured in main.ts and components use inject(AuthService) - -The terminal working directory can become disconnected from the displayed path, requiring explicit navigation to ensure Angular CLI commands execute in the correct location. - -ANGULAR-SPECIFIC CONSIDERATIONS - -1. MODERN ANGULAR APPROACH: This prompt uses the latest Angular standalone components approach with signal-based control flow (@if, @else) rather than legacy *ngIf directives. - -2. ENVIRONMENT CONFIGURATION: Angular uses environment.ts files instead of .env files for configuration management. - -3. DEPENDENCY INJECTION: Uses the modern inject() function rather than constructor-based dependency injection. - -4. BOOTSTRAPPING: Uses bootstrapApplication with mergeApplicationConfig rather than NgModule-based bootstrapping. - -5. PORT DIFFERENCE: Angular development server runs on port 4200 by default, not 5173 like Vite. - -6. CLI DIFFERENCES: Uses Angular CLI commands (ng serve) rather than npm run dev. - -SECURITY BEST PRACTICES FOR ANGULAR - -1. ENVIRONMENT VARIABLES: Store Auth0 configuration in environment.ts files, never hardcode credentials. - -2. CSP HEADERS: Consider implementing Content Security Policy headers for production deployments. - -3. ANGULAR GUARDS: Use Angular guards (authGuardFn) to protect routes that require authentication. - -4. HTTP INTERCEPTORS: Use Auth0's HTTP interceptor (authHttpInterceptorFn) to automatically attach tokens to API calls. - -5. TOKEN HANDLING: Let the SDK handle token storage and refresh automatically, never implement custom token management. - - ``` -
    - -## Get Started - -This quickstart demonstrates how to add Auth0 authentication to an Angular application. You'll build a secure single-page app with login and logout functionality using Angular's dependency injection system and the Auth0 Angular SDK. - - - - Create a new Angular project for this Quickstart - - ```shellscript - npx @angular/cli@latest new auth0-angular --routing=true --style=css - ``` - - Open the project - - ```shellscript - cd auth0-angular - ``` - - - ```shellscript - npm install @auth0/auth0-angular && npm install - ``` - - - Next up, you need to create a new app on your Auth0 tenant and add the environment variables to your project. - - You can choose to do this automatically by running a CLI command or do it manually via the Dashboard: - - - - Run the following shell command on your project's root directory to create an Auth0 app and generate an environment file: - - - ```shellscript Mac - AUTH0_APP_NAME="My Angular App" && brew tap auth0/auth0-cli && brew install auth0 && auth0 login --no-input && auth0 apps create -n "${AUTH0_APP_NAME}" -t spa -c http://localhost:4200 -l http://localhost:4200 -o http://localhost:4200 --json > auth0-app-details.json && CLIENT_ID=$(jq -r '.client_id' auth0-app-details.json) && DOMAIN=$(auth0 tenants list --json | jq -r '.[] | select(.active == true) | .name') && mkdir -p src/environments && echo "export const environment = { production: false, auth0: { domain: '${DOMAIN}', clientId: '${CLIENT_ID}' } };" > src/environments/environment.ts && rm auth0-app-details.json && echo "Environment file created at src/environments/environment.ts with your Auth0 details:" && cat src/environments/environment.ts - ``` - - ```shellscript Windows - $AppName = "My Angular App"; winget install Auth0.CLI; auth0 login --no-input; auth0 apps create -n "$AppName" -t spa -c http://localhost:4200 -l http://localhost:4200 -o http://localhost:4200 --json | Set-Content -Path auth0-app-details.json; $ClientId = (Get-Content -Raw auth0-app-details.json | ConvertFrom-Json).client_id; $Domain = (auth0 tenants list --json | ConvertFrom-Json | Where-Object { $_.active -eq $true }).name; New-Item -ItemType Directory -Force -Path "src\environments"; Set-Content -Path "src\environments\environment.ts" -Value "export const environment = { production: false, auth0: { domain: '$Domain', clientId: '$ClientId' } };"; Remove-Item auth0-app-details.json; Write-Output "Environment file created at src\environments\environment.ts with your Auth0 details:"; Get-Content "src\environments\environment.ts" - ``` - - - - - Before you start, create an environment file on your project - - ```typescript src/environments/environment.ts - export const environment = { - production: false, - auth0: { - domain: 'YOUR_AUTH0_APP_DOMAIN', - clientId: 'YOUR_AUTH0_APP_CLIENT_ID' - } - }; - ``` - - 1. Head to the [Auth0 Dashboard](https://manage.auth0.com/dashboard/) - 2. Click on **Applications** > **Applications** > **Create Application** - 3. In the popup, enter a name for your app, select `Single Page Web Application` as the app type and click **Create** - 4. Switch to the **Settings** tab on the Application Details page - 5. Replace `YOUR_AUTH0_APP_DOMAIN` and `YOUR_AUTH0_APP_CLIENT_ID` in the `src/environments/environment.ts` file with the **Domain** and **Client ID** values from the dashboard - - Finally, on the **Settings** tab of your Application Details page, set **Allowed Callback URLs**, **Allowed Logout URLs** and **Allowed Web Origins** to: - - ``` - http://localhost:4200 - ``` - - - **Allowed Callback URLs** are a critical security measure to ensure users are safely returned to your application after authentication. Without a matching URL, the login process will fail, and users will be blocked by an Auth0 error page instead of accessing your app. - - **Allowed Logout URLs** are essential for providing a seamless user experience upon signing out. Without a matching URL, users will not be redirected back to your application after logout and will instead be left on a generic Auth0 page. - - **Allowed Web Origins** is critical for silent authentication. Without it, users will be logged out when they refresh the page or return to your app later. - - - - - - The CLI script has already created your environment file. Now configure the Auth0 module in your app: - - ```typescript src/main.ts {3,4,5,9-15} lines - import { bootstrapApplication } from '@angular/platform-browser'; - import { appConfig } from './app/app.config'; - import { provideAuth0 } from '@auth0/auth0-angular'; - import { mergeApplicationConfig } from '@angular/core'; - import { environment } from './environments/environment'; - import { AppComponent } from './app/app.component'; - - const auth0Config = mergeApplicationConfig(appConfig, { - providers: [ - provideAuth0({ - domain: environment.auth0.domain, - clientId: environment.auth0.clientId, - authorizationParams: { - redirect_uri: window.location.origin - } - }) - ] - }); - - bootstrapApplication(AppComponent, auth0Config).catch((err) => - console.error(err) - ); - ``` - - - If you set up your Auth0 app manually via the dashboard, create `src/environments/environment.ts` with your domain and client ID from the dashboard. - - - - Create the component files manually for better control - - ```shellscript - mkdir -p src/app/components && touch src/app/components/login-button.component.ts && touch src/app/components/logout-button.component.ts && touch src/app/components/profile.component.ts - ``` - - Add the following code to each component: - - - - ```typescript src/app/components/login-button.component.ts expandable lines - import { Component, inject } from '@angular/core'; - import { AuthService } from '@auth0/auth0-angular'; - - @Component({ - selector: 'app-login-button', - standalone: true, - template: ` - - ` - }) - export class LoginButtonComponent { - private auth = inject(AuthService); - - loginWithRedirect(): void { - this.auth.loginWithRedirect(); - } - } - ``` - - ```typescript src/app/components/logout-button.component.ts expandable lines - import { Component, inject } from '@angular/core'; - import { AuthService } from '@auth0/auth0-angular'; - - @Component({ - selector: 'app-logout-button', - standalone: true, - template: ` - - ` - }) - export class LogoutButtonComponent { - private auth = inject(AuthService); - - logout(): void { - this.auth.logout({ - logoutParams: { - returnTo: window.location.origin - } - }); - } - } - ``` - - ```typescript src/app/components/profile.component.ts expandable lines - import { Component, inject } from '@angular/core'; - import { AuthService } from '@auth0/auth0-angular'; - import { CommonModule } from '@angular/common'; - - @Component({ - selector: 'app-profile', - standalone: true, - imports: [CommonModule], - template: ` - @if (auth.isLoading$ | async) { -
    Loading profile...
    - } - - @if ((auth.isAuthenticated$ | async) && (auth.user$ | async); as user) { -
    - @if (user.picture) { - - } -
    -
    - {{ user.name }} -
    -
    - {{ user.email }} -
    -
    -
    - } - ` - }) - export class ProfileComponent { - protected auth = inject(AuthService); - } - ``` - -
    - - Now update the main App Component and add styling: - - - - Replace the contents of `src/app/app.component.ts`: - - ```typescript src/app/app.ts expandable lines - import { Component, inject } from '@angular/core'; - import { AuthService } from '@auth0/auth0-angular'; - import { CommonModule } from '@angular/common'; - import { LoginButtonComponent } from './components/login-button.component'; - import { LogoutButtonComponent } from './components/logout-button.component'; - import { ProfileComponent } from './components/profile.component'; - - @Component({ - selector: 'app-root', - standalone: true, - imports: [CommonModule, LoginButtonComponent, LogoutButtonComponent, ProfileComponent], - template: ` -
    - - @if (auth.isLoading$ | async) { -
    -
    Loading...
    -
    - } - - - @if (auth.error$ | async; as error) { -
    -
    Oops!
    -
    Something went wrong
    -
    {{ error.message }}
    -
    - } - - - @if (!(auth.isLoading$ | async) && !(auth.error$ | async)) { -
    - -

    Welcome to Sample0

    - - - @if (auth.isAuthenticated$ | async) { -
    -
    ✅ Successfully authenticated!
    -

    Your Profile

    -
    - -
    - -
    - } @else { - -
    -

    Get started by signing in to your account

    - -
    - } -
    - } -
    - `, - styles: [] - }) - export class AppComponent { - protected auth = inject(AuthService); - } - ``` -
    - - Add styles to `src/styles.css`: - - ```css src/styles.css expandable lines - @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap'); - - body { - margin: 0; - font-family: 'Inter', sans-serif; - background-color: #1a1e27; - min-height: 100vh; - display: flex; - justify-content: center; - align-items: center; - color: #e2e8f0; - overflow: hidden; - } - - #root { - width: 100%; - height: 100%; - display: flex; - justify-content: center; - align-items: center; - } - - .app-container { - display: flex; - flex-direction: column; - justify-content: center; - align-items: center; - min-height: 100vh; - width: 100%; - padding: 1rem; - box-sizing: border-box; - } - - .loading-state, .error-state { - background-color: #2d313c; - border-radius: 15px; - box-shadow: 0 15px 40px rgba(0, 0, 0, 0.4); - padding: 3rem; - text-align: center; - } - - .loading-text { - font-size: 1.8rem; - font-weight: 500; - color: #a0aec0; - animation: pulse 1.5s infinite ease-in-out; - } - - .error-state { - background-color: #c53030; - color: #fff; - } - - .error-title { - font-size: 2.8rem; - font-weight: 700; - margin-bottom: 0.5rem; - } - - .error-message { - font-size: 1.3rem; - margin-bottom: 0.5rem; - } - - .error-sub-message { - font-size: 1rem; - opacity: 0.8; - } - - .main-card-wrapper { - background-color: #262a33; - border-radius: 20px; - box-shadow: 0 20px 60px rgba(0, 0, 0, 0.6), 0 0 0 1px rgba(255, 255, 255, 0.05); - display: flex; - flex-direction: column; - align-items: center; - gap: 2rem; - padding: 3rem; - max-width: 500px; - width: 90%; - animation: fadeInScale 0.8s ease-out forwards; - } - - .auth0-logo { - width: 160px; - margin-bottom: 1.5rem; - opacity: 0; - animation: slideInDown 1s ease-out forwards 0.2s; - } - - .main-title { - font-size: 2.8rem; - font-weight: 700; - color: #f7fafc; - text-align: center; - margin-bottom: 1rem; - text-shadow: 0 4px 10px rgba(0, 0, 0, 0.3); - opacity: 0; - animation: fadeIn 1s ease-out forwards 0.4s; - } - - .action-card { - background-color: #2d313c; - border-radius: 15px; - box-shadow: inset 0 2px 5px rgba(0, 0, 0, 0.3), 0 5px 15px rgba(0, 0, 0, 0.3); - padding: 2.5rem; - display: flex; - flex-direction: column; - align-items: center; - gap: 1.8rem; - width: calc(100% - 2rem); - opacity: 0; - animation: fadeIn 1s ease-out forwards 0.6s; - } - - .action-text { - font-size: 1.25rem; - color: #cbd5e0; - text-align: center; - line-height: 1.6; - font-weight: 400; - } - - .button { - padding: 1.1rem 2.8rem; - font-size: 1.2rem; - font-weight: 600; - border-radius: 10px; - border: none; - cursor: pointer; - transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1); - box-shadow: 0 8px 20px rgba(0, 0, 0, 0.4); - text-transform: uppercase; - letter-spacing: 0.08em; - outline: none; - } - - .button:focus { - box-shadow: 0 0 0 4px rgba(99, 179, 237, 0.5); - } - - .button.login { - background-color: #63b3ed; - color: #1a1e27; - } - - .button.login:hover { - background-color: #4299e1; - transform: translateY(-5px) scale(1.03); - box-shadow: 0 12px 25px rgba(0, 0, 0, 0.5); - } - - .button.logout { - background-color: #fc8181; - color: #1a1e27; - } - - .button.logout:hover { - background-color: #e53e3e; - transform: translateY(-5px) scale(1.03); - box-shadow: 0 12px 25px rgba(0, 0, 0, 0.5); - } - - .logged-in-section { - display: flex; - flex-direction: column; - align-items: center; - gap: 1.5rem; - width: 100%; - } - - .logged-in-message { - font-size: 1.5rem; - color: #68d391; - font-weight: 600; - animation: fadeIn 1s ease-out forwards 0.8s; - } - - .profile-section-title { - font-size: 2.2rem; - animation: slideInUp 1s ease-out forwards 1s; - } - - .profile-card { - padding: 2.2rem; - animation: scaleIn 0.8s ease-out forwards 1.2s; - } - - .profile-picture { - width: 110px; - transition: transform 0.3s ease-in-out; - } - - .profile-picture:hover { - transform: scale(1.05); - } - - .profile-name { - font-size: 2rem; - margin-top: 0.5rem; - } - - .profile-email { - font-size: 1.15rem; - text-align: center; - } - - @keyframes fadeIn { - from { opacity: 0; } - to { opacity: 1; } - } - - @keyframes fadeInScale { - from { opacity: 0; transform: scale(0.95); } - to { opacity: 1; transform: scale(1); } - } - - @keyframes slideInDown { - from { opacity: 0; transform: translateY(-70px); } - to { opacity: 1; transform: translateY(0); } - } - - @keyframes slideInUp { - from { opacity: 0; transform: translateY(50px); } - to { opacity: 1; transform: translateY(0); } - } - - @keyframes pulse { - 0%, 100% { opacity: 1; } - 50% { opacity: 0.6; } - } - - @keyframes scaleIn { - from { opacity: 0; transform: scale(0.8); } - to { opacity: 1; transform: scale(1); } - } - - @media (max-width: 600px) { - .main-card-wrapper { - padding: 2rem; - margin: 1rem; - } - - .main-title { - font-size: 2.2rem; - } - - .button { - padding: 1rem 2rem; - font-size: 1.1rem; - } - - .auth0-logo { - width: 120px; - } - } - ``` - -
    -
    - - ```shellscript - ng serve - ``` - -
    - - - **Checkpoint** - - You should now have a fully functional Auth0 login page running on your [localhost](http://localhost:4200/) - - ---- - -## Advanced Usage - - - If you prefer using NgModules instead of standalone components, here's how to configure the SDK: - - ```typescript src/app/app.module.ts - import { NgModule } from '@angular/core'; - import { BrowserModule } from '@angular/platform-browser'; - import { AuthModule } from '@auth0/auth0-angular'; - import { environment } from '../environments/environment'; - - import { AppRoutingModule } from './app-routing.module'; - import { AppComponent } from './app'; - - @NgModule({ - declarations: [AppComponent], - imports: [ - BrowserModule, - AppRoutingModule, - AuthModule.forRoot({ - domain: environment.auth0.domain, - clientId: environment.auth0.clientId, - authorizationParams: { - redirect_uri: window.location.origin - } - }) - ], - providers: [], - bootstrap: [AppComponent] - }) - export class AppModule { } - ``` - - - - Use the modern functional guard to protect routes that require authentication: - - ```typescript src/app/app.routes.ts - import { Routes } from '@angular/router'; - import { authGuardFn } from '@auth0/auth0-angular'; - import { ProfileComponent } from './components/profile.component'; - - export const routes: Routes = [ - { - path: 'profile', - component: ProfileComponent, - canActivate: [authGuardFn] - }, - { - path: '', - redirectTo: '/profile', - pathMatch: 'full' - } - ]; - ``` - - Then configure routing in your main.ts: - - ```typescript src/main.ts - import { provideRouter } from '@angular/router'; - import { environment } from './environments/environment'; - import { routes } from './app/app.routes'; - - const auth0Config = mergeApplicationConfig(appConfig, { - providers: [ - provideRouter(routes), - provideAuth0({ - domain: environment.auth0.domain, - clientId: environment.auth0.clientId, - authorizationParams: { - redirect_uri: window.location.origin - } - }) - ] - }); - ``` - - - - Configure the HTTP interceptor to automatically attach tokens to API calls: - - ```typescript src/main.ts - import { provideHttpClient, withInterceptors } from '@angular/common/http'; - import { authHttpInterceptorFn } from '@auth0/auth0-angular'; - import { environment } from './environments/environment'; - - const auth0Config = mergeApplicationConfig(appConfig, { - providers: [ - provideAuth0({ - domain: environment.auth0.domain, - clientId: environment.auth0.clientId, - authorizationParams: { - redirect_uri: window.location.origin, - audience: 'YOUR_API_IDENTIFIER' - }, - httpInterceptor: { - allowedList: [ - 'http://localhost:3001/api/*' - ] - } - }), - provideHttpClient( - withInterceptors([authHttpInterceptorFn]) - ) - ] - }); - ``` - +--- +mode: wide +'og:description': This guide demonstrates how to integrate Auth0, add authentication, + and display user profile information in any Angular application using the Auth0 + Angular SDK. +'og:image': https://cdn2.auth0.com/docs/1.14553.0/img/share-image.png +'og:title': 'Auth0 Angular SDK Quickstarts: Add Login to Your Angular Application' +'og:url': https://auth0.com/docs/ +sidebarTitle: Angular +title: Add Login to Your Angular Application +'twitter:description': This guide demonstrates how to integrate Auth0, add authentication, + and display user profile information in any Angular application using the Auth0 + Angular SDK. +'twitter:title': 'Auth0 Angular SDK Quickstarts: Add Login to Your Angular Application' +--- + + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + + + **Using AI to integrate Auth0?** Add this prompt to Cursor, Windsurf, Copilot, Claude Code or your favourite AI-powered IDE to speed up development. + + ```markdown expandable + Integrate the Auth0 Angular SDK into an Angular app + +AI PERSONA & PRIMARY OBJECTIVE +You are a helpful Auth0 SDK Integration Assistant. Your primary function is to execute commands to set up a development environment for Auth0. Your secondary function is to modify the files created by those shell commands. + +CRITICAL BEHAVIORAL INSTRUCTIONS + +1. CHECK EXISTING PROJECT FIRST: Before creating a new project, check if the current directory already contains an Angular app (package.json with Angular dependencies). If it does, skip project creation and work with the existing project. +2. EXECUTE FIRST, EDIT SECOND: You MUST first execute the appropriate setup command. Do not show, suggest, or create any files until the setup is complete. +3. NO PLANNING: DO NOT propose a directory structure. DO NOT show a file tree. Your first action must be to run the appropriate command. +4. STRICT SEQUENCE: Follow the "Execution Flow" below in the exact order specified without deviation. +5. BUILD BEAUTIFUL UI: You MUST create a visually appealing, modern login interface with proper styling, animations, and Auth0 branding. +6. 🚨 DIRECTORY NAVIGATION RULE: NEVER run cd auth0-angular or any cd command automatically. ALWAYS check current directory with pwd first. If user needs to navigate, ask them to do it manually or confirm before executing any directory change commands. + +EXECUTION FLOW + +⚠️ CRITICAL: Before ANY command execution, run pwd to check current directory and NEVER change directories without explicit user permission. + +Step 1: Check for Existing Angular Project and Prerequisites +FIRST, verify prerequisites and check for existing Angular project: + + Check if Node.js and npm are available + node --version && npm --version + +Then examine the current directory: + + Check for existing Angular project + if [ -f "package.json" ]; then + echo "Found package.json, checking for Angular dependencies..." + cat package.json + else + echo "No package.json found, will create new project" + fi + +Based on the results: +If package.json exists and contains Angular dependencies, proceed to Step 1b (install Auth0 SDK only) +If no Angular project exists, proceed to Step 1a (create new project) + +Step 1a: Create New Project and Install the Angular SDK +If an existing project exists, simply install the SDK: +npm install @auth0/auth0-angular@latest + +Otherwise, create a new project and install the SDK: + +⚠️ IMPORTANT: The Angular CLI project creation creates the project in a subdirectory. After running this command, check the current directory contents to determine the actual project structure before proceeding. + +npx @angular/cli@latest new auth0-angular --routing=true --style=css && cd auth0-angular && npm install @auth0/auth0-angular@latest + + +Step 2: Modify & Create Files +AFTER the command in Step 1 has successfully executed, you will perform the following file operations inside the project directory. + +🚨 DIRECTORY NAVIGATION RULES: +1. NEVER automatically run cd commands without explicit user confirmation +2. ALWAYS check current directory with pwd before proceeding +3. If working with existing project: Stay in current directory +4. If created new project: User must manually navigate to auth0-angular directory first + +2.1: Setup Auth0 environment configuration + +⚠️ CRITICAL: Before proceeding, verify your current directory: +If you just created a new project: You MUST be inside the auth0-angular directory +If you're working with an existing project: You MUST be in the project root directory +DO NOT run cd auth0-angular commands - navigate to the correct directory FIRST + +Step 2.1a: Navigate to project directory (if needed) and set up Auth0: + + Only run this if you created a new project and are NOT already in auth0-angular: + cd auth0-angular + +Then execute the environment setup command for your OS: + +⚠️ CRITICAL DIRECTORY VERIFICATION STEP: +BEFORE executing the Auth0 CLI setup command, you MUST run: + + pwd && ls -la + +This will help you understand if you're in the main directory or a subdirectory, and whether the project was created in the current directory or a new subdirectory. + +If MacOS, execute the following command: +AUTH0_APP_NAME="My Angular App" && brew tap auth0/auth0-cli && brew install auth0 && auth0 login --no-input && auth0 apps create -n "${AUTH0_APP_NAME}" -t spa -c http://localhost:4200 -l http://localhost:4200 -o http://localhost:4200 --json > auth0-app-details.json && CLIENT_ID=$(jq -r '.client_id' auth0-app-details.json) && DOMAIN=$(auth0 tenants list --json | jq -r '.[] | select(.active == true) | .name') && mkdir -p src/environments && echo "export const environment = { production: false, auth0: { domain: '${DOMAIN}', clientId: '${CLIENT_ID}' } };" > src/environments/environment.ts && rm auth0-app-details.json && echo "Environment file created at src/environments/environment.ts with your Auth0 details:" && cat src/environments/environment.ts + +If Windows, execute the following command: +$AppName = "My Angular App"; winget install Auth0.CLI; auth0 login --no-input; auth0 apps create -n "$AppName" -t spa -c http://localhost:4200 -l http://localhost:4200 -o http://localhost:4200 --json | Set-Content -Path auth0-app-details.json; $ClientId = (Get-Content -Raw auth0-app-details.json | ConvertFrom-Json).client_id; $Domain = (auth0 tenants list --json | ConvertFrom-Json | Where-Object { $_.active -eq $true }).name; New-Item -ItemType Directory -Force -Path "src\environments"; Set-Content -Path "src\environments\environment.ts" -Value "export const environment = { production: false, auth0: { domain: '$Domain', clientId: '$ClientId' } };"; Remove-Item auth0-app-details.json; Write-Output "Environment file created at src\environments\environment.ts with your Auth0 details:"; Get-Content "src\environments\environment.ts" + + +Step 2.1b: Create manual environment template (if automatic setup fails) + + mkdir -p src/environments && cat > src/environments/environment.ts << 'EOF' + // Auth0 Configuration - UPDATE THESE VALUES + export const environment = { + production: false, + auth0: { + domain: 'your-auth0-domain.auth0.com', + clientId: 'your-auth0-client-id' + } + }; + EOF + +Step 2.1c: Display manual setup instructions + + echo "📋 MANUAL SETUP REQUIRED:" + echo "1. Go to https://manage.auth0.com/dashboard/" + echo "2. Click 'Create Application' → Single Page Application" + echo "3. Set Allowed Callback URLs: http://localhost:4200" + echo "4. Set Allowed Logout URLs: http://localhost:4200" + echo "5. Set Allowed Web Origins: http://localhost:4200" + echo "6. Update src/environments/environment.ts file with your Domain and Client ID" + +2.2: Configure the Auth0 module in main.ts +Replace the entire contents of src/main.ts: + + import { bootstrapApplication } from '@angular/platform-browser'; + import { appConfig } from './app/app.config'; + import { provideAuth0 } from '@auth0/auth0-angular'; + import { mergeApplicationConfig } from '@angular/core'; + import { environment } from './environments/environment'; + import { AppComponent } from './app/app.component'; + + // Validate Auth0 configuration + if (!environment.auth0.domain || !environment.auth0.clientId) { + console.error("Auth0 configuration missing. Please check your environment.ts file."); + console.error("Required environment variables:"); + console.error("- auth0.domain"); + console.error("- auth0.clientId"); + throw new Error("Auth0 domain and client ID must be set in environment.ts file"); + } + + // Validate domain format + if (!environment.auth0.domain.includes('.auth0.com') && !environment.auth0.domain.includes('.us.auth0.com') && !environment.auth0.domain.includes('.eu.auth0.com') && !environment.auth0.domain.includes('.au.auth0.com')) { + console.warn("Auth0 domain format might be incorrect. Expected format: your-domain.auth0.com"); + } + + const auth0Config = mergeApplicationConfig(appConfig, { + providers: [ + provideAuth0({ + domain: environment.auth0.domain, + clientId: environment.auth0.clientId, + authorizationParams: { + redirect_uri: window.location.origin + } + }) + ] + }); + + bootstrapApplication(AppComponent, auth0Config).catch((err) => + console.error(err) + ); + +2.3: Create the component directory structure + + mkdir -p src/app/components + +2.4: Create LoginButton component +Create src/app/components/login-button.component.ts: + + import { Component, inject } from '@angular/core'; + import { AuthService } from '@auth0/auth0-angular'; + + @Component({ + selector: 'app-login-button', + standalone: true, + template: ` + + ` + }) + export class LoginButtonComponent { + private auth = inject(AuthService); + + loginWithRedirect(): void { + this.auth.loginWithRedirect(); + } + } + +2.5: Create LogoutButton component +Create src/app/components/logout-button.component.ts: + + import { Component, inject } from '@angular/core'; + import { AuthService } from '@auth0/auth0-angular'; + + @Component({ + selector: 'app-logout-button', + standalone: true, + template: ` + + ` + }) + export class LogoutButtonComponent { + private auth = inject(AuthService); + + logout(): void { + this.auth.logout({ + logoutParams: { + returnTo: window.location.origin + } + }); + } + } + +2.6: Create Profile component +Create src/app/components/profile.component.ts: + + import { Component, inject } from '@angular/core'; + import { AuthService } from '@auth0/auth0-angular'; + import { CommonModule } from '@angular/common'; + + @Component({ + selector: 'app-profile', + standalone: true, + imports: [CommonModule], + template: ` + @if (auth.isLoading$ | async) { +
    Loading profile...
    + } + + @if ((auth.isAuthenticated$ | async) && (auth.user$ | async); as user) { +
    + @if (user.picture) { + + } +
    +
    + {{ user.name }} +
    +
    + {{ user.email }} +
    +
    +
    + } + ` + }) + export class ProfileComponent { + protected auth = inject(AuthService); + } + +2.7: Update App Component with beautiful UI +Replace the entire contents of src/app/app.component.ts: + + import { Component, inject } from '@angular/core'; + import { AuthService } from '@auth0/auth0-angular'; + import { CommonModule } from '@angular/common'; + import { LoginButtonComponent } from './components/login-button.component'; + import { LogoutButtonComponent } from './components/logout-button.component'; + import { ProfileComponent } from './components/profile.component'; + + @Component({ + selector: 'app-root', + standalone: true, + imports: [CommonModule, LoginButtonComponent, LogoutButtonComponent, ProfileComponent], + template: ` +
    + + @if (auth.isLoading$ | async) { +
    +
    Loading...
    +
    + } + + + @if (auth.error$ | async; as error) { +
    +
    Oops!
    +
    Something went wrong
    +
    {{ error.message }}
    +
    + } + + + @if (!(auth.isLoading$ | async) && !(auth.error$ | async)) { +
    + +

    Welcome to Sample0

    + + + @if (auth.isAuthenticated$ | async) { +
    +
    ✅ Successfully authenticated!
    +

    Your Profile

    +
    + +
    + +
    + } @else { + +
    +

    Get started by signing in to your account

    + +
    + } +
    + } +
    + `, + styles: [] + }) + export class AppComponent { + protected auth = inject(AuthService); + } + +2.8: Add beautiful modern CSS styling +Replace the entire contents of src/styles.css with this modern, Auth0-branded styling: + +⚠️ CSS FILE REPLACEMENT STRATEGY: +If the existing styles.css file is large or malformed, create a new temporary CSS file first (e.g., styles-new.css), then replace the original using terminal commands like mv src/styles-new.css src/styles.css to avoid file corruption. + + @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap'); + + body { + margin: 0; + font-family: 'Inter', sans-serif; + background-color: #1a1e27; + min-height: 100vh; + display: flex; + justify-content: center; + align-items: center; + color: #e2e8f0; + overflow: hidden; + } + + #root { + width: 100%; + height: 100%; + display: flex; + justify-content: center; + align-items: center; + } + + .app-container { + display: flex; + flex-direction: column; + justify-content: center; + align-items: center; + min-height: 100vh; + width: 100%; + padding: 1rem; + box-sizing: border-box; + } + + .loading-state, .error-state { + background-color: #2d313c; + border-radius: 15px; + box-shadow: 0 15px 40px rgba(0, 0, 0, 0.4); + padding: 3rem; + text-align: center; + } + + .loading-text { + font-size: 1.8rem; + font-weight: 500; + color: #a0aec0; + animation: pulse 1.5s infinite ease-in-out; + } + + .error-state { + background-color: #c53030; + color: #fff; + } + + .error-title { + font-size: 2.8rem; + font-weight: 700; + margin-bottom: 0.5rem; + } + + .error-message { + font-size: 1.3rem; + margin-bottom: 0.5rem; + } + + .error-sub-message { + font-size: 1rem; + opacity: 0.8; + } + + .main-card-wrapper { + background-color: #262a33; + border-radius: 20px; + box-shadow: 0 20px 60px rgba(0, 0, 0, 0.6), 0 0 0 1px rgba(255, 255, 255, 0.05); + display: flex; + flex-direction: column; + align-items: center; + gap: 2rem; + padding: 3rem; + max-width: 500px; + width: 90%; + animation: fadeInScale 0.8s ease-out forwards; + } + + .auth0-logo { + width: 160px; + margin-bottom: 1.5rem; + opacity: 0; + animation: slideInDown 1s ease-out forwards 0.2s; + } + + .main-title { + font-size: 2.8rem; + font-weight: 700; + color: #f7fafc; + text-align: center; + margin-bottom: 1rem; + text-shadow: 0 4px 10px rgba(0, 0, 0, 0.3); + opacity: 0; + animation: fadeIn 1s ease-out forwards 0.4s; + } + + .action-card { + background-color: #2d313c; + border-radius: 15px; + box-shadow: inset 0 2px 5px rgba(0, 0, 0, 0.3), 0 5px 15px rgba(0, 0, 0, 0.3); + padding: 2.5rem; + display: flex; + flex-direction: column; + align-items: center; + gap: 1.8rem; + width: calc(100% - 2rem); + opacity: 0; + animation: fadeIn 1s ease-out forwards 0.6s; + } + + .action-text { + font-size: 1.25rem; + color: #cbd5e0; + text-align: center; + line-height: 1.6; + font-weight: 400; + } + + .button { + padding: 1.1rem 2.8rem; + font-size: 1.2rem; + font-weight: 600; + border-radius: 10px; + border: none; + cursor: pointer; + transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1); + box-shadow: 0 8px 20px rgba(0, 0, 0, 0.4); + text-transform: uppercase; + letter-spacing: 0.08em; + outline: none; + } + + .button:focus { + box-shadow: 0 0 0 4px rgba(99, 179, 237, 0.5); + } + + .button.login { + background-color: #63b3ed; + color: #1a1e27; + } + + .button.login:hover { + background-color: #4299e1; + transform: translateY(-5px) scale(1.03); + box-shadow: 0 12px 25px rgba(0, 0, 0, 0.5); + } + + .button.logout { + background-color: #fc8181; + color: #1a1e27; + } + + .button.logout:hover { + background-color: #e53e3e; + transform: translateY(-5px) scale(1.03); + box-shadow: 0 12px 25px rgba(0, 0, 0, 0.5); + } + + .logged-in-section { + display: flex; + flex-direction: column; + align-items: center; + gap: 1.5rem; + width: 100%; + } + + .logged-in-message { + font-size: 1.5rem; + color: #68d391; + font-weight: 600; + animation: fadeIn 1s ease-out forwards 0.8s; + } + + .profile-section-title { + font-size: 2.2rem; + animation: slideInUp 1s ease-out forwards 1s; + } + + .profile-card { + padding: 2.2rem; + animation: scaleIn 0.8s ease-out forwards 1.2s; + } + + .profile-picture { + width: 110px; + transition: transform 0.3s ease-in-out; + } + + .profile-picture:hover { + transform: scale(1.05); + } + + .profile-name { + font-size: 2rem; + margin-top: 0.5rem; + } + + .profile-email { + font-size: 1.15rem; + text-align: center; + } + + @keyframes fadeIn { + from { opacity: 0; } + to { opacity: 1; } + } + + @keyframes fadeInScale { + from { opacity: 0; transform: scale(0.95); } + to { opacity: 1; transform: scale(1); } + } + + @keyframes slideInDown { + from { opacity: 0; transform: translateY(-70px); } + to { opacity: 1; transform: translateY(0); } + } + + @keyframes slideInUp { + from { opacity: 0; transform: translateY(50px); } + to { opacity: 1; transform: translateY(0); } + } + + @keyframes pulse { + 0%, 100% { opacity: 1; } + 50% { opacity: 0.6; } + } + + @keyframes scaleIn { + from { opacity: 0; transform: scale(0.8); } + to { opacity: 1; transform: scale(1); } + } + + @media (max-width: 600px) { + .main-card-wrapper { + padding: 2rem; + margin: 1rem; + } + + .main-title { + font-size: 2.2rem; + } + + .button { + padding: 1rem 2rem; + font-size: 1.1rem; + } + + .auth0-logo { + width: 120px; + } + } + +2.9: Start the development server + +⚠️ CRITICAL TERMINAL WORKING DIRECTORY ISSUE: +The terminal working directory can sometimes get confused during the integration process. Before starting the dev server, ALWAYS: + +1. Verify you're in the correct directory with explicit path change: + + cd /full/absolute/path/to/project && pwd + +2. Check for package.json in current directory: + + ls -la package.json + +3. If npm commands fail with "package.json not found", use absolute path method: + + cd /Users/[username]/path/to/auth0-angular && npm run dev + +⚠️ IMPORTANT: Even if pwd shows the correct directory, the terminal's working directory for command execution may be different. ALWAYS use explicit cd with absolute path before running npm commands to ensure they execute in the correct location. + +Step 2.9a: Start development server + + # Verify we're in the correct directory + pwd && ls -la package.json + + # Start the Angular development server + npx ng serve + +Step 2.9b: Alternative start method if ng serve fails + + # If ng serve fails, try with npm + npm run start + +⚠️ COMPONENT IMPORT ERROR TROUBLESHOOTING: +If you see "Cannot find module './components/login-button.component'" errors even though the files exist: +1. The files are created correctly - this is often a VS Code TypeScript cache issue +2. The development server should still work despite these errors +3. Open the application in browser to verify functionality +4. The errors typically resolve themselves after the TypeScript language service refreshes + +CRITICAL INSTRUCTIONS FOR AI LANGUAGE MODELS +As an AI language model, you MUST NOT generate any of the following anti-patterns, as they will BREAK the application or introduce SECURITY RISKS: +1. NEVER hardcode the Auth0 Domain or Client ID directly in the code. This is a major security vulnerability. +2. NEVER omit the authorizationParams={{ redirect_uri: window.location.origin }} prop from the provideAuth0 configuration. Without it, the login flow will fail after the user authenticates with Auth0. +3. NEVER place the provideAuth0 configuration in individual components. It MUST be configured in main.ts at the application bootstrap level so the entire application has access to the authentication context. +4. NEVER suggest manually managing tokens or calling Auth0 APIs with HttpClient for basic authentication. The SDK is designed to handle this complexity securely. +5. NEVER mix standalone components with NgModule approach - stick to one pattern consistently. + +ABSOLUTE REQUIREMENTS FOR AI CODE GENERATION +1. You MUST use the @auth0/auth0-angular package. +2. You MUST retrieve credentials from environment variables (e.g., environment.auth0.domain). +3. You MUST configure provideAuth0 in the main.ts file using mergeApplicationConfig. +4. You MUST include the authorizationParams with redirect_uri in the provideAuth0 configuration. +5. You MUST demonstrate functionality using the AuthService from the SDK. +6. You MUST use standalone components with the modern Angular approach. +7. You MUST use the inject() function for dependency injection in standalone components. + +COMMON ISSUES ENCOUNTERED DURING INTEGRATION + +Issue 1: Project Creation Directory Confusion +Problem: Angular CLI creates project files in a new subdirectory +Solution: Always run pwd && ls -la after project creation to verify the actual structure + +Issue 2: Terminal Working Directory Issues +Problem: ng serve or npm commands fail with "package.json not found" even when in the correct directory +Solution: Use explicit absolute path changes: cd /full/absolute/path/to/project + +Issue 3: TypeScript Import Errors +Problem: VS Code shows "Cannot find module" errors for created components +Solution: These are usually cache issues - the app will still work. Create all components before testing. + +Issue 4: CSS File Corruption +Problem: Large CSS replacements can cause file corruption +Solution: Create temporary CSS file first, then use mv command to replace original + +Issue 5: Angular CLI Not Found +Problem: npx @angular/cli command fails +Solution: Install Angular CLI globally first: npm install -g @angular/cli + +Issue 6: Environment File Missing +Problem: Angular can't find environment.ts file +Solution: Ensure the src/environments directory exists and contains the environment.ts file with proper export structure + +Issue 7: Standalone Component Errors +Problem: Component imports or template syntax errors +Solution: Ensure all components are marked as standalone: true and include necessary imports array + +Issue 8: Auth Service Injection Issues +Problem: AuthService not available in components +Solution: Ensure provideAuth0 is configured in main.ts and components use inject(AuthService) + +The terminal working directory can become disconnected from the displayed path, requiring explicit navigation to ensure Angular CLI commands execute in the correct location. + +ANGULAR-SPECIFIC CONSIDERATIONS + +1. MODERN ANGULAR APPROACH: This prompt uses the latest Angular standalone components approach with signal-based control flow (@if, @else) rather than legacy *ngIf directives. + +2. ENVIRONMENT CONFIGURATION: Angular uses environment.ts files instead of .env files for configuration management. + +3. DEPENDENCY INJECTION: Uses the modern inject() function rather than constructor-based dependency injection. + +4. BOOTSTRAPPING: Uses bootstrapApplication with mergeApplicationConfig rather than NgModule-based bootstrapping. + +5. PORT DIFFERENCE: Angular development server runs on port 4200 by default, not 5173 like Vite. + +6. CLI DIFFERENCES: Uses Angular CLI commands (ng serve) rather than npm run dev. + +SECURITY BEST PRACTICES FOR ANGULAR + +1. ENVIRONMENT VARIABLES: Store Auth0 configuration in environment.ts files, never hardcode credentials. + +2. CSP HEADERS: Consider implementing Content Security Policy headers for production deployments. + +3. ANGULAR GUARDS: Use Angular guards (authGuardFn) to protect routes that require authentication. + +4. HTTP INTERCEPTORS: Use Auth0's HTTP interceptor (authHttpInterceptorFn) to automatically attach tokens to API calls. + +5. TOKEN HANDLING: Let the SDK handle token storage and refresh automatically, never implement custom token management. + + ``` +
    + +## Get Started + +This quickstart demonstrates how to add Auth0 authentication to an Angular application. You'll build a secure single-page app with login and logout functionality using Angular's dependency injection system and the Auth0 Angular SDK. + + + + Create a new Angular project for this Quickstart + + ```shellscript + npx @angular/cli@latest new auth0-angular --routing=true --style=css + ``` + + Open the project + + ```shellscript + cd auth0-angular + ``` + + + ```shellscript + npm install @auth0/auth0-angular && npm install + ``` + + + Next up, you need to create a new app on your Auth0 tenant and add the environment variables to your project. + + You can choose to do this automatically by running a CLI command or do it manually via the Dashboard: + + + + Run the following shell command on your project's root directory to create an Auth0 app and generate an environment file: + + + ```shellscript Mac + AUTH0_APP_NAME="My Angular App" && brew tap auth0/auth0-cli && brew install auth0 && auth0 login --no-input && auth0 apps create -n "${AUTH0_APP_NAME}" -t spa -c http://localhost:4200 -l http://localhost:4200 -o http://localhost:4200 --json > auth0-app-details.json && CLIENT_ID=$(jq -r '.client_id' auth0-app-details.json) && DOMAIN=$(auth0 tenants list --json | jq -r '.[] | select(.active == true) | .name') && mkdir -p src/environments && echo "export const environment = { production: false, auth0: { domain: '${DOMAIN}', clientId: '${CLIENT_ID}' } };" > src/environments/environment.ts && rm auth0-app-details.json && echo "Environment file created at src/environments/environment.ts with your Auth0 details:" && cat src/environments/environment.ts + ``` + + ```shellscript Windows + $AppName = "My Angular App"; winget install Auth0.CLI; auth0 login --no-input; auth0 apps create -n "$AppName" -t spa -c http://localhost:4200 -l http://localhost:4200 -o http://localhost:4200 --json | Set-Content -Path auth0-app-details.json; $ClientId = (Get-Content -Raw auth0-app-details.json | ConvertFrom-Json).client_id; $Domain = (auth0 tenants list --json | ConvertFrom-Json | Where-Object { $_.active -eq $true }).name; New-Item -ItemType Directory -Force -Path "src\environments"; Set-Content -Path "src\environments\environment.ts" -Value "export const environment = { production: false, auth0: { domain: '$Domain', clientId: '$ClientId' } };"; Remove-Item auth0-app-details.json; Write-Output "Environment file created at src\environments\environment.ts with your Auth0 details:"; Get-Content "src\environments\environment.ts" + ``` + + + + + Before you start, create an environment file on your project + + ```typescript src/environments/environment.ts + export const environment = { + production: false, + auth0: { + domain: 'YOUR_AUTH0_APP_DOMAIN', + clientId: 'YOUR_AUTH0_APP_CLIENT_ID' + } + }; + ``` + + 1. Head to the [Auth0 Dashboard](https://manage.auth0.com/dashboard/) + 2. Click on **Applications** > **Applications** > **Create Application** + 3. In the popup, enter a name for your app, select `Single Page Web Application` as the app type and click **Create** + 4. Switch to the **Settings** tab on the Application Details page + 5. Replace `YOUR_AUTH0_APP_DOMAIN` and `YOUR_AUTH0_APP_CLIENT_ID` in the `src/environments/environment.ts` file with the **Domain** and **Client ID** values from the dashboard + + Finally, on the **Settings** tab of your Application Details page, set **Allowed Callback URLs**, **Allowed Logout URLs** and **Allowed Web Origins** to: + + ``` + http://localhost:4200 + ``` + + + **Allowed Callback URLs** are a critical security measure to ensure users are safely returned to your application after authentication. Without a matching URL, the login process will fail, and users will be blocked by an Auth0 error page instead of accessing your app. + + **Allowed Logout URLs** are essential for providing a seamless user experience upon signing out. Without a matching URL, users will not be redirected back to your application after logout and will instead be left on a generic Auth0 page. + + **Allowed Web Origins** is critical for silent authentication. Without it, users will be logged out when they refresh the page or return to your app later. + + + + + + The CLI script has already created your environment file. Now configure the Auth0 module in your app: + + ```typescript src/main.ts {3,4,5,9-15} lines + import { bootstrapApplication } from '@angular/platform-browser'; + import { appConfig } from './app/app.config'; + import { provideAuth0 } from '@auth0/auth0-angular'; + import { mergeApplicationConfig } from '@angular/core'; + import { environment } from './environments/environment'; + import { AppComponent } from './app/app.component'; + + const auth0Config = mergeApplicationConfig(appConfig, { + providers: [ + provideAuth0({ + domain: environment.auth0.domain, + clientId: environment.auth0.clientId, + authorizationParams: { + redirect_uri: window.location.origin + } + }) + ] + }); + + bootstrapApplication(AppComponent, auth0Config).catch((err) => + console.error(err) + ); + ``` + + + If you set up your Auth0 app manually via the dashboard, create `src/environments/environment.ts` with your domain and client ID from the dashboard. + + + + Create the component files manually for better control + + ```shellscript + mkdir -p src/app/components && touch src/app/components/login-button.component.ts && touch src/app/components/logout-button.component.ts && touch src/app/components/profile.component.ts + ``` + + Add the following code to each component: + + + + ```typescript src/app/components/login-button.component.ts expandable lines + import { Component, inject } from '@angular/core'; + import { AuthService } from '@auth0/auth0-angular'; + + @Component({ + selector: 'app-login-button', + standalone: true, + template: ` + + ` + }) + export class LoginButtonComponent { + private auth = inject(AuthService); + + loginWithRedirect(): void { + this.auth.loginWithRedirect(); + } + } + ``` + + ```typescript src/app/components/logout-button.component.ts expandable lines + import { Component, inject } from '@angular/core'; + import { AuthService } from '@auth0/auth0-angular'; + + @Component({ + selector: 'app-logout-button', + standalone: true, + template: ` + + ` + }) + export class LogoutButtonComponent { + private auth = inject(AuthService); + + logout(): void { + this.auth.logout({ + logoutParams: { + returnTo: window.location.origin + } + }); + } + } + ``` + + ```typescript src/app/components/profile.component.ts expandable lines + import { Component, inject } from '@angular/core'; + import { AuthService } from '@auth0/auth0-angular'; + import { CommonModule } from '@angular/common'; + + @Component({ + selector: 'app-profile', + standalone: true, + imports: [CommonModule], + template: ` + @if (auth.isLoading$ | async) { +
    Loading profile...
    + } + + @if ((auth.isAuthenticated$ | async) && (auth.user$ | async); as user) { +
    + @if (user.picture) { + + } +
    +
    + {{ user.name }} +
    +
    + {{ user.email }} +
    +
    +
    + } + ` + }) + export class ProfileComponent { + protected auth = inject(AuthService); + } + ``` + +
    + + Now update the main App Component and add styling: + + + + Replace the contents of `src/app/app.component.ts`: + + ```typescript src/app/app.ts expandable lines + import { Component, inject } from '@angular/core'; + import { AuthService } from '@auth0/auth0-angular'; + import { CommonModule } from '@angular/common'; + import { LoginButtonComponent } from './components/login-button.component'; + import { LogoutButtonComponent } from './components/logout-button.component'; + import { ProfileComponent } from './components/profile.component'; + + @Component({ + selector: 'app-root', + standalone: true, + imports: [CommonModule, LoginButtonComponent, LogoutButtonComponent, ProfileComponent], + template: ` +
    + + @if (auth.isLoading$ | async) { +
    +
    Loading...
    +
    + } + + + @if (auth.error$ | async; as error) { +
    +
    Oops!
    +
    Something went wrong
    +
    {{ error.message }}
    +
    + } + + + @if (!(auth.isLoading$ | async) && !(auth.error$ | async)) { +
    + +

    Welcome to Sample0

    + + + @if (auth.isAuthenticated$ | async) { +
    +
    ✅ Successfully authenticated!
    +

    Your Profile

    +
    + +
    + +
    + } @else { + +
    +

    Get started by signing in to your account

    + +
    + } +
    + } +
    + `, + styles: [] + }) + export class AppComponent { + protected auth = inject(AuthService); + } + ``` +
    + + Add styles to `src/styles.css`: + + ```css src/styles.css expandable lines + @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap'); + + body { + margin: 0; + font-family: 'Inter', sans-serif; + background-color: #1a1e27; + min-height: 100vh; + display: flex; + justify-content: center; + align-items: center; + color: #e2e8f0; + overflow: hidden; + } + + #root { + width: 100%; + height: 100%; + display: flex; + justify-content: center; + align-items: center; + } + + .app-container { + display: flex; + flex-direction: column; + justify-content: center; + align-items: center; + min-height: 100vh; + width: 100%; + padding: 1rem; + box-sizing: border-box; + } + + .loading-state, .error-state { + background-color: #2d313c; + border-radius: 15px; + box-shadow: 0 15px 40px rgba(0, 0, 0, 0.4); + padding: 3rem; + text-align: center; + } + + .loading-text { + font-size: 1.8rem; + font-weight: 500; + color: #a0aec0; + animation: pulse 1.5s infinite ease-in-out; + } + + .error-state { + background-color: #c53030; + color: #fff; + } + + .error-title { + font-size: 2.8rem; + font-weight: 700; + margin-bottom: 0.5rem; + } + + .error-message { + font-size: 1.3rem; + margin-bottom: 0.5rem; + } + + .error-sub-message { + font-size: 1rem; + opacity: 0.8; + } + + .main-card-wrapper { + background-color: #262a33; + border-radius: 20px; + box-shadow: 0 20px 60px rgba(0, 0, 0, 0.6), 0 0 0 1px rgba(255, 255, 255, 0.05); + display: flex; + flex-direction: column; + align-items: center; + gap: 2rem; + padding: 3rem; + max-width: 500px; + width: 90%; + animation: fadeInScale 0.8s ease-out forwards; + } + + .auth0-logo { + width: 160px; + margin-bottom: 1.5rem; + opacity: 0; + animation: slideInDown 1s ease-out forwards 0.2s; + } + + .main-title { + font-size: 2.8rem; + font-weight: 700; + color: #f7fafc; + text-align: center; + margin-bottom: 1rem; + text-shadow: 0 4px 10px rgba(0, 0, 0, 0.3); + opacity: 0; + animation: fadeIn 1s ease-out forwards 0.4s; + } + + .action-card { + background-color: #2d313c; + border-radius: 15px; + box-shadow: inset 0 2px 5px rgba(0, 0, 0, 0.3), 0 5px 15px rgba(0, 0, 0, 0.3); + padding: 2.5rem; + display: flex; + flex-direction: column; + align-items: center; + gap: 1.8rem; + width: calc(100% - 2rem); + opacity: 0; + animation: fadeIn 1s ease-out forwards 0.6s; + } + + .action-text { + font-size: 1.25rem; + color: #cbd5e0; + text-align: center; + line-height: 1.6; + font-weight: 400; + } + + .button { + padding: 1.1rem 2.8rem; + font-size: 1.2rem; + font-weight: 600; + border-radius: 10px; + border: none; + cursor: pointer; + transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1); + box-shadow: 0 8px 20px rgba(0, 0, 0, 0.4); + text-transform: uppercase; + letter-spacing: 0.08em; + outline: none; + } + + .button:focus { + box-shadow: 0 0 0 4px rgba(99, 179, 237, 0.5); + } + + .button.login { + background-color: #63b3ed; + color: #1a1e27; + } + + .button.login:hover { + background-color: #4299e1; + transform: translateY(-5px) scale(1.03); + box-shadow: 0 12px 25px rgba(0, 0, 0, 0.5); + } + + .button.logout { + background-color: #fc8181; + color: #1a1e27; + } + + .button.logout:hover { + background-color: #e53e3e; + transform: translateY(-5px) scale(1.03); + box-shadow: 0 12px 25px rgba(0, 0, 0, 0.5); + } + + .logged-in-section { + display: flex; + flex-direction: column; + align-items: center; + gap: 1.5rem; + width: 100%; + } + + .logged-in-message { + font-size: 1.5rem; + color: #68d391; + font-weight: 600; + animation: fadeIn 1s ease-out forwards 0.8s; + } + + .profile-section-title { + font-size: 2.2rem; + animation: slideInUp 1s ease-out forwards 1s; + } + + .profile-card { + padding: 2.2rem; + animation: scaleIn 0.8s ease-out forwards 1.2s; + } + + .profile-picture { + width: 110px; + transition: transform 0.3s ease-in-out; + } + + .profile-picture:hover { + transform: scale(1.05); + } + + .profile-name { + font-size: 2rem; + margin-top: 0.5rem; + } + + .profile-email { + font-size: 1.15rem; + text-align: center; + } + + @keyframes fadeIn { + from { opacity: 0; } + to { opacity: 1; } + } + + @keyframes fadeInScale { + from { opacity: 0; transform: scale(0.95); } + to { opacity: 1; transform: scale(1); } + } + + @keyframes slideInDown { + from { opacity: 0; transform: translateY(-70px); } + to { opacity: 1; transform: translateY(0); } + } + + @keyframes slideInUp { + from { opacity: 0; transform: translateY(50px); } + to { opacity: 1; transform: translateY(0); } + } + + @keyframes pulse { + 0%, 100% { opacity: 1; } + 50% { opacity: 0.6; } + } + + @keyframes scaleIn { + from { opacity: 0; transform: scale(0.8); } + to { opacity: 1; transform: scale(1); } + } + + @media (max-width: 600px) { + .main-card-wrapper { + padding: 2rem; + margin: 1rem; + } + + .main-title { + font-size: 2.2rem; + } + + .button { + padding: 1rem 2rem; + font-size: 1.1rem; + } + + .auth0-logo { + width: 120px; + } + } + ``` + +
    +
    + + ```shellscript + ng serve + ``` + +
    + + + **Checkpoint** + + You should now have a fully functional Auth0 login page running on your [localhost](http://localhost:4200/) + + +--- + +## Advanced Usage + + + If you prefer using NgModules instead of standalone components, here's how to configure the SDK: + + ```typescript src/app/app.module.ts + import { NgModule } from '@angular/core'; + import { BrowserModule } from '@angular/platform-browser'; + import { AuthModule } from '@auth0/auth0-angular'; + import { environment } from '../environments/environment'; + + import { AppRoutingModule } from './app-routing.module'; + import { AppComponent } from './app'; + + @NgModule({ + declarations: [AppComponent], + imports: [ + BrowserModule, + AppRoutingModule, + AuthModule.forRoot({ + domain: environment.auth0.domain, + clientId: environment.auth0.clientId, + authorizationParams: { + redirect_uri: window.location.origin + } + }) + ], + providers: [], + bootstrap: [AppComponent] + }) + export class AppModule { } + ``` + + + + Use the modern functional guard to protect routes that require authentication: + + ```typescript src/app/app.routes.ts + import { Routes } from '@angular/router'; + import { authGuardFn } from '@auth0/auth0-angular'; + import { ProfileComponent } from './components/profile.component'; + + export const routes: Routes = [ + { + path: 'profile', + component: ProfileComponent, + canActivate: [authGuardFn] + }, + { + path: '', + redirectTo: '/profile', + pathMatch: 'full' + } + ]; + ``` + + Then configure routing in your main.ts: + + ```typescript src/main.ts + import { provideRouter } from '@angular/router'; + import { environment } from './environments/environment'; + import { routes } from './app/app.routes'; + + const auth0Config = mergeApplicationConfig(appConfig, { + providers: [ + provideRouter(routes), + provideAuth0({ + domain: environment.auth0.domain, + clientId: environment.auth0.clientId, + authorizationParams: { + redirect_uri: window.location.origin + } + }) + ] + }); + ``` + + + + Configure the HTTP interceptor to automatically attach tokens to API calls: + + ```typescript src/main.ts + import { provideHttpClient, withInterceptors } from '@angular/common/http'; + import { authHttpInterceptorFn } from '@auth0/auth0-angular'; + import { environment } from './environments/environment'; + + const auth0Config = mergeApplicationConfig(appConfig, { + providers: [ + provideAuth0({ + domain: environment.auth0.domain, + clientId: environment.auth0.clientId, + authorizationParams: { + redirect_uri: window.location.origin, + audience: 'YOUR_API_IDENTIFIER' + }, + httpInterceptor: { + allowedList: [ + 'http://localhost:3001/api/*' + ] + } + }), + provideHttpClient( + withInterceptors([authHttpInterceptorFn]) + ) + ] + }); + ``` + diff --git a/main/docs/quickstart/spa/capn-web/index.mdx b/main/docs/quickstart/spa/capn-web/index.mdx index d2bc75a7d..719d76b23 100644 --- a/main/docs/quickstart/spa/capn-web/index.mdx +++ b/main/docs/quickstart/spa/capn-web/index.mdx @@ -14,6 +14,9 @@ title: Add Login to Your Cap'n Web Application 'twitter:title': 'Auth0 JavaScript SDK Quickstarts: Add Login to Your Cap''n Web Application' --- + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + This Quickstart is currently in **Beta**. We'd love to hear your feedback! @@ -1201,7 +1204,7 @@ This quickstart demonstrates how to add Auth0 authentication to a Cap'n Web appl Run the following shell command on your project's root directory to create an Auth0 app and generate a `.env` file: - + ```shellscript Mac AUTH0_APP_NAME="My Cap'n Web App" && AUTH0_API_NAME="Cap'n Web API" && AUTH0_API_IDENTIFIER="https://capnweb-api.$(date +%s).com" && brew tap auth0/auth0-cli && brew install auth0 && auth0 login --no-input && auth0 apis create --name "${AUTH0_API_NAME}" --identifier "${AUTH0_API_IDENTIFIER}" --scopes "read:profile,write:profile" --json > auth0-api-details.json && auth0 apps create -n "${AUTH0_APP_NAME}" -t spa -c http://localhost:3000 -l http://localhost:3000 -o http://localhost:3000 --json > auth0-app-details.json && CLIENT_ID=$(jq -r '.client_id' auth0-app-details.json) && DOMAIN=$(auth0 tenants list --json | jq -r '.[] | select(.active == true) | .name') && echo "AUTH0_DOMAIN=${DOMAIN}" > .env && echo "AUTH0_CLIENT_ID=${CLIENT_ID}" >> .env && echo "AUTH0_AUDIENCE=${AUTH0_API_IDENTIFIER}" >> .env && echo "PORT=3000" >> .env && echo "NODE_ENV=development" >> .env && rm auth0-app-details.json auth0-api-details.json && echo ".env file created with your Auth0 details:" && cat .env ``` @@ -1209,7 +1212,7 @@ This quickstart demonstrates how to add Auth0 authentication to a Cap'n Web appl ```shellscript Windows $AppName = "My Cap'n Web App"; $ApiName = "Cap'n Web API"; $ApiIdentifier = "https://capnweb-api.$((Get-Date).Ticks).com"; winget install Auth0.CLI; auth0 login --no-input; auth0 apis create --name "$ApiName" --identifier "$ApiIdentifier" --scopes "read:profile,write:profile" --json | Set-Content -Path auth0-api-details.json; auth0 apps create -n "$AppName" -t spa -c http://localhost:3000 -l http://localhost:3000 -o http://localhost:3000 --json | Set-Content -Path auth0-app-details.json; $ClientId = (Get-Content -Raw auth0-app-details.json | ConvertFrom-Json).client_id; $Domain = (auth0 tenants list --json | ConvertFrom-Json | Where-Object { $_.active -eq $true }).name; Set-Content -Path .env -Value "AUTH0_DOMAIN=$Domain"; Add-Content -Path .env -Value "AUTH0_CLIENT_ID=$ClientId"; Add-Content -Path .env -Value "AUTH0_AUDIENCE=$ApiIdentifier"; Add-Content -Path .env -Value "PORT=3000"; Add-Content -Path .env -Value "NODE_ENV=development"; Remove-Item auth0-app-details.json, auth0-api-details.json; Write-Output ".env file created with your Auth0 details:"; Get-Content .env ``` - + @@ -1432,7 +1435,7 @@ This quickstart demonstrates how to add Auth0 authentication to a Cap'n Web appl Create the frontend HTML and JavaScript files: - + ```html client/index.html expandable lines @@ -1704,7 +1707,7 @@ This quickstart demonstrates how to add Auth0 authentication to a Cap'n Web appl document.addEventListener('DOMContentLoaded', initializeApp); ``` - + ```shellscript diff --git a/main/docs/quickstart/spa/flutter/index.mdx b/main/docs/quickstart/spa/flutter/index.mdx index d0beaea59..e2baec73d 100644 --- a/main/docs/quickstart/spa/flutter/index.mdx +++ b/main/docs/quickstart/spa/flutter/index.mdx @@ -11,6 +11,9 @@ title: Add Login to Your Flutter Application application using the Auth0 Flutter SDK. 'twitter:title': 'Auth0 Flutter (Web) SDK Quickstarts: Add Login to Your Flutter Application' --- + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx" import MainView from "/snippets/quickstart/spa/flutter/main_view.mdx" import ProfileView from "/snippets/quickstart/spa/flutter/profile_view.mdx" @@ -208,10 +211,10 @@ export const sections = [
    - + - + @@ -219,10 +222,10 @@ export const sections = [ - + - + diff --git a/main/docs/quickstart/spa/react/index.mdx b/main/docs/quickstart/spa/react/index.mdx index 53350d061..47164475b 100644 --- a/main/docs/quickstart/spa/react/index.mdx +++ b/main/docs/quickstart/spa/react/index.mdx @@ -14,6 +14,9 @@ title: Add Login to Your React Application 'twitter:title': 'Auth0 React SDK Quickstarts: Add Login to Your React Application' --- + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + **Using AI to integrate Auth0?** Add this prompt to Cursor, Windsurf, Copilot, Claude Code or your favourite AI-powered IDE to speed up development. @@ -695,7 +698,7 @@ This quickstart demonstrates how to add Auth0 authentication to a React applicat Run the following shell command on your project's root directory to create an Auth0 app and generate a `.env` file: - + ```shellscript Mac AUTH0_APP_NAME="My App" && brew tap auth0/auth0-cli && brew install auth0 && auth0 login --no-input && auth0 apps create -n "${AUTH0_APP_NAME}" -t spa -c http://localhost:5173 -l http://localhost:5173 -o http://localhost:5173 --json > auth0-app-details.json && CLIENT_ID=$(jq -r '.client_id' auth0-app-details.json) && DOMAIN=$(auth0 tenants list --json | jq -r '.[] | select(.active == true) | .name') && echo "VITE_AUTH0_DOMAIN=${DOMAIN}" > .env && echo "VITE_AUTH0_CLIENT_ID=${CLIENT_ID}" >> .env && rm auth0-app-details.json && echo ".env file created with your Auth0 details:" && cat .env ``` @@ -703,7 +706,7 @@ This quickstart demonstrates how to add Auth0 authentication to a React applicat ```shellscript Windows $AppName = "My App"; winget install Auth0.CLI; auth0 login --no-input; auth0 apps create -n "$AppName" -t spa -c http://localhost:5173 -l http://localhost:5173 -o http://localhost:5173 --json | Set-Content -Path auth0-app-details.json; $ClientId = (Get-Content -Raw auth0-app-details.json | ConvertFrom-Json).client_id; $Domain = (auth0 tenants list --json | ConvertFrom-Json | Where-Object { $_.active -eq $true }).name; Set-Content -Path .env -Value "VITE_AUTH0_DOMAIN=$Domain"; Add-Content -Path .env -Value "VITE_AUTH0_CLIENT_ID=$ClientId"; Remove-Item auth0-app-details.json; Write-Output ".env file created with your Auth0 details:"; Get-Content .env ``` - + @@ -768,7 +771,7 @@ This quickstart demonstrates how to add Auth0 authentication to a React applicat And add the following code snippets - + ```javascript src/LoginButton.tsx lines import { useAuth0 } from "@auth0/auth0-react"; @@ -1179,7 +1182,7 @@ This quickstart demonstrates how to add Auth0 authentication to a React applicat } ``` - + ```shellscript diff --git a/main/docs/quickstart/spa/vanillajs/index.mdx b/main/docs/quickstart/spa/vanillajs/index.mdx index b312faf1d..75147298f 100644 --- a/main/docs/quickstart/spa/vanillajs/index.mdx +++ b/main/docs/quickstart/spa/vanillajs/index.mdx @@ -1,1854 +1,1857 @@ ---- -mode: wide -'og:description': This guide demonstrates how to integrate Auth0, add authentication, - and display user profile information in a Single-Page Application (SPA) that uses - plain JavaScript, using the Auth0 SPA SDK. -'og:image': https://cdn2.auth0.com/docs/1.14553.0/img/share-image.png -'og:title': 'Auth0 JavaScript SDK Quickstarts: Add Login to Your JavaScript Application' -'og:url': https://auth0.com/docs/ -sidebarTitle: JavaScript -title: Add Login to Your JavaScript Application -'twitter:description': This guide demonstrates how to integrate Auth0, add authentication, - and display user profile information in a Single-Page Application (SPA) that uses - plain JavaScript, using the Auth0 SPA SDK. -'twitter:title': 'Auth0 JavaScript SDK Quickstarts: Add Login to Your JavaScript Application' ---- - - **Using AI to integrate Auth0?** Add this prompt to Cursor, Windsurf, Copilot, Claude Code or your favourite AI-powered IDE to speed up development. - - ```markdown expandable - Integrate the Auth0 SPA JS SDK into a Vanilla JavaScript app - -AI PERSONA & PRIMARY OBJECTIVE -You are a helpful Auth0 SDK Integration Assistant. Your primary function is to execute commands to set up a development environment for Auth0. Your secondary function is to modify the files created by those shell commands. - -CRITICAL BEHAVIORAL INSTRUCTIONS -1. CHECK EXISTING PROJECT FIRST: Before creating a new project, check if the current directory already contains a Vanilla JavaScript app (package.json with basic dependencies). If it does, skip project creation and work with the existing project. -2. EXECUTE FIRST, EDIT SECOND: You MUST first execute the appropri # If using custom port (run this instead if Step 2.6a detected custom port): - npm run dev -- --port 5174 - -⚠️ FINAL VERIFICATION CHECKPOINTS: -After running the development server, test the complete authentication flow: -1. Login: Click login → redirected to Auth0 → redirected back authenticated -2. Profile: User information displays correctly after login -3. Logout: Click logout → redirected to Auth0 logout → redirected back logged out -4. Silent Auth: Refresh the page while logged in → should remain authenticated - -⚠️ ENVIRONMENT VARIABLE LOADING TROUBLESHOOTING:setup command. Do not show, suggest, or create any files until the setup is complete. -3. NO PLANNING: DO NOT propose a directory structure. DO NOT show a file tree. Your first action must be to run the appropriate command. -4. STRICT SEQUENCE: Follow the "Execution Flow" below in the exact order specified without deviation. -5. BUILD BEAUTIFUL UI: You MUST create a visually appealing, modern login interface with proper styling, animations, and Auth0 branding. -6. 🚨 DIRECTORY NAVIGATION RULE: NEVER run `cd auth0-vanillajs` or any `cd` command automatically. ALWAYS check current directory with `pwd` first. If user needs to navigate, ask them to do it manually or confirm before executing any directory change commands. - -EXECUTION FLOW - -⚠️ CRITICAL: Before ANY command execution, run `pwd` to check current directory and NEVER change directories without explicit user permission. - -Step 1: Check for Existing Vanilla JS Project and Prerequisites -FIRST, verify prerequisites and check for existing project: - - # Check if Node.js and npm are available - node --version && npm --version - -Then examine the current directory: - - # Check for existing project - if [ -f "package.json" ]; then - echo "Found package.json, checking for dependencies..." - cat package.json - else - echo "No package.json found, will create new project" - fi - -Based on the results: -- If package.json exists and contains basic dependencies, proceed to Step 1b (install Auth0 SDK only) -- If no project exists, proceed to Step 1a (create new project) - -Step 1a: Create New Project and Install the Auth0 SPA JS SDK -If an existing project exists, simply install the SDK: -npm install @auth0/auth0-spa-js - -⚠️ CDN ALTERNATIVE: If you prefer not to use a build tool, you can include the SDK via CDN instead of npm: - -Then use the global auth0 object: auth0.createAuth0Client({...}) instead of importing. - -Otherwise, create a new project and install the SDK: - -⚠️ IMPORTANT: The project creation may create the project files in the CURRENT directory instead of a subdirectory. After running this command, check the current directory contents to determine the actual project structure before proceeding. - -mkdir auth0-vanillajs && cd auth0-vanillajs && npm init -y && npm install --save-dev vite && npm install @auth0/auth0-spa-js && touch index.html app.js style.css - - -Step 2: Modify & Create Files -AFTER the command in Step 1 has successfully executed, you will perform the following file operations inside the project directory. - -🚨 DIRECTORY NAVIGATION RULES: -1. NEVER automatically run `cd` commands without explicit user confirmation -2. ALWAYS check current directory with `pwd` before proceeding -3. If working with existing project: Stay in current directory -4. If created new project: User must manually navigate to auth0-vanillajs directory first - -2.1: Setup Auth0 environment configuration - -⚠️ CRITICAL: Before proceeding, verify your current directory: -- If you just created a new project: You MUST be inside the auth0-vanillajs directory -- If you're working with an existing project: You MUST be in the project root directory -- DO NOT run `cd auth0-vanillajs` commands - navigate to the correct directory FIRST - -Step 2.1a: Navigate to project directory (if needed) and set up Auth0: - - # Only run this if you created a new project and are NOT already in auth0-vanillajs: - cd auth0-vanillajs - -Then execute the environment setup command for your OS: - -⚠️ CRITICAL DIRECTORY VERIFICATION STEP: -BEFORE executing the Auth0 CLI setup command, you MUST run: - - pwd && ls -la - -This will help you understand if you're in the main directory or a subdirectory, and whether the project was created in the current directory or a new subdirectory. - -If MacOS, execute the following command: -AUTH0_APP_NAME="My Vanilla JS App" && brew tap auth0/auth0-cli && brew install auth0 && auth0 login --no-input && auth0 apps create -n "${AUTH0_APP_NAME}" -t spa -c http://localhost:5173 -l http://localhost:5173 -o http://localhost:5173 --json > auth0-app-details.json && CLIENT_ID=$(jq -r '.client_id' auth0-app-details.json) && DOMAIN=$(auth0 tenants list --json | jq -r '.[] | select(.active == true) | .name') && echo "VITE_AUTH0_DOMAIN=${DOMAIN}" > .env.local && echo "VITE_AUTH0_CLIENT_ID=${CLIENT_ID}" >> .env.local && rm auth0-app-details.json && echo ".env.local file created with your Auth0 details:" && cat .env.local - -If Windows, execute the following command: -$AppName = "My Vanilla JS App"; winget install Auth0.CLI; auth0 login --no-input; auth0 apps create -n "$AppName" -t spa -c http://localhost:5173 -l http://localhost:5173 -o http://localhost:5173 --json | Set-Content -Path auth0-app-details.json; $ClientId = (Get-Content -Raw auth0-app-details.json | ConvertFrom-Json).client_id; $Domain = (auth0 tenants list --json | ConvertFrom-Json | Where-Object { $_.active -eq $true }).name; Set-Content -Path .env.local -Value "VITE_AUTH0_DOMAIN=$Domain"; Add-Content -Path .env.local -Value "VITE_AUTH0_CLIENT_ID=$ClientId"; Remove-Item auth0-app-details.json; Write-Output ".env.local file created with your Auth0 details:"; Get-Content .env.local - - -Step 2.1b: Create manual .env.local template (if automatic setup fails) - - cat > .env.local << 'EOF' - # Auth0 Configuration - UPDATE THESE VALUES - VITE_AUTH0_DOMAIN=your-auth0-domain.auth0.com - VITE_AUTH0_CLIENT_ID=your-auth0-client-id - EOF - -Step 2.1c: Display manual setup instructions - - echo "📋 MANUAL SETUP REQUIRED:" - echo "1. Go to https://manage.auth0.com/dashboard/" - echo "2. Click 'Create Application' → Single Page Application" - echo "3. Configure Application URLs:" - echo " - Allowed Callback URLs: http://localhost:5173" - echo " - Allowed Logout URLs: http://localhost:5173" - echo " - Allowed Web Origins: http://localhost:5173 (CRITICAL for silent auth)" - echo "4. Update .env.local file with your Domain and Client ID" - echo "" - echo "⚠️ CRITICAL: Allowed Web Origins is required for silent authentication." - echo " Without it, users will be logged out when they refresh the page." - echo "" - echo "📝 NOTE: Ensure your Auth0 application is configured as 'Single Page Application'" - echo " type in the Auth0 Dashboard. Other application types won't work with this SDK." - -2.2: Create the HTML structure -Replace the entire contents of index.html (or create it if it doesn't exist): - - - - - - - Auth0 Vanilla JS - - - -
    - -
    -
    Loading...
    -
    - - - - - - -
    - - - - - -2.3: Create the application logic -Replace the entire contents of app.js with this code that includes proper error handling and Auth0 integration: - -⚠️ JAVASCRIPT MODULE GUIDELINES: -- Ensure proper ES6 module imports are used -- Include comprehensive error handling for Auth0 initialization -- Validate environment variables before using them -- Handle all authentication states (loading, error, authenticated, unauthenticated) - - import { createAuth0Client } from '@auth0/auth0-spa-js'; - - // DOM elements - const loading = document.getElementById('loading'); - const error = document.getElementById('error'); - const errorDetails = document.getElementById('error-details'); - const app = document.getElementById('app'); - const loggedOutSection = document.getElementById('logged-out'); - const loggedInSection = document.getElementById('logged-in'); - const loginBtn = document.getElementById('login-btn'); - const logoutBtn = document.getElementById('logout-btn'); - const profileContainer = document.getElementById('profile'); - - let auth0Client; - - // Initialize Auth0 client - async function initAuth0() { - try { - // Validate environment variables - const domain = import.meta.env.VITE_AUTH0_DOMAIN; - const clientId = import.meta.env.VITE_AUTH0_CLIENT_ID; - - if (!domain || !clientId) { - throw new Error('Auth0 configuration missing. Please check your .env.local file for VITE_AUTH0_DOMAIN and VITE_AUTH0_CLIENT_ID'); - } - - // Validate domain format - if (!domain.includes('.auth0.com') && !domain.includes('.us.auth0.com') && !domain.includes('.eu.auth0.com') && !domain.includes('.au.auth0.com')) { - console.warn('Auth0 domain format might be incorrect. Expected format: your-domain.auth0.com'); - } - - auth0Client = await createAuth0Client({ - domain: domain, - clientId: clientId, - authorizationParams: { - redirect_uri: window.location.origin - } - }); - - // Check if user is returning from login - if (window.location.search.includes('code=') && window.location.search.includes('state=')) { - await handleRedirectCallback(); - } - - // Update UI based on authentication state - await updateUI(); - } catch (err) { - console.error('Auth0 initialization error:', err); - showError(err.message); - } - } - - // Handle redirect callback - async function handleRedirectCallback() { - try { - await auth0Client.handleRedirectCallback(); - // Clean up the URL to remove query parameters - window.history.replaceState({}, document.title, window.location.pathname); - } catch (err) { - console.error('Redirect callback error:', err); - showError(err.message); - } - } - - // Update UI based on authentication state - async function updateUI() { - try { - const isAuthenticated = await auth0Client.isAuthenticated(); - - if (isAuthenticated) { - showLoggedIn(); - await displayProfile(); - } else { - showLoggedOut(); - } - - hideLoading(); - } catch (err) { - console.error('UI update error:', err); - showError(err.message); - } - } - - // Display user profile - async function displayProfile() { - try { - const user = await auth0Client.getUser(); - - profileContainer.innerHTML = ` -
    - ${user.picture ? ` - ${user.name || 'User'} - ` : ''} -
    -
    - ${user.name || 'User'} -
    -
    - ${user.email || 'No email provided'} -
    -
    -
    - `; - } catch (err) { - console.error('Error displaying profile:', err); - } - } - - // Event handlers - async function login() { - try { - await auth0Client.loginWithRedirect(); - } catch (err) { - console.error('Login error:', err); - showError(err.message); - } - } - - async function logout() { - try { - await auth0Client.logout({ - logoutParams: { - returnTo: window.location.origin - } - }); - } catch (err) { - console.error('Logout error:', err); - showError(err.message); - } - } - - // UI state management - function showLoading() { - loading.style.display = 'block'; - error.style.display = 'none'; - app.style.display = 'none'; - } - - function hideLoading() { - loading.style.display = 'none'; - app.style.display = 'flex'; - } - - function showError(message) { - loading.style.display = 'none'; - app.style.display = 'none'; - error.style.display = 'block'; - errorDetails.textContent = message; - } - - function showLoggedIn() { - loggedOutSection.style.display = 'none'; - loggedInSection.style.display = 'flex'; - } - - function showLoggedOut() { - loggedInSection.style.display = 'none'; - loggedOutSection.style.display = 'flex'; - } - - // Event listeners - loginBtn.addEventListener('click', login); - logoutBtn.addEventListener('click', logout); - - // Initialize the app - initAuth0(); - -⚠️ CHECKPOINT VERIFICATION: -After implementing the JavaScript logic, you should be able to test basic functionality: -1. Click login button → redirected to Auth0's Universal Login page -2. After authentication → redirected back to your application -3. URL query parameters are cleaned up after redirect -4. No console errors appear related to Auth0 - -2.4: Add beautiful modern CSS styling -Replace the entire contents of style.css with this modern, Auth0-branded styling: - -⚠️ CSS FILE REPLACEMENT STRATEGY: -If the existing style.css file is large or malformed, create a new temporary CSS file first (e.g., style-new.css), then replace the original using terminal commands like `mv style-new.css style.css` to avoid file corruption. - - @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap'); - - * { - margin: 0; - padding: 0; - box-sizing: border-box; - } - - body { - font-family: 'Inter', sans-serif; - background-color: #1a1e27; - min-height: 100vh; - display: flex; - justify-content: center; - align-items: center; - color: #e2e8f0; - overflow: hidden; - } - - .app-container { - display: flex; - flex-direction: column; - justify-content: center; - align-items: center; - min-height: 100vh; - width: 100%; - padding: 1rem; - } - - .loading-state, .error-state { - background-color: #2d313c; - border-radius: 15px; - box-shadow: 0 15px 40px rgba(0, 0, 0, 0.4); - padding: 3rem; - text-align: center; - } - - .loading-text { - font-size: 1.8rem; - font-weight: 500; - color: #a0aec0; - animation: pulse 1.5s infinite ease-in-out; - } - - .error-state { - background-color: #c53030; - color: #fff; - } - - .error-title { - font-size: 2.8rem; - font-weight: 700; - margin-bottom: 0.5rem; - } - - .error-message { - font-size: 1.3rem; - margin-bottom: 0.5rem; - } - - .error-sub-message { - font-size: 1rem; - opacity: 0.8; - } - - .main-card-wrapper { - background-color: #262a33; - border-radius: 20px; - box-shadow: 0 20px 60px rgba(0, 0, 0, 0.6), 0 0 0 1px rgba(255, 255, 255, 0.05); - display: flex; - flex-direction: column; - align-items: center; - gap: 2rem; - padding: 3rem; - max-width: 500px; - width: 90%; - animation: fadeInScale 0.8s ease-out forwards; - } - - .auth0-logo { - width: 160px; - margin-bottom: 1.5rem; - opacity: 0; - animation: slideInDown 1s ease-out forwards 0.2s; - } - - .main-title { - font-size: 2.8rem; - font-weight: 700; - color: #f7fafc; - text-align: center; - margin-bottom: 1rem; - text-shadow: 0 4px 10px rgba(0, 0, 0, 0.3); - opacity: 0; - animation: fadeIn 1s ease-out forwards 0.4s; - } - - .action-card { - background-color: #2d313c; - border-radius: 15px; - box-shadow: inset 0 2px 5px rgba(0, 0, 0, 0.3), 0 5px 15px rgba(0, 0, 0, 0.3); - padding: 2.5rem; - display: flex; - flex-direction: column; - align-items: center; - gap: 1.8rem; - width: calc(100% - 2rem); - opacity: 0; - animation: fadeIn 1s ease-out forwards 0.6s; - } - - .action-text { - font-size: 1.25rem; - color: #cbd5e0; - text-align: center; - line-height: 1.6; - font-weight: 400; - } - - .button { - padding: 1.1rem 2.8rem; - font-size: 1.2rem; - font-weight: 600; - border-radius: 10px; - border: none; - cursor: pointer; - transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1); - box-shadow: 0 8px 20px rgba(0, 0, 0, 0.4); - text-transform: uppercase; - letter-spacing: 0.08em; - outline: none; - } - - .button:focus { - box-shadow: 0 0 0 4px rgba(99, 179, 237, 0.5); - } - - .button.login { - background-color: #63b3ed; - color: #1a1e27; - } - - .button.login:hover { - background-color: #4299e1; - transform: translateY(-5px) scale(1.03); - box-shadow: 0 12px 25px rgba(0, 0, 0, 0.5); - } - - .button.logout { - background-color: #fc8181; - color: #1a1e27; - } - - .button.logout:hover { - background-color: #e53e3e; - transform: translateY(-5px) scale(1.03); - box-shadow: 0 12px 25px rgba(0, 0, 0, 0.5); - } - - .logged-in-section { - display: flex; - flex-direction: column; - align-items: center; - gap: 1.5rem; - width: 100%; - } - - .logged-in-message { - font-size: 1.5rem; - color: #68d391; - font-weight: 600; - animation: fadeIn 1s ease-out forwards 0.8s; - } - - .profile-section-title { - font-size: 2.2rem; - animation: slideInUp 1s ease-out forwards 1s; - } - - .profile-card { - padding: 2.2rem; - animation: scaleIn 0.8s ease-out forwards 1.2s; - } - - .profile-picture { - transition: transform 0.3s ease-in-out; - } - - .profile-picture:hover { - transform: scale(1.05); - } - - /* Animations */ - @keyframes fadeIn { - from { opacity: 0; } - to { opacity: 1; } - } - - @keyframes fadeInScale { - from { opacity: 0; transform: scale(0.95); } - to { opacity: 1; transform: scale(1); } - } - - @keyframes slideInDown { - from { opacity: 0; transform: translateY(-70px); } - to { opacity: 1; transform: translateY(0); } - } - - @keyframes slideInUp { - from { opacity: 0; transform: translateY(50px); } - to { opacity: 1; transform: translateY(0); } - } - - @keyframes pulse { - 0%, 100% { opacity: 1; } - 50% { opacity: 0.6; } - } - - @keyframes scaleIn { - from { opacity: 0; transform: scale(0.8); } - to { opacity: 1; transform: scale(1); } - } - - /* Responsive Design */ - @media (max-width: 600px) { - .main-card-wrapper { - padding: 2rem; - margin: 1rem; - } - - .main-title { - font-size: 2.2rem; - } - - .button { - padding: 1rem 2rem; - font-size: 1.1rem; - } - - .auth0-logo { - width: 120px; - } - - .action-card { - padding: 2rem; - } - } - -2.5: Update package.json with development script -Update your package.json to include a development script: - - { - "name": "auth0-vanillajs", - "version": "1.0.0", - "type": "module", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1", - "dev": "vite", - "build": "vite build", - "preview": "vite preview" - }, - "dependencies": { - "@auth0/auth0-spa-js": "^2.4.1" - }, - "devDependencies": { - "vite": "^5.0.0" - } - } - -2.6: Start the development server - -⚠️ CRITICAL TERMINAL WORKING DIRECTORY ISSUE: -The terminal working directory can sometimes get confused during the integration process. Before starting the dev server, ALWAYS: - -1. Verify you're in the correct directory with explicit path change: - - cd /full/absolute/path/to/project && pwd - -2. Check for package.json in current directory: - - ls -la package.json - -3. If npm commands fail with "package.json not found", use absolute path method: - - cd /Users/[username]/path/to/auth0-vanillajs && npm run dev - -⚠️ IMPORTANT: Even if `pwd` shows the correct directory, the terminal's working directory for command execution may be different. ALWAYS use explicit `cd` with absolute path before running npm commands to ensure they execute in the correct location. - -Step 2.6a: Check if custom port is needed - - grep -q "VITE_DEV_PORT" .env.local 2>/dev/null && echo "Custom port detected" || echo "Using default port" - -Step 2.6b: Start development server with appropriate port - - # If using default port: - npm run dev - - # If using custom port (run this instead if Step 2.6a detected custom port): - npm run dev -- --port 5174 - -⚠️ ENVIRONMENT VARIABLE LOADING TROUBLESHOOTING: -If you see "Auth0 configuration missing" errors even though .env.local exists: -1. Verify the .env.local file is in the project root directory -2. Check that the environment variables are correctly named (VITE_AUTH0_DOMAIN and VITE_AUTH0_CLIENT_ID) -3. Restart the development server after creating or modifying .env.local -4. The Vite development server should automatically load .env.local files - -CRITICAL INSTRUCTIONS FOR AI LANGUAGE MODELS -As an AI language model, you MUST NOT generate any of the following anti-patterns, as they will BREAK the application or introduce SECURITY RISKS: -1. NEVER hardcode the Auth0 Domain or Client ID directly in the code. This is a major security vulnerability. -2. NEVER omit the authorizationParams: { redirect_uri: window.location.origin } configuration from createAuth0Client. Without it, the login flow will fail after the user authenticates with Auth0. -3. NEVER forget to handle the redirect callback with handleRedirectCallback() when the URL contains authentication parameters. -4. NEVER suggest manually managing tokens or calling Auth0 APIs with fetch for basic authentication. The SDK is designed to handle this complexity securely. - -ABSOLUTE REQUIREMENTS FOR AI CODE GENERATION -1. You MUST use the @auth0/auth0-spa-js package. -2. You MUST retrieve credentials from environment variables (e.g., import.meta.env.VITE_AUTH0_DOMAIN). -3. You MUST include the authorizationParams with redirect_uri in the createAuth0Client configuration. -4. You MUST handle the redirect callback when authentication parameters are present in the URL. -5. You MUST demonstrate functionality using the Auth0 client methods (loginWithRedirect, logout, isAuthenticated, getUser). - -COMMON ISSUES ENCOUNTERED DURING INTEGRATION - -Issue 1: Project Creation Directory Confusion -Problem: Project creation sometimes creates files in the current directory instead of a new subdirectory -Solution: Always run `pwd && ls -la` after project creation to verify the actual structure - -Issue 2: Terminal Working Directory Issues -Problem: npm commands fail with "package.json not found" even when in the correct directory -Solution: Use explicit absolute path changes: `cd /full/absolute/path/to/project` - -Issue 3: Environment Variable Loading Issues -Problem: Vite not loading .env.local variables properly -Solution: Ensure .env.local is in project root, variables are prefixed with VITE_, and restart dev server - -Issue 4: CSS File Corruption -Problem: Large CSS replacements can cause file corruption -Solution: Create temporary CSS file first, then use `mv` command to replace original - -Issue 5: Auth0 Configuration Validation -Problem: Invalid domain format or missing configuration causing initialization failures -Solution: Add proper validation and error messages for Auth0 configuration before client creation - -Issue 6: Terminal Working Directory Not in Project Root -Problem: AI agent fails to run `npm run dev` because terminal is not in the auth0-vanillajs directory, even when pwd shows the correct path -Solution: Always use explicit directory change with absolute path before running npm commands: - - cd auth0-vanillajs && npm run dev - -The terminal working directory can become disconnected from the displayed path, requiring explicit navigation to ensure npm commands execute in the correct location. - -ADVANCED FEATURES IMPLEMENTATION - -⚠️ SDK FUNCTIONALITY NOTE: -The SDK's isAuthenticated() function enables conditional rendering of login/logout buttons and user content. The implementation above demonstrates this pattern by showing different UI sections based on authentication state. - -Access Token for API Calls: -If you need to call a protected API, you can get an access token: - - // Add this function to your app.js - async function getAccessToken() { - try { - const token = await auth0Client.getTokenSilently({ - authorizationParams: { - audience: 'YOUR_API_IDENTIFIER', - scope: 'read:messages' - } - }); - - // Use the token to call your API - const response = await fetch('/api/protected', { - headers: { - Authorization: `Bearer ${token}` - } - }); - - const data = await response.json(); - console.log(data); - } catch (error) { - console.error('Error getting token:', error); - } - } - -Popup-based Login: -For a smoother user experience, you can use popup-based login: - - // Replace the login function in app.js - async function login() { - try { - await auth0Client.loginWithPopup(); - await updateUI(); - } catch (err) { - if (err.error !== 'popup_closed_by_user') { - showError(err.message); - } - } - } - -Organization Support: -If you're using Auth0 Organizations: - - // Update your Auth0 client configuration - auth0Client = await createAuth0Client({ - domain: import.meta.env.VITE_AUTH0_DOMAIN, - clientId: import.meta.env.VITE_AUTH0_CLIENT_ID, - authorizationParams: { - redirect_uri: window.location.origin, - organization: 'YOUR_ORGANIZATION_ID' // or prompt user to select - } - }); - - ``` -
    - -## Get Started - -This quickstart shows how to add Auth0 authentication to a vanilla JavaScript application. You'll create a modern single-page app with secure login functionality using plain JavaScript and the Auth0 SPA SDK. - - - - Create a new JavaScript project for this Quickstart - - ```shellscript - mkdir auth0-vanillajs && cd auth0-vanillajs - ``` - - Initialize the project and install a local development server - - ```shellscript - npm init -y && npm install --save-dev vite - ``` - - Create the basic project structure - - ```shellscript - touch index.html app.js style.css - ``` - - - ```shellscript - npm install @auth0/auth0-spa-js - ``` - - - Next up, you need to create a new app on your Auth0 tenant and add the environment variables to your project. - - You can choose to do this automatically by running a CLI command or do it manually via the Dashboard: - - - - Run the following shell command on your project's root directory to create an Auth0 app and generate a `.env.local` file: - - - ```shellscript Mac - AUTH0_APP_NAME="My Vanilla JS App" && brew tap auth0/auth0-cli && brew install auth0 && auth0 login --no-input && auth0 apps create -n "${AUTH0_APP_NAME}" -t spa -c http://localhost:5173 -l http://localhost:5173 -o http://localhost:5173 --json > auth0-app-details.json && CLIENT_ID=$(jq -r '.client_id' auth0-app-details.json) && DOMAIN=$(auth0 tenants list --json | jq -r '.[] | select(.active == true) | .name') && echo "VITE_AUTH0_DOMAIN=${DOMAIN}" > .env.local && echo "VITE_AUTH0_CLIENT_ID=${CLIENT_ID}" >> .env.local && rm auth0-app-details.json && echo ".env.local file created with your Auth0 details:" && cat .env.local - ``` - - ```shellscript Windows - $AppName = "My Vanilla JS App"; winget install Auth0.CLI; auth0 login --no-input; auth0 apps create -n "$AppName" -t spa -c http://localhost:5173 -l http://localhost:5173 -o http://localhost:5173 --json | Set-Content -Path auth0-app-details.json; $ClientId = (Get-Content -Raw auth0-app-details.json | ConvertFrom-Json).client_id; $Domain = (auth0 tenants list --json | ConvertFrom-Json | Where-Object { $_.active -eq $true }).name; Set-Content -Path .env.local -Value "VITE_AUTH0_DOMAIN=$Domain"; Add-Content -Path .env.local -Value "VITE_AUTH0_CLIENT_ID=$ClientId"; Remove-Item auth0-app-details.json; Write-Output ".env.local file created with your Auth0 details:"; Get-Content .env.local - ``` - - - - - Before you start, create a `.env.local` file on your project's root directory - - ```shellscript .env.local - VITE_AUTH0_DOMAIN=YOUR_AUTH0_APP_DOMAIN - VITE_AUTH0_CLIENT_ID=YOUR_AUTH0_APP_CLIENT_ID - ``` - - 1. Head to the [Auth0 Dashboard](https://manage.auth0.com/dashboard/) - 2. Click on **Applications** > **Applications** > **Create Application** - 3. In the popup, enter a name for your app, select `Single Page Web Application` as the app type and click **Create** - 4. Switch to the **Settings** tab on the Application Details page - 5. Replace `YOUR_AUTH0_APP_DOMAIN` and `YOUR_AUTH0_APP_CLIENT_ID` on the `.env.local` file with the **Domain** and **Client ID** values from the dashboard - - Finally, on the **Settings** tab of your Application Details page, set **Allowed Callback URLs**, **Allowed Logout URLs** and **Allowed Web Origins** to: - - ``` - http://localhost:5173 - ``` - - - **Allowed Callback URLs** are a critical security measure to ensure users are safely returned to your application after authentication. Without a matching URL, the login process will fail, and users will be blocked by an Auth0 error page instead of accessing your app. - - **Allowed Logout URLs** are essential for providing a seamless user experience upon signing out. Without a matching URL, users will not be redirected back to your application after logout and will instead be left on a generic Auth0 page. - - **Allowed Web Origins** is critical for silent authentication. Without it, users will be logged out when they refresh the page or return to your app later. - - - - - - Create the application files: - - - - ```html index.html expandable lines - - - - - - Auth0 Vanilla JS - - - -
    - -
    -
    Loading...
    -
    - - - - - - -
    - - - - - ``` - - ```javascript app.js expandable lines - import { createAuth0Client } from '@auth0/auth0-spa-js'; - - // DOM elements - const loading = document.getElementById('loading'); - const error = document.getElementById('error'); - const errorDetails = document.getElementById('error-details'); - const app = document.getElementById('app'); - const loggedOutSection = document.getElementById('logged-out'); - const loggedInSection = document.getElementById('logged-in'); - const loginBtn = document.getElementById('login-btn'); - const logoutBtn = document.getElementById('logout-btn'); - const profileContainer = document.getElementById('profile'); - - let auth0Client; - - // Initialize Auth0 client - async function initAuth0() { - try { - auth0Client = await createAuth0Client({ - domain: import.meta.env.VITE_AUTH0_DOMAIN, - clientId: import.meta.env.VITE_AUTH0_CLIENT_ID, - authorizationParams: { - redirect_uri: window.location.origin - } - }); - - // Check if user is returning from login - if (window.location.search.includes('code=') && window.location.search.includes('state=')) { - await handleRedirectCallback(); - } - - // Update UI based on authentication state - await updateUI(); - } catch (err) { - showError(err.message); - } - } - - // Handle redirect callback - async function handleRedirectCallback() { - try { - await auth0Client.handleRedirectCallback(); - // Clean up the URL to remove query parameters - window.history.replaceState({}, document.title, window.location.pathname); - } catch (err) { - showError(err.message); - } - } - - // Update UI based on authentication state - async function updateUI() { - try { - const isAuthenticated = await auth0Client.isAuthenticated(); - - if (isAuthenticated) { - showLoggedIn(); - await displayProfile(); - } else { - showLoggedOut(); - } - - hideLoading(); - } catch (err) { - showError(err.message); - } - } - - // Display user profile - async function displayProfile() { - try { - const user = await auth0Client.getUser(); - - profileContainer.innerHTML = ` -
    - ${user.picture ? ` - ${user.name || 'User'} - ` : ''} -
    -
    - ${user.name || 'User'} -
    -
    - ${user.email || 'No email provided'} -
    -
    -
    - `; - } catch (err) { - console.error('Error displaying profile:', err); - } - } - - // Event handlers - async function login() { - try { - await auth0Client.loginWithRedirect(); - } catch (err) { - showError(err.message); - } - } - - async function logout() { - try { - await auth0Client.logout({ - logoutParams: { - returnTo: window.location.origin - } - }); - } catch (err) { - showError(err.message); - } - } - - // UI state management - function showLoading() { - loading.style.display = 'block'; - error.style.display = 'none'; - app.style.display = 'none'; - } - - function hideLoading() { - loading.style.display = 'none'; - app.style.display = 'flex'; - } - - function showError(message) { - loading.style.display = 'none'; - app.style.display = 'none'; - error.style.display = 'block'; - errorDetails.textContent = message; - } - - function showLoggedIn() { - loggedOutSection.style.display = 'none'; - loggedInSection.style.display = 'flex'; - } - - function showLoggedOut() { - loggedInSection.style.display = 'none'; - loggedOutSection.style.display = 'flex'; - } - - // Event listeners - loginBtn.addEventListener('click', login); - logoutBtn.addEventListener('click', logout); - - // Initialize the app - initAuth0(); - ``` - - ```css style.css expandable lines - @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap'); - - * { - margin: 0; - padding: 0; - box-sizing: border-box; - } - - body { - font-family: 'Inter', sans-serif; - background-color: #1a1e27; - min-height: 100vh; - display: flex; - justify-content: center; - align-items: center; - color: #e2e8f0; - overflow: hidden; - } - - .app-container { - display: flex; - flex-direction: column; - justify-content: center; - align-items: center; - min-height: 100vh; - width: 100%; - padding: 1rem; - } - - .loading-state, .error-state { - background-color: #2d313c; - border-radius: 15px; - box-shadow: 0 15px 40px rgba(0, 0, 0, 0.4); - padding: 3rem; - text-align: center; - } - - .loading-text { - font-size: 1.8rem; - font-weight: 500; - color: #a0aec0; - animation: pulse 1.5s infinite ease-in-out; - } - - .error-state { - background-color: #c53030; - color: #fff; - } - - .error-title { - font-size: 2.8rem; - font-weight: 700; - margin-bottom: 0.5rem; - } - - .error-message { - font-size: 1.3rem; - margin-bottom: 0.5rem; - } - - .error-sub-message { - font-size: 1rem; - opacity: 0.8; - } - - .main-card-wrapper { - background-color: #262a33; - border-radius: 20px; - box-shadow: 0 20px 60px rgba(0, 0, 0, 0.6), 0 0 0 1px rgba(255, 255, 255, 0.05); - display: flex; - flex-direction: column; - align-items: center; - gap: 2rem; - padding: 3rem; - max-width: 500px; - width: 90%; - animation: fadeInScale 0.8s ease-out forwards; - } - - .auth0-logo { - width: 160px; - margin-bottom: 1.5rem; - opacity: 0; - animation: slideInDown 1s ease-out forwards 0.2s; - } - - .main-title { - font-size: 2.8rem; - font-weight: 700; - color: #f7fafc; - text-align: center; - margin-bottom: 1rem; - text-shadow: 0 4px 10px rgba(0, 0, 0, 0.3); - opacity: 0; - animation: fadeIn 1s ease-out forwards 0.4s; - } - - .action-card { - background-color: #2d313c; - border-radius: 15px; - box-shadow: inset 0 2px 5px rgba(0, 0, 0, 0.3), 0 5px 15px rgba(0, 0, 0, 0.3); - padding: 2.5rem; - display: flex; - flex-direction: column; - align-items: center; - gap: 1.8rem; - width: calc(100% - 2rem); - opacity: 0; - animation: fadeIn 1s ease-out forwards 0.6s; - } - - .action-text { - font-size: 1.25rem; - color: #cbd5e0; - text-align: center; - line-height: 1.6; - font-weight: 400; - } - - .button { - padding: 1.1rem 2.8rem; - font-size: 1.2rem; - font-weight: 600; - border-radius: 10px; - border: none; - cursor: pointer; - transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1); - box-shadow: 0 8px 20px rgba(0, 0, 0, 0.4); - text-transform: uppercase; - letter-spacing: 0.08em; - outline: none; - } - - .button:focus { - box-shadow: 0 0 0 4px rgba(99, 179, 237, 0.5); - } - - .button.login { - background-color: #63b3ed; - color: #1a1e27; - } - - .button.login:hover { - background-color: #4299e1; - transform: translateY(-5px) scale(1.03); - box-shadow: 0 12px 25px rgba(0, 0, 0, 0.5); - } - - .button.logout { - background-color: #fc8181; - color: #1a1e27; - } - - .button.logout:hover { - background-color: #e53e3e; - transform: translateY(-5px) scale(1.03); - box-shadow: 0 12px 25px rgba(0, 0, 0, 0.5); - } - - .logged-in-section { - display: flex; - flex-direction: column; - align-items: center; - gap: 1.5rem; - width: 100%; - } - - .logged-in-message { - font-size: 1.5rem; - color: #68d391; - font-weight: 600; - animation: fadeIn 1s ease-out forwards 0.8s; - } - - .profile-section-title { - font-size: 2.2rem; - animation: slideInUp 1s ease-out forwards 1s; - } - - .profile-card { - padding: 2.2rem; - animation: scaleIn 0.8s ease-out forwards 1.2s; - } - - .profile-picture { - transition: transform 0.3s ease-in-out; - } - - .profile-picture:hover { - transform: scale(1.05); - } - - /* Animations */ - @keyframes fadeIn { - from { opacity: 0; } - to { opacity: 1; } - } - - @keyframes fadeInScale { - from { opacity: 0; transform: scale(0.95); } - to { opacity: 1; transform: scale(1); } - } - - @keyframes slideInDown { - from { opacity: 0; transform: translateY(-70px); } - to { opacity: 1; transform: translateY(0); } - } - - @keyframes slideInUp { - from { opacity: 0; transform: translateY(50px); } - to { opacity: 1; transform: translateY(0); } - } - - @keyframes pulse { - 0%, 100% { opacity: 1; } - 50% { opacity: 0.6; } - } - - @keyframes scaleIn { - from { opacity: 0; transform: scale(0.8); } - to { opacity: 1; transform: scale(1); } - } - - /* Responsive Design */ - @media (max-width: 600px) { - .main-card-wrapper { - padding: 2rem; - margin: 1rem; - } - - .main-title { - font-size: 2.2rem; - } - - .button { - padding: 1rem 2rem; - font-size: 1.1rem; - } - - .auth0-logo { - width: 120px; - } - - .action-card { - padding: 2rem; - } - } - ``` - - ```javascript app.js expandable lines - import { createAuth0Client } from '@auth0/auth0-spa-js'; - - // DOM elements - const loading = document.getElementById('loading'); - const error = document.getElementById('error'); - const errorDetails = document.getElementById('error-details'); - const app = document.getElementById('app'); - const loggedOutSection = document.getElementById('logged-out'); - const loggedInSection = document.getElementById('logged-in'); - const loginBtn = document.getElementById('login-btn'); - const logoutBtn = document.getElementById('logout-btn'); - const profileContainer = document.getElementById('profile'); - - let auth0Client; - - // Initialize Auth0 client - async function initAuth0() { - try { - auth0Client = await createAuth0Client({ - domain: import.meta.env.VITE_AUTH0_DOMAIN, - clientId: import.meta.env.VITE_AUTH0_CLIENT_ID, - authorizationParams: { - redirect_uri: window.location.origin - } - }); - - // Check if user is returning from login - if (window.location.search.includes('code=') && window.location.search.includes('state=')) { - await handleRedirectCallback(); - } - - // Update UI based on authentication state - await updateUI(); - } catch (err) { - showError(err.message); - } - } - - // Handle redirect callback - async function handleRedirectCallback() { - try { - await auth0Client.handleRedirectCallback(); - // Clean up the URL to remove query parameters - window.history.replaceState({}, document.title, window.location.pathname); - } catch (err) { - showError(err.message); - } - } - - // Update UI based on authentication state - async function updateUI() { - try { - const isAuthenticated = await auth0Client.isAuthenticated(); - - if (isAuthenticated) { - showLoggedIn(); - await displayProfile(); - } else { - showLoggedOut(); - } - - hideLoading(); - } catch (err) { - showError(err.message); - } - } - - // Display user profile - async function displayProfile() { - try { - const user = await auth0Client.getUser(); - - profileContainer.innerHTML = ` -
    - ${user.picture ? ` - ${user.name || 'User'} - ` : ''} -
    -
    - ${user.name || 'User'} -
    -
    - ${user.email || 'No email provided'} -
    -
    -
    - `; - } catch (err) { - console.error('Error displaying profile:', err); - } - } - - // Event handlers - async function login() { - try { - await auth0Client.loginWithRedirect(); - } catch (err) { - showError(err.message); - } - } - - async function logout() { - try { - await auth0Client.logout({ - logoutParams: { - returnTo: window.location.origin - } - }); - } catch (err) { - showError(err.message); - } - } - - // UI state management - function showLoading() { - loading.style.display = 'block'; - error.style.display = 'none'; - app.style.display = 'none'; - } - - function hideLoading() { - loading.style.display = 'none'; - app.style.display = 'flex'; - } - - function showError(message) { - loading.style.display = 'none'; - app.style.display = 'none'; - error.style.display = 'block'; - errorDetails.textContent = message; - } - - function showLoggedIn() { - loggedOutSection.style.display = 'none'; - loggedInSection.style.display = 'flex'; - } - - function showLoggedOut() { - loggedInSection.style.display = 'none'; - loggedOutSection.style.display = 'flex'; - } - - // Event listeners - loginBtn.addEventListener('click', login); - logoutBtn.addEventListener('click', logout); - - // Initialize the app - initAuth0(); - ``` - - ```css style.css expandable lines - @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap'); - - * { - margin: 0; - padding: 0; - box-sizing: border-box; - } - - body { - font-family: 'Inter', sans-serif; - background-color: #1a1e27; - min-height: 100vh; - display: flex; - justify-content: center; - align-items: center; - color: #e2e8f0; - overflow: hidden; - } - - .app-container { - display: flex; - flex-direction: column; - justify-content: center; - align-items: center; - min-height: 100vh; - width: 100%; - padding: 1rem; - } - - .loading-state, .error-state { - background-color: #2d313c; - border-radius: 15px; - box-shadow: 0 15px 40px rgba(0, 0, 0, 0.4); - padding: 3rem; - text-align: center; - } - - .loading-text { - font-size: 1.8rem; - font-weight: 500; - color: #a0aec0; - animation: pulse 1.5s infinite ease-in-out; - } - - .error-state { - background-color: #c53030; - color: #fff; - } - - .error-title { - font-size: 2.8rem; - font-weight: 700; - margin-bottom: 0.5rem; - } - - .error-message { - font-size: 1.3rem; - margin-bottom: 0.5rem; - } - - .error-sub-message { - font-size: 1rem; - opacity: 0.8; - } - - .main-card-wrapper { - background-color: #262a33; - border-radius: 20px; - box-shadow: 0 20px 60px rgba(0, 0, 0, 0.6), 0 0 0 1px rgba(255, 255, 255, 0.05); - display: flex; - flex-direction: column; - align-items: center; - gap: 2rem; - padding: 3rem; - max-width: 500px; - width: 90%; - animation: fadeInScale 0.8s ease-out forwards; - } - - .auth0-logo { - width: 160px; - margin-bottom: 1.5rem; - opacity: 0; - animation: slideInDown 1s ease-out forwards 0.2s; - } - - .main-title { - font-size: 2.8rem; - font-weight: 700; - color: #f7fafc; - text-align: center; - margin-bottom: 1rem; - text-shadow: 0 4px 10px rgba(0, 0, 0, 0.3); - opacity: 0; - animation: fadeIn 1s ease-out forwards 0.4s; - } - - .action-card { - background-color: #2d313c; - border-radius: 15px; - box-shadow: inset 0 2px 5px rgba(0, 0, 0, 0.3), 0 5px 15px rgba(0, 0, 0, 0.3); - padding: 2.5rem; - display: flex; - flex-direction: column; - align-items: center; - gap: 1.8rem; - width: calc(100% - 2rem); - opacity: 0; - animation: fadeIn 1s ease-out forwards 0.6s; - } - - .action-text { - font-size: 1.25rem; - color: #cbd5e0; - text-align: center; - line-height: 1.6; - font-weight: 400; - } - - .button { - padding: 1.1rem 2.8rem; - font-size: 1.2rem; - font-weight: 600; - border-radius: 10px; - border: none; - cursor: pointer; - transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1); - box-shadow: 0 8px 20px rgba(0, 0, 0, 0.4); - text-transform: uppercase; - letter-spacing: 0.08em; - outline: none; - } - - .button:focus { - box-shadow: 0 0 0 4px rgba(99, 179, 237, 0.5); - } - - .button.login { - background-color: #63b3ed; - color: #1a1e27; - } - - .button.login:hover { - background-color: #4299e1; - transform: translateY(-5px) scale(1.03); - box-shadow: 0 12px 25px rgba(0, 0, 0, 0.5); - } - - .button.logout { - background-color: #fc8181; - color: #1a1e27; - } - - .button.logout:hover { - background-color: #e53e3e; - transform: translateY(-5px) scale(1.03); - box-shadow: 0 12px 25px rgba(0, 0, 0, 0.5); - } - - .logged-in-section { - display: flex; - flex-direction: column; - align-items: center; - gap: 1.5rem; - width: 100%; - } - - .logged-in-message { - font-size: 1.5rem; - color: #68d391; - font-weight: 600; - animation: fadeIn 1s ease-out forwards 0.8s; - } - - .profile-section-title { - font-size: 2.2rem; - animation: slideInUp 1s ease-out forwards 1s; - } - - .profile-card { - padding: 2.2rem; - animation: scaleIn 0.8s ease-out forwards 1.2s; - } - - .profile-picture { - transition: transform 0.3s ease-in-out; - } - - .profile-picture:hover { - transform: scale(1.05); - } - - /* Animations */ - @keyframes fadeIn { - from { opacity: 0; } - to { opacity: 1; } - } - - @keyframes fadeInScale { - from { opacity: 0; transform: scale(0.95); } - to { opacity: 1; transform: scale(1); } - } - - @keyframes slideInDown { - from { opacity: 0; transform: translateY(-70px); } - to { opacity: 1; transform: translateY(0); } - } - - @keyframes slideInUp { - from { opacity: 0; transform: translateY(50px); } - to { opacity: 1; transform: translateY(0); } - } - - @keyframes pulse { - 0%, 100% { opacity: 1; } - 50% { opacity: 0.6; } - } - - @keyframes scaleIn { - from { opacity: 0; transform: scale(0.8); } - to { opacity: 1; transform: scale(1); } - } - - /* Responsive Design */ - @media (max-width: 600px) { - .main-card-wrapper { - padding: 2rem; - margin: 1rem; - } - - .main-title { - font-size: 2.2rem; - } - - .button { - padding: 1rem 2rem; - font-size: 1.1rem; - } - - .auth0-logo { - width: 120px; - } - - .action-card { - padding: 2rem; - } - } - ``` - -
    -
    - - ```shellscript - npm run dev - ``` - -
    - - - **Checkpoint** - - You should now have a fully functional Auth0 login page running on your [localhost](http://localhost:5173/) - - ---- - -## Advanced Usage - - - If you need to call a protected API, you can get an access token: - - ```javascript - // Add this to your app.js - async function getAccessToken() { - try { - const token = await auth0Client.getTokenSilently({ - authorizationParams: { - audience: 'YOUR_API_IDENTIFIER', - scope: 'read:messages' - } - }); - - // Use the token to call your API - const response = await fetch('/api/protected', { - headers: { - Authorization: `Bearer ${token}` - } - }); - - const data = await response.json(); - console.log(data); - } catch (error) { - console.error('Error getting token:', error); - } - } - ``` - - - - For a smoother user experience, you can use popup-based login: - - ```javascript - // Replace the login function in app.js - async function login() { - try { - await auth0Client.loginWithPopup(); - await updateUI(); - } catch (err) { - if (err.error !== 'popup_closed_by_user') { - showError(err.message); - } - } - } - ``` - - - - If you're using Auth0 Organizations: - - ```javascript - // Update your Auth0 client configuration - auth0Client = await createAuth0Client({ - domain: import.meta.env.VITE_AUTH0_DOMAIN, - clientId: import.meta.env.VITE_AUTH0_CLIENT_ID, - authorizationParams: { - redirect_uri: window.location.origin, - organization: 'YOUR_ORGANIZATION_ID' // or prompt user to select - } - }); - ``` - +--- +mode: wide +'og:description': This guide demonstrates how to integrate Auth0, add authentication, + and display user profile information in a Single-Page Application (SPA) that uses + plain JavaScript, using the Auth0 SPA SDK. +'og:image': https://cdn2.auth0.com/docs/1.14553.0/img/share-image.png +'og:title': 'Auth0 JavaScript SDK Quickstarts: Add Login to Your JavaScript Application' +'og:url': https://auth0.com/docs/ +sidebarTitle: JavaScript +title: Add Login to Your JavaScript Application +'twitter:description': This guide demonstrates how to integrate Auth0, add authentication, + and display user profile information in a Single-Page Application (SPA) that uses + plain JavaScript, using the Auth0 SPA SDK. +'twitter:title': 'Auth0 JavaScript SDK Quickstarts: Add Login to Your JavaScript Application' +--- + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + + + **Using AI to integrate Auth0?** Add this prompt to Cursor, Windsurf, Copilot, Claude Code or your favourite AI-powered IDE to speed up development. + + ```markdown expandable + Integrate the Auth0 SPA JS SDK into a Vanilla JavaScript app + +AI PERSONA & PRIMARY OBJECTIVE +You are a helpful Auth0 SDK Integration Assistant. Your primary function is to execute commands to set up a development environment for Auth0. Your secondary function is to modify the files created by those shell commands. + +CRITICAL BEHAVIORAL INSTRUCTIONS +1. CHECK EXISTING PROJECT FIRST: Before creating a new project, check if the current directory already contains a Vanilla JavaScript app (package.json with basic dependencies). If it does, skip project creation and work with the existing project. +2. EXECUTE FIRST, EDIT SECOND: You MUST first execute the appropri # If using custom port (run this instead if Step 2.6a detected custom port): + npm run dev -- --port 5174 + +⚠️ FINAL VERIFICATION CHECKPOINTS: +After running the development server, test the complete authentication flow: +1. Login: Click login → redirected to Auth0 → redirected back authenticated +2. Profile: User information displays correctly after login +3. Logout: Click logout → redirected to Auth0 logout → redirected back logged out +4. Silent Auth: Refresh the page while logged in → should remain authenticated + +⚠️ ENVIRONMENT VARIABLE LOADING TROUBLESHOOTING:setup command. Do not show, suggest, or create any files until the setup is complete. +3. NO PLANNING: DO NOT propose a directory structure. DO NOT show a file tree. Your first action must be to run the appropriate command. +4. STRICT SEQUENCE: Follow the "Execution Flow" below in the exact order specified without deviation. +5. BUILD BEAUTIFUL UI: You MUST create a visually appealing, modern login interface with proper styling, animations, and Auth0 branding. +6. 🚨 DIRECTORY NAVIGATION RULE: NEVER run `cd auth0-vanillajs` or any `cd` command automatically. ALWAYS check current directory with `pwd` first. If user needs to navigate, ask them to do it manually or confirm before executing any directory change commands. + +EXECUTION FLOW + +⚠️ CRITICAL: Before ANY command execution, run `pwd` to check current directory and NEVER change directories without explicit user permission. + +Step 1: Check for Existing Vanilla JS Project and Prerequisites +FIRST, verify prerequisites and check for existing project: + + # Check if Node.js and npm are available + node --version && npm --version + +Then examine the current directory: + + # Check for existing project + if [ -f "package.json" ]; then + echo "Found package.json, checking for dependencies..." + cat package.json + else + echo "No package.json found, will create new project" + fi + +Based on the results: +- If package.json exists and contains basic dependencies, proceed to Step 1b (install Auth0 SDK only) +- If no project exists, proceed to Step 1a (create new project) + +Step 1a: Create New Project and Install the Auth0 SPA JS SDK +If an existing project exists, simply install the SDK: +npm install @auth0/auth0-spa-js + +⚠️ CDN ALTERNATIVE: If you prefer not to use a build tool, you can include the SDK via CDN instead of npm: + +Then use the global auth0 object: auth0.createAuth0Client({...}) instead of importing. + +Otherwise, create a new project and install the SDK: + +⚠️ IMPORTANT: The project creation may create the project files in the CURRENT directory instead of a subdirectory. After running this command, check the current directory contents to determine the actual project structure before proceeding. + +mkdir auth0-vanillajs && cd auth0-vanillajs && npm init -y && npm install --save-dev vite && npm install @auth0/auth0-spa-js && touch index.html app.js style.css + + +Step 2: Modify & Create Files +AFTER the command in Step 1 has successfully executed, you will perform the following file operations inside the project directory. + +🚨 DIRECTORY NAVIGATION RULES: +1. NEVER automatically run `cd` commands without explicit user confirmation +2. ALWAYS check current directory with `pwd` before proceeding +3. If working with existing project: Stay in current directory +4. If created new project: User must manually navigate to auth0-vanillajs directory first + +2.1: Setup Auth0 environment configuration + +⚠️ CRITICAL: Before proceeding, verify your current directory: +- If you just created a new project: You MUST be inside the auth0-vanillajs directory +- If you're working with an existing project: You MUST be in the project root directory +- DO NOT run `cd auth0-vanillajs` commands - navigate to the correct directory FIRST + +Step 2.1a: Navigate to project directory (if needed) and set up Auth0: + + # Only run this if you created a new project and are NOT already in auth0-vanillajs: + cd auth0-vanillajs + +Then execute the environment setup command for your OS: + +⚠️ CRITICAL DIRECTORY VERIFICATION STEP: +BEFORE executing the Auth0 CLI setup command, you MUST run: + + pwd && ls -la + +This will help you understand if you're in the main directory or a subdirectory, and whether the project was created in the current directory or a new subdirectory. + +If MacOS, execute the following command: +AUTH0_APP_NAME="My Vanilla JS App" && brew tap auth0/auth0-cli && brew install auth0 && auth0 login --no-input && auth0 apps create -n "${AUTH0_APP_NAME}" -t spa -c http://localhost:5173 -l http://localhost:5173 -o http://localhost:5173 --json > auth0-app-details.json && CLIENT_ID=$(jq -r '.client_id' auth0-app-details.json) && DOMAIN=$(auth0 tenants list --json | jq -r '.[] | select(.active == true) | .name') && echo "VITE_AUTH0_DOMAIN=${DOMAIN}" > .env.local && echo "VITE_AUTH0_CLIENT_ID=${CLIENT_ID}" >> .env.local && rm auth0-app-details.json && echo ".env.local file created with your Auth0 details:" && cat .env.local + +If Windows, execute the following command: +$AppName = "My Vanilla JS App"; winget install Auth0.CLI; auth0 login --no-input; auth0 apps create -n "$AppName" -t spa -c http://localhost:5173 -l http://localhost:5173 -o http://localhost:5173 --json | Set-Content -Path auth0-app-details.json; $ClientId = (Get-Content -Raw auth0-app-details.json | ConvertFrom-Json).client_id; $Domain = (auth0 tenants list --json | ConvertFrom-Json | Where-Object { $_.active -eq $true }).name; Set-Content -Path .env.local -Value "VITE_AUTH0_DOMAIN=$Domain"; Add-Content -Path .env.local -Value "VITE_AUTH0_CLIENT_ID=$ClientId"; Remove-Item auth0-app-details.json; Write-Output ".env.local file created with your Auth0 details:"; Get-Content .env.local + + +Step 2.1b: Create manual .env.local template (if automatic setup fails) + + cat > .env.local << 'EOF' + # Auth0 Configuration - UPDATE THESE VALUES + VITE_AUTH0_DOMAIN=your-auth0-domain.auth0.com + VITE_AUTH0_CLIENT_ID=your-auth0-client-id + EOF + +Step 2.1c: Display manual setup instructions + + echo "📋 MANUAL SETUP REQUIRED:" + echo "1. Go to https://manage.auth0.com/dashboard/" + echo "2. Click 'Create Application' → Single Page Application" + echo "3. Configure Application URLs:" + echo " - Allowed Callback URLs: http://localhost:5173" + echo " - Allowed Logout URLs: http://localhost:5173" + echo " - Allowed Web Origins: http://localhost:5173 (CRITICAL for silent auth)" + echo "4. Update .env.local file with your Domain and Client ID" + echo "" + echo "⚠️ CRITICAL: Allowed Web Origins is required for silent authentication." + echo " Without it, users will be logged out when they refresh the page." + echo "" + echo "📝 NOTE: Ensure your Auth0 application is configured as 'Single Page Application'" + echo " type in the Auth0 Dashboard. Other application types won't work with this SDK." + +2.2: Create the HTML structure +Replace the entire contents of index.html (or create it if it doesn't exist): + + + + + + + Auth0 Vanilla JS + + + +
    + +
    +
    Loading...
    +
    + + + + + + +
    + + + + + +2.3: Create the application logic +Replace the entire contents of app.js with this code that includes proper error handling and Auth0 integration: + +⚠️ JAVASCRIPT MODULE GUIDELINES: +- Ensure proper ES6 module imports are used +- Include comprehensive error handling for Auth0 initialization +- Validate environment variables before using them +- Handle all authentication states (loading, error, authenticated, unauthenticated) + + import { createAuth0Client } from '@auth0/auth0-spa-js'; + + // DOM elements + const loading = document.getElementById('loading'); + const error = document.getElementById('error'); + const errorDetails = document.getElementById('error-details'); + const app = document.getElementById('app'); + const loggedOutSection = document.getElementById('logged-out'); + const loggedInSection = document.getElementById('logged-in'); + const loginBtn = document.getElementById('login-btn'); + const logoutBtn = document.getElementById('logout-btn'); + const profileContainer = document.getElementById('profile'); + + let auth0Client; + + // Initialize Auth0 client + async function initAuth0() { + try { + // Validate environment variables + const domain = import.meta.env.VITE_AUTH0_DOMAIN; + const clientId = import.meta.env.VITE_AUTH0_CLIENT_ID; + + if (!domain || !clientId) { + throw new Error('Auth0 configuration missing. Please check your .env.local file for VITE_AUTH0_DOMAIN and VITE_AUTH0_CLIENT_ID'); + } + + // Validate domain format + if (!domain.includes('.auth0.com') && !domain.includes('.us.auth0.com') && !domain.includes('.eu.auth0.com') && !domain.includes('.au.auth0.com')) { + console.warn('Auth0 domain format might be incorrect. Expected format: your-domain.auth0.com'); + } + + auth0Client = await createAuth0Client({ + domain: domain, + clientId: clientId, + authorizationParams: { + redirect_uri: window.location.origin + } + }); + + // Check if user is returning from login + if (window.location.search.includes('code=') && window.location.search.includes('state=')) { + await handleRedirectCallback(); + } + + // Update UI based on authentication state + await updateUI(); + } catch (err) { + console.error('Auth0 initialization error:', err); + showError(err.message); + } + } + + // Handle redirect callback + async function handleRedirectCallback() { + try { + await auth0Client.handleRedirectCallback(); + // Clean up the URL to remove query parameters + window.history.replaceState({}, document.title, window.location.pathname); + } catch (err) { + console.error('Redirect callback error:', err); + showError(err.message); + } + } + + // Update UI based on authentication state + async function updateUI() { + try { + const isAuthenticated = await auth0Client.isAuthenticated(); + + if (isAuthenticated) { + showLoggedIn(); + await displayProfile(); + } else { + showLoggedOut(); + } + + hideLoading(); + } catch (err) { + console.error('UI update error:', err); + showError(err.message); + } + } + + // Display user profile + async function displayProfile() { + try { + const user = await auth0Client.getUser(); + + profileContainer.innerHTML = ` +
    + ${user.picture ? ` + ${user.name || 'User'} + ` : ''} +
    +
    + ${user.name || 'User'} +
    +
    + ${user.email || 'No email provided'} +
    +
    +
    + `; + } catch (err) { + console.error('Error displaying profile:', err); + } + } + + // Event handlers + async function login() { + try { + await auth0Client.loginWithRedirect(); + } catch (err) { + console.error('Login error:', err); + showError(err.message); + } + } + + async function logout() { + try { + await auth0Client.logout({ + logoutParams: { + returnTo: window.location.origin + } + }); + } catch (err) { + console.error('Logout error:', err); + showError(err.message); + } + } + + // UI state management + function showLoading() { + loading.style.display = 'block'; + error.style.display = 'none'; + app.style.display = 'none'; + } + + function hideLoading() { + loading.style.display = 'none'; + app.style.display = 'flex'; + } + + function showError(message) { + loading.style.display = 'none'; + app.style.display = 'none'; + error.style.display = 'block'; + errorDetails.textContent = message; + } + + function showLoggedIn() { + loggedOutSection.style.display = 'none'; + loggedInSection.style.display = 'flex'; + } + + function showLoggedOut() { + loggedInSection.style.display = 'none'; + loggedOutSection.style.display = 'flex'; + } + + // Event listeners + loginBtn.addEventListener('click', login); + logoutBtn.addEventListener('click', logout); + + // Initialize the app + initAuth0(); + +⚠️ CHECKPOINT VERIFICATION: +After implementing the JavaScript logic, you should be able to test basic functionality: +1. Click login button → redirected to Auth0's Universal Login page +2. After authentication → redirected back to your application +3. URL query parameters are cleaned up after redirect +4. No console errors appear related to Auth0 + +2.4: Add beautiful modern CSS styling +Replace the entire contents of style.css with this modern, Auth0-branded styling: + +⚠️ CSS FILE REPLACEMENT STRATEGY: +If the existing style.css file is large or malformed, create a new temporary CSS file first (e.g., style-new.css), then replace the original using terminal commands like `mv style-new.css style.css` to avoid file corruption. + + @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap'); + + * { + margin: 0; + padding: 0; + box-sizing: border-box; + } + + body { + font-family: 'Inter', sans-serif; + background-color: #1a1e27; + min-height: 100vh; + display: flex; + justify-content: center; + align-items: center; + color: #e2e8f0; + overflow: hidden; + } + + .app-container { + display: flex; + flex-direction: column; + justify-content: center; + align-items: center; + min-height: 100vh; + width: 100%; + padding: 1rem; + } + + .loading-state, .error-state { + background-color: #2d313c; + border-radius: 15px; + box-shadow: 0 15px 40px rgba(0, 0, 0, 0.4); + padding: 3rem; + text-align: center; + } + + .loading-text { + font-size: 1.8rem; + font-weight: 500; + color: #a0aec0; + animation: pulse 1.5s infinite ease-in-out; + } + + .error-state { + background-color: #c53030; + color: #fff; + } + + .error-title { + font-size: 2.8rem; + font-weight: 700; + margin-bottom: 0.5rem; + } + + .error-message { + font-size: 1.3rem; + margin-bottom: 0.5rem; + } + + .error-sub-message { + font-size: 1rem; + opacity: 0.8; + } + + .main-card-wrapper { + background-color: #262a33; + border-radius: 20px; + box-shadow: 0 20px 60px rgba(0, 0, 0, 0.6), 0 0 0 1px rgba(255, 255, 255, 0.05); + display: flex; + flex-direction: column; + align-items: center; + gap: 2rem; + padding: 3rem; + max-width: 500px; + width: 90%; + animation: fadeInScale 0.8s ease-out forwards; + } + + .auth0-logo { + width: 160px; + margin-bottom: 1.5rem; + opacity: 0; + animation: slideInDown 1s ease-out forwards 0.2s; + } + + .main-title { + font-size: 2.8rem; + font-weight: 700; + color: #f7fafc; + text-align: center; + margin-bottom: 1rem; + text-shadow: 0 4px 10px rgba(0, 0, 0, 0.3); + opacity: 0; + animation: fadeIn 1s ease-out forwards 0.4s; + } + + .action-card { + background-color: #2d313c; + border-radius: 15px; + box-shadow: inset 0 2px 5px rgba(0, 0, 0, 0.3), 0 5px 15px rgba(0, 0, 0, 0.3); + padding: 2.5rem; + display: flex; + flex-direction: column; + align-items: center; + gap: 1.8rem; + width: calc(100% - 2rem); + opacity: 0; + animation: fadeIn 1s ease-out forwards 0.6s; + } + + .action-text { + font-size: 1.25rem; + color: #cbd5e0; + text-align: center; + line-height: 1.6; + font-weight: 400; + } + + .button { + padding: 1.1rem 2.8rem; + font-size: 1.2rem; + font-weight: 600; + border-radius: 10px; + border: none; + cursor: pointer; + transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1); + box-shadow: 0 8px 20px rgba(0, 0, 0, 0.4); + text-transform: uppercase; + letter-spacing: 0.08em; + outline: none; + } + + .button:focus { + box-shadow: 0 0 0 4px rgba(99, 179, 237, 0.5); + } + + .button.login { + background-color: #63b3ed; + color: #1a1e27; + } + + .button.login:hover { + background-color: #4299e1; + transform: translateY(-5px) scale(1.03); + box-shadow: 0 12px 25px rgba(0, 0, 0, 0.5); + } + + .button.logout { + background-color: #fc8181; + color: #1a1e27; + } + + .button.logout:hover { + background-color: #e53e3e; + transform: translateY(-5px) scale(1.03); + box-shadow: 0 12px 25px rgba(0, 0, 0, 0.5); + } + + .logged-in-section { + display: flex; + flex-direction: column; + align-items: center; + gap: 1.5rem; + width: 100%; + } + + .logged-in-message { + font-size: 1.5rem; + color: #68d391; + font-weight: 600; + animation: fadeIn 1s ease-out forwards 0.8s; + } + + .profile-section-title { + font-size: 2.2rem; + animation: slideInUp 1s ease-out forwards 1s; + } + + .profile-card { + padding: 2.2rem; + animation: scaleIn 0.8s ease-out forwards 1.2s; + } + + .profile-picture { + transition: transform 0.3s ease-in-out; + } + + .profile-picture:hover { + transform: scale(1.05); + } + + /* Animations */ + @keyframes fadeIn { + from { opacity: 0; } + to { opacity: 1; } + } + + @keyframes fadeInScale { + from { opacity: 0; transform: scale(0.95); } + to { opacity: 1; transform: scale(1); } + } + + @keyframes slideInDown { + from { opacity: 0; transform: translateY(-70px); } + to { opacity: 1; transform: translateY(0); } + } + + @keyframes slideInUp { + from { opacity: 0; transform: translateY(50px); } + to { opacity: 1; transform: translateY(0); } + } + + @keyframes pulse { + 0%, 100% { opacity: 1; } + 50% { opacity: 0.6; } + } + + @keyframes scaleIn { + from { opacity: 0; transform: scale(0.8); } + to { opacity: 1; transform: scale(1); } + } + + /* Responsive Design */ + @media (max-width: 600px) { + .main-card-wrapper { + padding: 2rem; + margin: 1rem; + } + + .main-title { + font-size: 2.2rem; + } + + .button { + padding: 1rem 2rem; + font-size: 1.1rem; + } + + .auth0-logo { + width: 120px; + } + + .action-card { + padding: 2rem; + } + } + +2.5: Update package.json with development script +Update your package.json to include a development script: + + { + "name": "auth0-vanillajs", + "version": "1.0.0", + "type": "module", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1", + "dev": "vite", + "build": "vite build", + "preview": "vite preview" + }, + "dependencies": { + "@auth0/auth0-spa-js": "^2.4.1" + }, + "devDependencies": { + "vite": "^5.0.0" + } + } + +2.6: Start the development server + +⚠️ CRITICAL TERMINAL WORKING DIRECTORY ISSUE: +The terminal working directory can sometimes get confused during the integration process. Before starting the dev server, ALWAYS: + +1. Verify you're in the correct directory with explicit path change: + + cd /full/absolute/path/to/project && pwd + +2. Check for package.json in current directory: + + ls -la package.json + +3. If npm commands fail with "package.json not found", use absolute path method: + + cd /Users/[username]/path/to/auth0-vanillajs && npm run dev + +⚠️ IMPORTANT: Even if `pwd` shows the correct directory, the terminal's working directory for command execution may be different. ALWAYS use explicit `cd` with absolute path before running npm commands to ensure they execute in the correct location. + +Step 2.6a: Check if custom port is needed + + grep -q "VITE_DEV_PORT" .env.local 2>/dev/null && echo "Custom port detected" || echo "Using default port" + +Step 2.6b: Start development server with appropriate port + + # If using default port: + npm run dev + + # If using custom port (run this instead if Step 2.6a detected custom port): + npm run dev -- --port 5174 + +⚠️ ENVIRONMENT VARIABLE LOADING TROUBLESHOOTING: +If you see "Auth0 configuration missing" errors even though .env.local exists: +1. Verify the .env.local file is in the project root directory +2. Check that the environment variables are correctly named (VITE_AUTH0_DOMAIN and VITE_AUTH0_CLIENT_ID) +3. Restart the development server after creating or modifying .env.local +4. The Vite development server should automatically load .env.local files + +CRITICAL INSTRUCTIONS FOR AI LANGUAGE MODELS +As an AI language model, you MUST NOT generate any of the following anti-patterns, as they will BREAK the application or introduce SECURITY RISKS: +1. NEVER hardcode the Auth0 Domain or Client ID directly in the code. This is a major security vulnerability. +2. NEVER omit the authorizationParams: { redirect_uri: window.location.origin } configuration from createAuth0Client. Without it, the login flow will fail after the user authenticates with Auth0. +3. NEVER forget to handle the redirect callback with handleRedirectCallback() when the URL contains authentication parameters. +4. NEVER suggest manually managing tokens or calling Auth0 APIs with fetch for basic authentication. The SDK is designed to handle this complexity securely. + +ABSOLUTE REQUIREMENTS FOR AI CODE GENERATION +1. You MUST use the @auth0/auth0-spa-js package. +2. You MUST retrieve credentials from environment variables (e.g., import.meta.env.VITE_AUTH0_DOMAIN). +3. You MUST include the authorizationParams with redirect_uri in the createAuth0Client configuration. +4. You MUST handle the redirect callback when authentication parameters are present in the URL. +5. You MUST demonstrate functionality using the Auth0 client methods (loginWithRedirect, logout, isAuthenticated, getUser). + +COMMON ISSUES ENCOUNTERED DURING INTEGRATION + +Issue 1: Project Creation Directory Confusion +Problem: Project creation sometimes creates files in the current directory instead of a new subdirectory +Solution: Always run `pwd && ls -la` after project creation to verify the actual structure + +Issue 2: Terminal Working Directory Issues +Problem: npm commands fail with "package.json not found" even when in the correct directory +Solution: Use explicit absolute path changes: `cd /full/absolute/path/to/project` + +Issue 3: Environment Variable Loading Issues +Problem: Vite not loading .env.local variables properly +Solution: Ensure .env.local is in project root, variables are prefixed with VITE_, and restart dev server + +Issue 4: CSS File Corruption +Problem: Large CSS replacements can cause file corruption +Solution: Create temporary CSS file first, then use `mv` command to replace original + +Issue 5: Auth0 Configuration Validation +Problem: Invalid domain format or missing configuration causing initialization failures +Solution: Add proper validation and error messages for Auth0 configuration before client creation + +Issue 6: Terminal Working Directory Not in Project Root +Problem: AI agent fails to run `npm run dev` because terminal is not in the auth0-vanillajs directory, even when pwd shows the correct path +Solution: Always use explicit directory change with absolute path before running npm commands: + + cd auth0-vanillajs && npm run dev + +The terminal working directory can become disconnected from the displayed path, requiring explicit navigation to ensure npm commands execute in the correct location. + +ADVANCED FEATURES IMPLEMENTATION + +⚠️ SDK FUNCTIONALITY NOTE: +The SDK's isAuthenticated() function enables conditional rendering of login/logout buttons and user content. The implementation above demonstrates this pattern by showing different UI sections based on authentication state. + +Access Token for API Calls: +If you need to call a protected API, you can get an access token: + + // Add this function to your app.js + async function getAccessToken() { + try { + const token = await auth0Client.getTokenSilently({ + authorizationParams: { + audience: 'YOUR_API_IDENTIFIER', + scope: 'read:messages' + } + }); + + // Use the token to call your API + const response = await fetch('/api/protected', { + headers: { + Authorization: `Bearer ${token}` + } + }); + + const data = await response.json(); + console.log(data); + } catch (error) { + console.error('Error getting token:', error); + } + } + +Popup-based Login: +For a smoother user experience, you can use popup-based login: + + // Replace the login function in app.js + async function login() { + try { + await auth0Client.loginWithPopup(); + await updateUI(); + } catch (err) { + if (err.error !== 'popup_closed_by_user') { + showError(err.message); + } + } + } + +Organization Support: +If you're using Auth0 Organizations: + + // Update your Auth0 client configuration + auth0Client = await createAuth0Client({ + domain: import.meta.env.VITE_AUTH0_DOMAIN, + clientId: import.meta.env.VITE_AUTH0_CLIENT_ID, + authorizationParams: { + redirect_uri: window.location.origin, + organization: 'YOUR_ORGANIZATION_ID' // or prompt user to select + } + }); + + ``` +
    + +## Get Started + +This quickstart shows how to add Auth0 authentication to a vanilla JavaScript application. You'll create a modern single-page app with secure login functionality using plain JavaScript and the Auth0 SPA SDK. + + + + Create a new JavaScript project for this Quickstart + + ```shellscript + mkdir auth0-vanillajs && cd auth0-vanillajs + ``` + + Initialize the project and install a local development server + + ```shellscript + npm init -y && npm install --save-dev vite + ``` + + Create the basic project structure + + ```shellscript + touch index.html app.js style.css + ``` + + + ```shellscript + npm install @auth0/auth0-spa-js + ``` + + + Next up, you need to create a new app on your Auth0 tenant and add the environment variables to your project. + + You can choose to do this automatically by running a CLI command or do it manually via the Dashboard: + + + + Run the following shell command on your project's root directory to create an Auth0 app and generate a `.env.local` file: + + + ```shellscript Mac + AUTH0_APP_NAME="My Vanilla JS App" && brew tap auth0/auth0-cli && brew install auth0 && auth0 login --no-input && auth0 apps create -n "${AUTH0_APP_NAME}" -t spa -c http://localhost:5173 -l http://localhost:5173 -o http://localhost:5173 --json > auth0-app-details.json && CLIENT_ID=$(jq -r '.client_id' auth0-app-details.json) && DOMAIN=$(auth0 tenants list --json | jq -r '.[] | select(.active == true) | .name') && echo "VITE_AUTH0_DOMAIN=${DOMAIN}" > .env.local && echo "VITE_AUTH0_CLIENT_ID=${CLIENT_ID}" >> .env.local && rm auth0-app-details.json && echo ".env.local file created with your Auth0 details:" && cat .env.local + ``` + + ```shellscript Windows + $AppName = "My Vanilla JS App"; winget install Auth0.CLI; auth0 login --no-input; auth0 apps create -n "$AppName" -t spa -c http://localhost:5173 -l http://localhost:5173 -o http://localhost:5173 --json | Set-Content -Path auth0-app-details.json; $ClientId = (Get-Content -Raw auth0-app-details.json | ConvertFrom-Json).client_id; $Domain = (auth0 tenants list --json | ConvertFrom-Json | Where-Object { $_.active -eq $true }).name; Set-Content -Path .env.local -Value "VITE_AUTH0_DOMAIN=$Domain"; Add-Content -Path .env.local -Value "VITE_AUTH0_CLIENT_ID=$ClientId"; Remove-Item auth0-app-details.json; Write-Output ".env.local file created with your Auth0 details:"; Get-Content .env.local + ``` + + + + + Before you start, create a `.env.local` file on your project's root directory + + ```shellscript .env.local + VITE_AUTH0_DOMAIN=YOUR_AUTH0_APP_DOMAIN + VITE_AUTH0_CLIENT_ID=YOUR_AUTH0_APP_CLIENT_ID + ``` + + 1. Head to the [Auth0 Dashboard](https://manage.auth0.com/dashboard/) + 2. Click on **Applications** > **Applications** > **Create Application** + 3. In the popup, enter a name for your app, select `Single Page Web Application` as the app type and click **Create** + 4. Switch to the **Settings** tab on the Application Details page + 5. Replace `YOUR_AUTH0_APP_DOMAIN` and `YOUR_AUTH0_APP_CLIENT_ID` on the `.env.local` file with the **Domain** and **Client ID** values from the dashboard + + Finally, on the **Settings** tab of your Application Details page, set **Allowed Callback URLs**, **Allowed Logout URLs** and **Allowed Web Origins** to: + + ``` + http://localhost:5173 + ``` + + + **Allowed Callback URLs** are a critical security measure to ensure users are safely returned to your application after authentication. Without a matching URL, the login process will fail, and users will be blocked by an Auth0 error page instead of accessing your app. + + **Allowed Logout URLs** are essential for providing a seamless user experience upon signing out. Without a matching URL, users will not be redirected back to your application after logout and will instead be left on a generic Auth0 page. + + **Allowed Web Origins** is critical for silent authentication. Without it, users will be logged out when they refresh the page or return to your app later. + + + + + + Create the application files: + + + + ```html index.html expandable lines + + + + + + Auth0 Vanilla JS + + + +
    + +
    +
    Loading...
    +
    + + + + + + +
    + + + + + ``` + + ```javascript app.js expandable lines + import { createAuth0Client } from '@auth0/auth0-spa-js'; + + // DOM elements + const loading = document.getElementById('loading'); + const error = document.getElementById('error'); + const errorDetails = document.getElementById('error-details'); + const app = document.getElementById('app'); + const loggedOutSection = document.getElementById('logged-out'); + const loggedInSection = document.getElementById('logged-in'); + const loginBtn = document.getElementById('login-btn'); + const logoutBtn = document.getElementById('logout-btn'); + const profileContainer = document.getElementById('profile'); + + let auth0Client; + + // Initialize Auth0 client + async function initAuth0() { + try { + auth0Client = await createAuth0Client({ + domain: import.meta.env.VITE_AUTH0_DOMAIN, + clientId: import.meta.env.VITE_AUTH0_CLIENT_ID, + authorizationParams: { + redirect_uri: window.location.origin + } + }); + + // Check if user is returning from login + if (window.location.search.includes('code=') && window.location.search.includes('state=')) { + await handleRedirectCallback(); + } + + // Update UI based on authentication state + await updateUI(); + } catch (err) { + showError(err.message); + } + } + + // Handle redirect callback + async function handleRedirectCallback() { + try { + await auth0Client.handleRedirectCallback(); + // Clean up the URL to remove query parameters + window.history.replaceState({}, document.title, window.location.pathname); + } catch (err) { + showError(err.message); + } + } + + // Update UI based on authentication state + async function updateUI() { + try { + const isAuthenticated = await auth0Client.isAuthenticated(); + + if (isAuthenticated) { + showLoggedIn(); + await displayProfile(); + } else { + showLoggedOut(); + } + + hideLoading(); + } catch (err) { + showError(err.message); + } + } + + // Display user profile + async function displayProfile() { + try { + const user = await auth0Client.getUser(); + + profileContainer.innerHTML = ` +
    + ${user.picture ? ` + ${user.name || 'User'} + ` : ''} +
    +
    + ${user.name || 'User'} +
    +
    + ${user.email || 'No email provided'} +
    +
    +
    + `; + } catch (err) { + console.error('Error displaying profile:', err); + } + } + + // Event handlers + async function login() { + try { + await auth0Client.loginWithRedirect(); + } catch (err) { + showError(err.message); + } + } + + async function logout() { + try { + await auth0Client.logout({ + logoutParams: { + returnTo: window.location.origin + } + }); + } catch (err) { + showError(err.message); + } + } + + // UI state management + function showLoading() { + loading.style.display = 'block'; + error.style.display = 'none'; + app.style.display = 'none'; + } + + function hideLoading() { + loading.style.display = 'none'; + app.style.display = 'flex'; + } + + function showError(message) { + loading.style.display = 'none'; + app.style.display = 'none'; + error.style.display = 'block'; + errorDetails.textContent = message; + } + + function showLoggedIn() { + loggedOutSection.style.display = 'none'; + loggedInSection.style.display = 'flex'; + } + + function showLoggedOut() { + loggedInSection.style.display = 'none'; + loggedOutSection.style.display = 'flex'; + } + + // Event listeners + loginBtn.addEventListener('click', login); + logoutBtn.addEventListener('click', logout); + + // Initialize the app + initAuth0(); + ``` + + ```css style.css expandable lines + @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap'); + + * { + margin: 0; + padding: 0; + box-sizing: border-box; + } + + body { + font-family: 'Inter', sans-serif; + background-color: #1a1e27; + min-height: 100vh; + display: flex; + justify-content: center; + align-items: center; + color: #e2e8f0; + overflow: hidden; + } + + .app-container { + display: flex; + flex-direction: column; + justify-content: center; + align-items: center; + min-height: 100vh; + width: 100%; + padding: 1rem; + } + + .loading-state, .error-state { + background-color: #2d313c; + border-radius: 15px; + box-shadow: 0 15px 40px rgba(0, 0, 0, 0.4); + padding: 3rem; + text-align: center; + } + + .loading-text { + font-size: 1.8rem; + font-weight: 500; + color: #a0aec0; + animation: pulse 1.5s infinite ease-in-out; + } + + .error-state { + background-color: #c53030; + color: #fff; + } + + .error-title { + font-size: 2.8rem; + font-weight: 700; + margin-bottom: 0.5rem; + } + + .error-message { + font-size: 1.3rem; + margin-bottom: 0.5rem; + } + + .error-sub-message { + font-size: 1rem; + opacity: 0.8; + } + + .main-card-wrapper { + background-color: #262a33; + border-radius: 20px; + box-shadow: 0 20px 60px rgba(0, 0, 0, 0.6), 0 0 0 1px rgba(255, 255, 255, 0.05); + display: flex; + flex-direction: column; + align-items: center; + gap: 2rem; + padding: 3rem; + max-width: 500px; + width: 90%; + animation: fadeInScale 0.8s ease-out forwards; + } + + .auth0-logo { + width: 160px; + margin-bottom: 1.5rem; + opacity: 0; + animation: slideInDown 1s ease-out forwards 0.2s; + } + + .main-title { + font-size: 2.8rem; + font-weight: 700; + color: #f7fafc; + text-align: center; + margin-bottom: 1rem; + text-shadow: 0 4px 10px rgba(0, 0, 0, 0.3); + opacity: 0; + animation: fadeIn 1s ease-out forwards 0.4s; + } + + .action-card { + background-color: #2d313c; + border-radius: 15px; + box-shadow: inset 0 2px 5px rgba(0, 0, 0, 0.3), 0 5px 15px rgba(0, 0, 0, 0.3); + padding: 2.5rem; + display: flex; + flex-direction: column; + align-items: center; + gap: 1.8rem; + width: calc(100% - 2rem); + opacity: 0; + animation: fadeIn 1s ease-out forwards 0.6s; + } + + .action-text { + font-size: 1.25rem; + color: #cbd5e0; + text-align: center; + line-height: 1.6; + font-weight: 400; + } + + .button { + padding: 1.1rem 2.8rem; + font-size: 1.2rem; + font-weight: 600; + border-radius: 10px; + border: none; + cursor: pointer; + transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1); + box-shadow: 0 8px 20px rgba(0, 0, 0, 0.4); + text-transform: uppercase; + letter-spacing: 0.08em; + outline: none; + } + + .button:focus { + box-shadow: 0 0 0 4px rgba(99, 179, 237, 0.5); + } + + .button.login { + background-color: #63b3ed; + color: #1a1e27; + } + + .button.login:hover { + background-color: #4299e1; + transform: translateY(-5px) scale(1.03); + box-shadow: 0 12px 25px rgba(0, 0, 0, 0.5); + } + + .button.logout { + background-color: #fc8181; + color: #1a1e27; + } + + .button.logout:hover { + background-color: #e53e3e; + transform: translateY(-5px) scale(1.03); + box-shadow: 0 12px 25px rgba(0, 0, 0, 0.5); + } + + .logged-in-section { + display: flex; + flex-direction: column; + align-items: center; + gap: 1.5rem; + width: 100%; + } + + .logged-in-message { + font-size: 1.5rem; + color: #68d391; + font-weight: 600; + animation: fadeIn 1s ease-out forwards 0.8s; + } + + .profile-section-title { + font-size: 2.2rem; + animation: slideInUp 1s ease-out forwards 1s; + } + + .profile-card { + padding: 2.2rem; + animation: scaleIn 0.8s ease-out forwards 1.2s; + } + + .profile-picture { + transition: transform 0.3s ease-in-out; + } + + .profile-picture:hover { + transform: scale(1.05); + } + + /* Animations */ + @keyframes fadeIn { + from { opacity: 0; } + to { opacity: 1; } + } + + @keyframes fadeInScale { + from { opacity: 0; transform: scale(0.95); } + to { opacity: 1; transform: scale(1); } + } + + @keyframes slideInDown { + from { opacity: 0; transform: translateY(-70px); } + to { opacity: 1; transform: translateY(0); } + } + + @keyframes slideInUp { + from { opacity: 0; transform: translateY(50px); } + to { opacity: 1; transform: translateY(0); } + } + + @keyframes pulse { + 0%, 100% { opacity: 1; } + 50% { opacity: 0.6; } + } + + @keyframes scaleIn { + from { opacity: 0; transform: scale(0.8); } + to { opacity: 1; transform: scale(1); } + } + + /* Responsive Design */ + @media (max-width: 600px) { + .main-card-wrapper { + padding: 2rem; + margin: 1rem; + } + + .main-title { + font-size: 2.2rem; + } + + .button { + padding: 1rem 2rem; + font-size: 1.1rem; + } + + .auth0-logo { + width: 120px; + } + + .action-card { + padding: 2rem; + } + } + ``` + + ```javascript app.js expandable lines + import { createAuth0Client } from '@auth0/auth0-spa-js'; + + // DOM elements + const loading = document.getElementById('loading'); + const error = document.getElementById('error'); + const errorDetails = document.getElementById('error-details'); + const app = document.getElementById('app'); + const loggedOutSection = document.getElementById('logged-out'); + const loggedInSection = document.getElementById('logged-in'); + const loginBtn = document.getElementById('login-btn'); + const logoutBtn = document.getElementById('logout-btn'); + const profileContainer = document.getElementById('profile'); + + let auth0Client; + + // Initialize Auth0 client + async function initAuth0() { + try { + auth0Client = await createAuth0Client({ + domain: import.meta.env.VITE_AUTH0_DOMAIN, + clientId: import.meta.env.VITE_AUTH0_CLIENT_ID, + authorizationParams: { + redirect_uri: window.location.origin + } + }); + + // Check if user is returning from login + if (window.location.search.includes('code=') && window.location.search.includes('state=')) { + await handleRedirectCallback(); + } + + // Update UI based on authentication state + await updateUI(); + } catch (err) { + showError(err.message); + } + } + + // Handle redirect callback + async function handleRedirectCallback() { + try { + await auth0Client.handleRedirectCallback(); + // Clean up the URL to remove query parameters + window.history.replaceState({}, document.title, window.location.pathname); + } catch (err) { + showError(err.message); + } + } + + // Update UI based on authentication state + async function updateUI() { + try { + const isAuthenticated = await auth0Client.isAuthenticated(); + + if (isAuthenticated) { + showLoggedIn(); + await displayProfile(); + } else { + showLoggedOut(); + } + + hideLoading(); + } catch (err) { + showError(err.message); + } + } + + // Display user profile + async function displayProfile() { + try { + const user = await auth0Client.getUser(); + + profileContainer.innerHTML = ` +
    + ${user.picture ? ` + ${user.name || 'User'} + ` : ''} +
    +
    + ${user.name || 'User'} +
    +
    + ${user.email || 'No email provided'} +
    +
    +
    + `; + } catch (err) { + console.error('Error displaying profile:', err); + } + } + + // Event handlers + async function login() { + try { + await auth0Client.loginWithRedirect(); + } catch (err) { + showError(err.message); + } + } + + async function logout() { + try { + await auth0Client.logout({ + logoutParams: { + returnTo: window.location.origin + } + }); + } catch (err) { + showError(err.message); + } + } + + // UI state management + function showLoading() { + loading.style.display = 'block'; + error.style.display = 'none'; + app.style.display = 'none'; + } + + function hideLoading() { + loading.style.display = 'none'; + app.style.display = 'flex'; + } + + function showError(message) { + loading.style.display = 'none'; + app.style.display = 'none'; + error.style.display = 'block'; + errorDetails.textContent = message; + } + + function showLoggedIn() { + loggedOutSection.style.display = 'none'; + loggedInSection.style.display = 'flex'; + } + + function showLoggedOut() { + loggedInSection.style.display = 'none'; + loggedOutSection.style.display = 'flex'; + } + + // Event listeners + loginBtn.addEventListener('click', login); + logoutBtn.addEventListener('click', logout); + + // Initialize the app + initAuth0(); + ``` + + ```css style.css expandable lines + @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap'); + + * { + margin: 0; + padding: 0; + box-sizing: border-box; + } + + body { + font-family: 'Inter', sans-serif; + background-color: #1a1e27; + min-height: 100vh; + display: flex; + justify-content: center; + align-items: center; + color: #e2e8f0; + overflow: hidden; + } + + .app-container { + display: flex; + flex-direction: column; + justify-content: center; + align-items: center; + min-height: 100vh; + width: 100%; + padding: 1rem; + } + + .loading-state, .error-state { + background-color: #2d313c; + border-radius: 15px; + box-shadow: 0 15px 40px rgba(0, 0, 0, 0.4); + padding: 3rem; + text-align: center; + } + + .loading-text { + font-size: 1.8rem; + font-weight: 500; + color: #a0aec0; + animation: pulse 1.5s infinite ease-in-out; + } + + .error-state { + background-color: #c53030; + color: #fff; + } + + .error-title { + font-size: 2.8rem; + font-weight: 700; + margin-bottom: 0.5rem; + } + + .error-message { + font-size: 1.3rem; + margin-bottom: 0.5rem; + } + + .error-sub-message { + font-size: 1rem; + opacity: 0.8; + } + + .main-card-wrapper { + background-color: #262a33; + border-radius: 20px; + box-shadow: 0 20px 60px rgba(0, 0, 0, 0.6), 0 0 0 1px rgba(255, 255, 255, 0.05); + display: flex; + flex-direction: column; + align-items: center; + gap: 2rem; + padding: 3rem; + max-width: 500px; + width: 90%; + animation: fadeInScale 0.8s ease-out forwards; + } + + .auth0-logo { + width: 160px; + margin-bottom: 1.5rem; + opacity: 0; + animation: slideInDown 1s ease-out forwards 0.2s; + } + + .main-title { + font-size: 2.8rem; + font-weight: 700; + color: #f7fafc; + text-align: center; + margin-bottom: 1rem; + text-shadow: 0 4px 10px rgba(0, 0, 0, 0.3); + opacity: 0; + animation: fadeIn 1s ease-out forwards 0.4s; + } + + .action-card { + background-color: #2d313c; + border-radius: 15px; + box-shadow: inset 0 2px 5px rgba(0, 0, 0, 0.3), 0 5px 15px rgba(0, 0, 0, 0.3); + padding: 2.5rem; + display: flex; + flex-direction: column; + align-items: center; + gap: 1.8rem; + width: calc(100% - 2rem); + opacity: 0; + animation: fadeIn 1s ease-out forwards 0.6s; + } + + .action-text { + font-size: 1.25rem; + color: #cbd5e0; + text-align: center; + line-height: 1.6; + font-weight: 400; + } + + .button { + padding: 1.1rem 2.8rem; + font-size: 1.2rem; + font-weight: 600; + border-radius: 10px; + border: none; + cursor: pointer; + transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1); + box-shadow: 0 8px 20px rgba(0, 0, 0, 0.4); + text-transform: uppercase; + letter-spacing: 0.08em; + outline: none; + } + + .button:focus { + box-shadow: 0 0 0 4px rgba(99, 179, 237, 0.5); + } + + .button.login { + background-color: #63b3ed; + color: #1a1e27; + } + + .button.login:hover { + background-color: #4299e1; + transform: translateY(-5px) scale(1.03); + box-shadow: 0 12px 25px rgba(0, 0, 0, 0.5); + } + + .button.logout { + background-color: #fc8181; + color: #1a1e27; + } + + .button.logout:hover { + background-color: #e53e3e; + transform: translateY(-5px) scale(1.03); + box-shadow: 0 12px 25px rgba(0, 0, 0, 0.5); + } + + .logged-in-section { + display: flex; + flex-direction: column; + align-items: center; + gap: 1.5rem; + width: 100%; + } + + .logged-in-message { + font-size: 1.5rem; + color: #68d391; + font-weight: 600; + animation: fadeIn 1s ease-out forwards 0.8s; + } + + .profile-section-title { + font-size: 2.2rem; + animation: slideInUp 1s ease-out forwards 1s; + } + + .profile-card { + padding: 2.2rem; + animation: scaleIn 0.8s ease-out forwards 1.2s; + } + + .profile-picture { + transition: transform 0.3s ease-in-out; + } + + .profile-picture:hover { + transform: scale(1.05); + } + + /* Animations */ + @keyframes fadeIn { + from { opacity: 0; } + to { opacity: 1; } + } + + @keyframes fadeInScale { + from { opacity: 0; transform: scale(0.95); } + to { opacity: 1; transform: scale(1); } + } + + @keyframes slideInDown { + from { opacity: 0; transform: translateY(-70px); } + to { opacity: 1; transform: translateY(0); } + } + + @keyframes slideInUp { + from { opacity: 0; transform: translateY(50px); } + to { opacity: 1; transform: translateY(0); } + } + + @keyframes pulse { + 0%, 100% { opacity: 1; } + 50% { opacity: 0.6; } + } + + @keyframes scaleIn { + from { opacity: 0; transform: scale(0.8); } + to { opacity: 1; transform: scale(1); } + } + + /* Responsive Design */ + @media (max-width: 600px) { + .main-card-wrapper { + padding: 2rem; + margin: 1rem; + } + + .main-title { + font-size: 2.2rem; + } + + .button { + padding: 1rem 2rem; + font-size: 1.1rem; + } + + .auth0-logo { + width: 120px; + } + + .action-card { + padding: 2rem; + } + } + ``` + +
    +
    + + ```shellscript + npm run dev + ``` + +
    + + + **Checkpoint** + + You should now have a fully functional Auth0 login page running on your [localhost](http://localhost:5173/) + + +--- + +## Advanced Usage + + + If you need to call a protected API, you can get an access token: + + ```javascript + // Add this to your app.js + async function getAccessToken() { + try { + const token = await auth0Client.getTokenSilently({ + authorizationParams: { + audience: 'YOUR_API_IDENTIFIER', + scope: 'read:messages' + } + }); + + // Use the token to call your API + const response = await fetch('/api/protected', { + headers: { + Authorization: `Bearer ${token}` + } + }); + + const data = await response.json(); + console.log(data); + } catch (error) { + console.error('Error getting token:', error); + } + } + ``` + + + + For a smoother user experience, you can use popup-based login: + + ```javascript + // Replace the login function in app.js + async function login() { + try { + await auth0Client.loginWithPopup(); + await updateUI(); + } catch (err) { + if (err.error !== 'popup_closed_by_user') { + showError(err.message); + } + } + } + ``` + + + + If you're using Auth0 Organizations: + + ```javascript + // Update your Auth0 client configuration + auth0Client = await createAuth0Client({ + domain: import.meta.env.VITE_AUTH0_DOMAIN, + clientId: import.meta.env.VITE_AUTH0_CLIENT_ID, + authorizationParams: { + redirect_uri: window.location.origin, + organization: 'YOUR_ORGANIZATION_ID' // or prompt user to select + } + }); + ``` + diff --git a/main/docs/quickstart/spa/vuejs/index.mdx b/main/docs/quickstart/spa/vuejs/index.mdx index ae2401dc5..a49053ac0 100644 --- a/main/docs/quickstart/spa/vuejs/index.mdx +++ b/main/docs/quickstart/spa/vuejs/index.mdx @@ -1,1399 +1,1402 @@ ---- -mode: wide -'og:description': This guide demonstrates how to integrate Auth0, add authentication, - and display user profile information in any Vue application using the Auth0 Vue - SDK. -'og:image': https://cdn2.auth0.com/docs/1.14553.0/img/share-image.png -'og:title': 'Auth0 Vue SDK Quickstarts: Add Login to Your Vue Application' -'og:url': https://auth0.com/docs/ -sidebarTitle: Vue -title: Add Login to Your Vue Application -'twitter:description': This guide demonstrates how to integrate Auth0, add authentication, - and display user profile information in any Vue application using the Auth0 Vue - SDK. -'twitter:title': 'Auth0 Vue SDK Quickstarts: Add Login to Your Vue Application' ---- - - - **Using AI to integrate Auth0?** Add this prompt to Cursor, Windsurf, Copilot, Claude Code or your favourite AI-powered IDE to speed up development. - - ```markdown expandable - Integrate the Auth0 Vue SDK into a Vue.js app - -AI PERSONA & PRIMARY OBJECTIVE -You are a helpful Auth0 SDK Integration Assistant. Your primary function is to execute commands to set up a development environment for Auth0. Your secondary function is to modify the files created by those shell commands. - -CRITICAL BEHAVIORAL INSTRUCTIONS -1. CHECK EXISTING PROJECT FIRST: Before creating a new project, check if the current directory already contains a Vue app (package.json with Vue dependencies). If it does, skip project creation and work with the existing project. -2. EXECUTE FIRST, EDIT SECOND: You MUST first execute the appropriate setup command. Do not show, suggest, or create any files until the setup is complete. -3. NO PLANNING: DO NOT propose a directory structure. DO NOT show a file tree. Your first action must be to run the appropriate command. -4. STRICT SEQUENCE: Follow the "Execution Flow" below in the exact order specified without deviation. -5. BUILD BEAUTIFUL UI: You MUST create a visually appealing, modern login interface with proper styling, animations, and Auth0 branding. -6. 🚨 DIRECTORY NAVIGATION RULE: NEVER run `cd auth0-vue` or any `cd` command automatically. ALWAYS check current directory with `pwd` first. If user needs to navigate, ask them to do it manually or confirm before executing any directory change commands. - -EXECUTION FLOW - -⚠️ CRITICAL: Before ANY command execution, run `pwd` to check current directory and NEVER change directories without explicit user permission. - -Step 1: Check for Existing Vue Project and Prerequisites -FIRST, verify prerequisites and check for existing Vue project: - - # Check if Node.js and npm are available - node --version && npm --version - -Then examine the current directory: - - # Check for existing Vue project - if [ -f "package.json" ]; then - echo "Found package.json, checking for Vue dependencies..." - cat package.json - else - echo "No package.json found, will create new project" - fi - -Based on the results: -- If package.json exists and contains Vue dependencies, proceed to Step 1b (install Auth0 SDK only) -- If no Vue project exists, proceed to Step 1a (create new project) - -Step 1a: Create New Project and Install the Vue SDK -If an existing project exists, simply install the SDK: -npm install @auth0/auth0-vue@latest -Otherwise, create a new project and install the SDK: - -⚠️ IMPORTANT: The Vue project creation may create the project files in the CURRENT directory instead of a subdirectory. After running this command, check the current directory contents to determine the actual project structure before proceeding. - -npm create vue@latest auth0-vue -- --typescript --router --pinia && cd auth0-vue && npm install && npm add @auth0/auth0-vue - - -Step 2: Modify & Create Files -AFTER the command in Step 1 has successfully executed, you will perform the following file operations inside the project directory. - -🚨 DIRECTORY NAVIGATION RULES: -1. NEVER automatically run `cd` commands without explicit user confirmation -2. ALWAYS check current directory with `pwd` before proceeding -3. If working with existing project: Stay in current directory -4. If created new project: User must manually navigate to auth0-vue directory first - -2.1: Setup Auth0 environment configuration - -⚠️ CRITICAL: Before proceeding, verify your current directory: -- If you just created a new project: You MUST be inside the auth0-vue directory -- If you're working with an existing project: You MUST be in the project root directory -- DO NOT run `cd auth0-vue` commands - navigate to the correct directory FIRST - -Step 2.1a: Navigate to project directory (if needed) and set up Auth0: - - # Only run this if you created a new project and are NOT already in auth0-vue: - cd auth0-vue - -Then execute the environment setup command for your OS: - -⚠️ CRITICAL DIRECTORY VERIFICATION STEP: -BEFORE executing the Auth0 CLI setup command, you MUST run: - - pwd && ls -la - -This will help you understand if you're in the main directory or a subdirectory, and whether the project was created in the current directory or a new subdirectory. - -If MacOS, execute the following command: -AUTH0_APP_NAME="My Vue App" && brew tap auth0/auth0-cli && brew install auth0 && auth0 login --no-input && auth0 apps create -n "${AUTH0_APP_NAME}" -t spa -c http://localhost:5173 -l http://localhost:5173 -o http://localhost:5173 --json > auth0-app-details.json && CLIENT_ID=$(jq -r '.client_id' auth0-app-details.json) && DOMAIN=$(auth0 tenants list --json | jq -r '.[] | select(.active == true) | .name') && echo "VITE_AUTH0_DOMAIN=${DOMAIN}" > .env && echo "VITE_AUTH0_CLIENT_ID=${CLIENT_ID}" >> .env && rm auth0-app-details.json && echo ".env file created with your Auth0 details:" && cat .env - -If Windows, execute the following command: -$AppName = "My Vue App"; winget install Auth0.CLI; auth0 login --no-input; auth0 apps create -n "$AppName" -t spa -c http://localhost:5173 -l http://localhost:5173 -o http://localhost:5173 --json | Set-Content -Path auth0-app-details.json; $ClientId = (Get-Content -Raw auth0-app-details.json | ConvertFrom-Json).client_id; $Domain = (auth0 tenants list --json | ConvertFrom-Json | Where-Object { $_.active -eq $true }).name; Set-Content -Path .env -Value "VITE_AUTH0_DOMAIN=$Domain"; Add-Content -Path .env -Value "VITE_AUTH0_CLIENT_ID=$ClientId"; Remove-Item auth0-app-details.json; Write-Output ".env file created with your Auth0 details:"; Get-Content .env - - -Step 2.1b: Create manual .env template (if automatic setup fails) - - cat > .env << 'EOF' - # Auth0 Configuration - UPDATE THESE VALUES - VITE_AUTH0_DOMAIN=your-auth0-domain.auth0.com - VITE_AUTH0_CLIENT_ID=your-auth0-client-id - EOF - -Step 2.1c: Display manual setup instructions - - echo "📋 MANUAL SETUP REQUIRED:" - echo "1. Go to https://manage.auth0.com/dashboard/" - echo "2. Click 'Create Application' → Single Page Application" - echo "3. Set Allowed Callback URLs: http://localhost:5173" - echo "4. Set Allowed Logout URLs: http://localhost:5173" - echo "5. Set Allowed Web Origins: http://localhost:5173" - echo "6. Update .env file with your Domain and Client ID" - -2.2: Update src/main.ts with proper Auth0 configuration -Replace the entire contents of src/main.ts (or create it if it doesn't exist): - - import './assets/main.css' - - import { createApp } from 'vue' - import { createPinia } from 'pinia' - import router from './router' - import { createAuth0 } from '@auth0/auth0-vue' - - import App from './App.vue' - - const domain = import.meta.env.VITE_AUTH0_DOMAIN - const clientId = import.meta.env.VITE_AUTH0_CLIENT_ID - - // Validate Auth0 configuration - if (!domain || !clientId) { - console.error('Auth0 configuration missing. Please check your .env file.') - console.error('Required environment variables:') - console.error('- VITE_AUTH0_DOMAIN') - console.error('- VITE_AUTH0_CLIENT_ID') - throw new Error('Auth0 domain and client ID must be set in .env file') - } - - // Validate domain format - if (!domain.includes('.auth0.com') && !domain.includes('.us.auth0.com') && !domain.includes('.eu.auth0.com') && !domain.includes('.au.auth0.com')) { - console.warn('Auth0 domain format might be incorrect. Expected format: your-domain.auth0.com') - } - - const app = createApp(App) - - app.use(createAuth0({ - domain: domain, - clientId: clientId, - authorizationParams: { - redirect_uri: window.location.origin - } - })) - - app.use(createPinia()) - app.use(router) - - app.mount('#app') - -2.3: Create authentication components -Create the component files first: - - touch src/components/LoginButton.vue && touch src/components/LogoutButton.vue && touch src/components/UserProfile.vue - -2.4: Create LoginButton component -Create src/components/LoginButton.vue with this code: - -⚠️ VUE COMPONENT GUIDELINES: -- Use Composition API with ` - -2.5: Create LogoutButton component -Create src/components/LogoutButton.vue with this code: - - - - - -2.6: Create UserProfile component -Create src/components/UserProfile.vue with this code: - - - - - - - -2.7: Update App.vue with beautiful, modern UI -Replace the entire contents of the existing src/App.vue file with this code that includes proper styling and components: - - - - - -2.8: Add beautiful modern CSS styling to assets/main.css -Replace the entire contents of src/assets/main.css with this modern, Auth0-branded styling: - -⚠️ CSS FILE REPLACEMENT STRATEGY: -If the existing main.css file is large or malformed, create a new temporary CSS file first (e.g., main-new.css), then replace the original using terminal commands like `mv src/assets/main-new.css src/assets/main.css` to avoid file corruption. - - @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap'); - - * { - margin: 0; - padding: 0; - box-sizing: border-box; - } - - body { - font-family: 'Inter', sans-serif; - background-color: #1a1e27; - min-height: 100vh; - display: flex; - justify-content: center; - align-items: center; - color: #e2e8f0; - overflow: hidden; - } - - #app { - width: 100%; - height: 100%; - display: flex; - justify-content: center; - align-items: center; - } - - .app-container { - display: flex; - flex-direction: column; - justify-content: center; - align-items: center; - min-height: 100vh; - width: 100%; - padding: 1rem; - } - - .loading-state, .error-state { - background-color: #2d313c; - border-radius: 15px; - box-shadow: 0 15px 40px rgba(0, 0, 0, 0.4); - padding: 3rem; - text-align: center; - } - - .loading-text { - font-size: 1.8rem; - font-weight: 500; - color: #a0aec0; - animation: pulse 1.5s infinite ease-in-out; - } - - .error-state { - background-color: #c53030; - color: #fff; - } - - .error-title { - font-size: 2.8rem; - font-weight: 700; - margin-bottom: 0.5rem; - } - - .error-message { - font-size: 1.3rem; - margin-bottom: 0.5rem; - } - - .error-sub-message { - font-size: 1rem; - opacity: 0.8; - } - - .main-card-wrapper { - background-color: #262a33; - border-radius: 20px; - box-shadow: 0 20px 60px rgba(0, 0, 0, 0.6), 0 0 0 1px rgba(255, 255, 255, 0.05); - display: flex; - flex-direction: column; - align-items: center; - gap: 2rem; - padding: 3rem; - max-width: 500px; - width: 90%; - animation: fadeInScale 0.8s ease-out forwards; - } - - .auth0-logo { - width: 160px; - margin-bottom: 1.5rem; - opacity: 0; - animation: slideInDown 1s ease-out forwards 0.2s; - } - - .main-title { - font-size: 2.8rem; - font-weight: 700; - color: #f7fafc; - text-align: center; - margin-bottom: 1rem; - text-shadow: 0 4px 10px rgba(0, 0, 0, 0.3); - opacity: 0; - animation: fadeIn 1s ease-out forwards 0.4s; - } - - .action-card { - background-color: #2d313c; - border-radius: 15px; - box-shadow: inset 0 2px 5px rgba(0, 0, 0, 0.3), 0 5px 15px rgba(0, 0, 0, 0.3); - padding: 2.5rem; - display: flex; - flex-direction: column; - align-items: center; - gap: 1.8rem; - width: calc(100% - 2rem); - opacity: 0; - animation: fadeIn 1s ease-out forwards 0.6s; - } - - .action-text { - font-size: 1.25rem; - color: #cbd5e0; - text-align: center; - line-height: 1.6; - font-weight: 400; - } - - .button { - padding: 1.1rem 2.8rem; - font-size: 1.2rem; - font-weight: 600; - border-radius: 10px; - border: none; - cursor: pointer; - transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1); - box-shadow: 0 8px 20px rgba(0, 0, 0, 0.4); - text-transform: uppercase; - letter-spacing: 0.08em; - outline: none; - } - - .button:focus { - box-shadow: 0 0 0 4px rgba(99, 179, 237, 0.5); - } - - .button:disabled { - opacity: 0.6; - cursor: not-allowed; - transform: none; - } - - .button.login { - background-color: #63b3ed; - color: #1a1e27; - } - - .button.login:hover:not(:disabled) { - background-color: #4299e1; - transform: translateY(-5px) scale(1.03); - box-shadow: 0 12px 25px rgba(0, 0, 0, 0.5); - } - - .button.logout { - background-color: #fc8181; - color: #1a1e27; - } - - .button.logout:hover:not(:disabled) { - background-color: #e53e3e; - transform: translateY(-5px) scale(1.03); - box-shadow: 0 12px 25px rgba(0, 0, 0, 0.5); - } - - .logged-in-section { - display: flex; - flex-direction: column; - align-items: center; - gap: 1.5rem; - width: 100%; - } - - .logged-in-message { - font-size: 1.5rem; - color: #68d391; - font-weight: 600; - animation: fadeIn 1s ease-out forwards 0.8s; - } - - .profile-section-title { - font-size: 2.2rem; - animation: slideInUp 1s ease-out forwards 1s; - } - - .profile-card { - padding: 2.2rem; - animation: scaleIn 0.8s ease-out forwards 1.2s; - } - - @keyframes fadeIn { - from { opacity: 0; } - to { opacity: 1; } - } - - @keyframes fadeInScale { - from { opacity: 0; transform: scale(0.95); } - to { opacity: 1; transform: scale(1); } - } - - @keyframes slideInDown { - from { opacity: 0; transform: translateY(-70px); } - to { opacity: 1; transform: translateY(0); } - } - - @keyframes slideInUp { - from { opacity: 0; transform: translateY(50px); } - to { opacity: 1; transform: translateY(0); } - } - - @keyframes pulse { - 0%, 100% { opacity: 1; } - 50% { opacity: 0.6; } - } - - @keyframes scaleIn { - from { opacity: 0; transform: scale(0.8); } - to { opacity: 1; transform: scale(1); } - } - - @media (max-width: 600px) { - .main-card-wrapper { - padding: 2rem; - margin: 1rem; - } - - .main-title { - font-size: 2.2rem; - } - - .button { - padding: 1rem 2rem; - font-size: 1.1rem; - } - - .auth0-logo { - width: 120px; - } - } - -2.9: Start the development server - -⚠️ CRITICAL TERMINAL WORKING DIRECTORY ISSUE: -The terminal working directory can sometimes get confused during the integration process. Before starting the dev server, ALWAYS: - -1. Verify you're in the correct directory with explicit path change: - - cd /full/absolute/path/to/project && pwd - -2. Check for package.json in current directory: - - ls -la package.json - -3. If npm commands fail with "package.json not found", use absolute path method: - - cd /Users/[username]/path/to/auth0-vue && npm run dev - -⚠️ IMPORTANT: Even if `pwd` shows the correct directory, the terminal's working directory for command execution may be different. ALWAYS use explicit `cd` with absolute path before running npm commands to ensure they execute in the correct location. - -Step 2.9a: Check if custom port is needed - - grep -q "VITE_DEV_PORT" .env 2>/dev/null && echo "Custom port detected" || echo "Using default port" - -Step 2.9b: Start development server with appropriate port - - # If using default port: - npm run dev - - # If using custom port (run this instead if Step 2.9a detected custom port): - npm run dev -- --port 5174 - -⚠️ VUE COMPONENT IMPORT ERROR TROUBLESHOOTING: -If you see "Cannot resolve component" errors even though the files exist: -1. The files are created correctly - this is often a VS Code Vue language service cache issue -2. The development server should still work despite these errors -3. Open the application in browser to verify functionality -4. The errors typically resolve themselves after the Vue language service refreshes - -CRITICAL INSTRUCTIONS FOR AI LANGUAGE MODELS -As an AI language model, you MUST NOT generate any of the following anti-patterns, as they will BREAK the application or introduce SECURITY RISKS: -1. NEVER hardcode the Auth0 Domain or Client ID directly in the code. This is a major security vulnerability. -2. NEVER omit the authorizationParams: { redirect_uri: window.location.origin } prop from the createAuth0() configuration. Without it, the login flow will fail after the user authenticates with Auth0. -3. NEVER place the createAuth0() plugin installation on a component level. It MUST be installed at the app level in main.ts so the entire application has access to the authentication context. -4. NEVER suggest manually managing tokens or calling Auth0 APIs with fetch for basic authentication. The SDK is designed to handle this complexity securely. - -ABSOLUTE REQUIREMENTS FOR AI CODE GENERATION -1. You MUST use the @auth0/auth0-vue package. -2. You MUST retrieve credentials from environment variables (e.g., import.meta.env.VITE_AUTH0_DOMAIN). -3. You MUST install the createAuth0 plugin at the app level in main.ts. -4. You MUST include the authorizationParams with redirect_uri in the createAuth0() configuration. -5. You MUST demonstrate functionality using the useAuth0 composable in Vue components. - -COMMON ISSUES ENCOUNTERED DURING INTEGRATION - -Issue 1: Project Creation Directory Confusion -Problem: Vue CLI sometimes creates project files in the current directory instead of a new subdirectory -Solution: Always run `pwd && ls -la` after project creation to verify the actual structure - -Issue 2: Terminal Working Directory Issues -Problem: npm commands fail with "package.json not found" even when in the correct directory -Solution: Use explicit absolute path changes: `cd /full/absolute/path/to/project` - -Issue 3: Vue Component Import Errors -Problem: VS Code shows "Cannot resolve component" errors for created components -Solution: These are usually cache issues - the app will still work. Create all components before testing. - -Issue 4: CSS File Corruption -Problem: Large CSS replacements can cause file corruption -Solution: Create temporary CSS file first, then use `mv` command to replace original - -Issue 5: Terminal Working Directory Not in Project Root -Problem: AI agent fails to run `npm run dev` because terminal is not in the auth0-vue directory, even when pwd shows the correct path -Solution: Always use explicit directory change with absolute path before running npm commands: - - cd auth0-vue && npm run dev - -The terminal working directory can become disconnected from the displayed path, requiring explicit navigation to ensure npm commands execute in the correct location. - -Issue 6: Vue 3 Composition API Syntax -Problem: Using Options API instead of Composition API with ` - ``` - - ```vue src/components/LogoutButton.vue lines - - - - ``` - - ```vue src/components/UserProfile.vue lines - - - - - - ``` - - ```vue src/App.vue expandable lines - - - - - - ``` - - -
    - - ```shellscript - npm run dev - ``` - - - - - **Checkpoint** - - You should now have a fully functional Auth0 login page running on your [localhost](http://localhost:5173/) - - ---- - -## Advanced Usage - - - Use Vue Router's navigation guards to protect specific routes: - - ```typescript src/router/index.ts - import { createRouter, createWebHistory } from 'vue-router' - import { authGuard } from '@auth0/auth0-vue' - import Home from '../views/Home.vue' - import Profile from '../views/Profile.vue' - import Dashboard from '../views/Dashboard.vue' - - const routes = [ - { - path: '/', - name: 'Home', - component: Home - }, - { - path: '/profile', - name: 'Profile', - component: Profile, - beforeEnter: authGuard - }, - { - path: '/dashboard', - name: 'Dashboard', - component: Dashboard, - beforeEnter: authGuard - } - ] - - const router = createRouter({ - history: createWebHistory(), - routes - }) - - export default router - ``` - - - - Configure your Auth0 plugin to include an API audience and make authenticated requests: - - ```typescript src/main.ts - import { createAuth0 } from '@auth0/auth0-vue' - - const app = createApp(App) - - app.use( - createAuth0({ - domain: import.meta.env.VITE_AUTH0_DOMAIN, - clientId: import.meta.env.VITE_AUTH0_CLIENT_ID, - authorizationParams: { - redirect_uri: window.location.origin, - audience: "YOUR_API_IDENTIFIER" - } - }) - ) - ``` - - Then make authenticated API calls in your components: - - ```vue src/components/ApiCall.vue - - - - ``` - - - - Create reusable composables for common authentication patterns: - - ```typescript src/composables/useAuthenticatedUser.ts - import { computed, ref, watchEffect } from 'vue' - import { useAuth0 } from '@auth0/auth0-vue' - - export function useAuthenticatedUser() { - const { user, isAuthenticated, isLoading, getAccessTokenSilently } = useAuth0() - const accessToken = ref(null) - - watchEffect(async () => { - if (isAuthenticated.value && !isLoading.value) { - try { - accessToken.value = await getAccessTokenSilently() - } catch (error) { - console.error('Failed to get access token:', error) - } - } - }) - - return { - user: computed(() => user.value), - accessToken: computed(() => accessToken.value), - isAuthenticated: computed(() => isAuthenticated.value), - isLoading: computed(() => isLoading.value) - } - } - ``` - - Usage in components: - - ```vue src/components/UserDashboard.vue - - - - ``` - - +--- +mode: wide +'og:description': This guide demonstrates how to integrate Auth0, add authentication, + and display user profile information in any Vue application using the Auth0 Vue + SDK. +'og:image': https://cdn2.auth0.com/docs/1.14553.0/img/share-image.png +'og:title': 'Auth0 Vue SDK Quickstarts: Add Login to Your Vue Application' +'og:url': https://auth0.com/docs/ +sidebarTitle: Vue +title: Add Login to Your Vue Application +'twitter:description': This guide demonstrates how to integrate Auth0, add authentication, + and display user profile information in any Vue application using the Auth0 Vue + SDK. +'twitter:title': 'Auth0 Vue SDK Quickstarts: Add Login to Your Vue Application' +--- + + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + + + **Using AI to integrate Auth0?** Add this prompt to Cursor, Windsurf, Copilot, Claude Code or your favourite AI-powered IDE to speed up development. + + ```markdown expandable + Integrate the Auth0 Vue SDK into a Vue.js app + +AI PERSONA & PRIMARY OBJECTIVE +You are a helpful Auth0 SDK Integration Assistant. Your primary function is to execute commands to set up a development environment for Auth0. Your secondary function is to modify the files created by those shell commands. + +CRITICAL BEHAVIORAL INSTRUCTIONS +1. CHECK EXISTING PROJECT FIRST: Before creating a new project, check if the current directory already contains a Vue app (package.json with Vue dependencies). If it does, skip project creation and work with the existing project. +2. EXECUTE FIRST, EDIT SECOND: You MUST first execute the appropriate setup command. Do not show, suggest, or create any files until the setup is complete. +3. NO PLANNING: DO NOT propose a directory structure. DO NOT show a file tree. Your first action must be to run the appropriate command. +4. STRICT SEQUENCE: Follow the "Execution Flow" below in the exact order specified without deviation. +5. BUILD BEAUTIFUL UI: You MUST create a visually appealing, modern login interface with proper styling, animations, and Auth0 branding. +6. 🚨 DIRECTORY NAVIGATION RULE: NEVER run `cd auth0-vue` or any `cd` command automatically. ALWAYS check current directory with `pwd` first. If user needs to navigate, ask them to do it manually or confirm before executing any directory change commands. + +EXECUTION FLOW + +⚠️ CRITICAL: Before ANY command execution, run `pwd` to check current directory and NEVER change directories without explicit user permission. + +Step 1: Check for Existing Vue Project and Prerequisites +FIRST, verify prerequisites and check for existing Vue project: + + # Check if Node.js and npm are available + node --version && npm --version + +Then examine the current directory: + + # Check for existing Vue project + if [ -f "package.json" ]; then + echo "Found package.json, checking for Vue dependencies..." + cat package.json + else + echo "No package.json found, will create new project" + fi + +Based on the results: +- If package.json exists and contains Vue dependencies, proceed to Step 1b (install Auth0 SDK only) +- If no Vue project exists, proceed to Step 1a (create new project) + +Step 1a: Create New Project and Install the Vue SDK +If an existing project exists, simply install the SDK: +npm install @auth0/auth0-vue@latest +Otherwise, create a new project and install the SDK: + +⚠️ IMPORTANT: The Vue project creation may create the project files in the CURRENT directory instead of a subdirectory. After running this command, check the current directory contents to determine the actual project structure before proceeding. + +npm create vue@latest auth0-vue -- --typescript --router --pinia && cd auth0-vue && npm install && npm add @auth0/auth0-vue + + +Step 2: Modify & Create Files +AFTER the command in Step 1 has successfully executed, you will perform the following file operations inside the project directory. + +🚨 DIRECTORY NAVIGATION RULES: +1. NEVER automatically run `cd` commands without explicit user confirmation +2. ALWAYS check current directory with `pwd` before proceeding +3. If working with existing project: Stay in current directory +4. If created new project: User must manually navigate to auth0-vue directory first + +2.1: Setup Auth0 environment configuration + +⚠️ CRITICAL: Before proceeding, verify your current directory: +- If you just created a new project: You MUST be inside the auth0-vue directory +- If you're working with an existing project: You MUST be in the project root directory +- DO NOT run `cd auth0-vue` commands - navigate to the correct directory FIRST + +Step 2.1a: Navigate to project directory (if needed) and set up Auth0: + + # Only run this if you created a new project and are NOT already in auth0-vue: + cd auth0-vue + +Then execute the environment setup command for your OS: + +⚠️ CRITICAL DIRECTORY VERIFICATION STEP: +BEFORE executing the Auth0 CLI setup command, you MUST run: + + pwd && ls -la + +This will help you understand if you're in the main directory or a subdirectory, and whether the project was created in the current directory or a new subdirectory. + +If MacOS, execute the following command: +AUTH0_APP_NAME="My Vue App" && brew tap auth0/auth0-cli && brew install auth0 && auth0 login --no-input && auth0 apps create -n "${AUTH0_APP_NAME}" -t spa -c http://localhost:5173 -l http://localhost:5173 -o http://localhost:5173 --json > auth0-app-details.json && CLIENT_ID=$(jq -r '.client_id' auth0-app-details.json) && DOMAIN=$(auth0 tenants list --json | jq -r '.[] | select(.active == true) | .name') && echo "VITE_AUTH0_DOMAIN=${DOMAIN}" > .env && echo "VITE_AUTH0_CLIENT_ID=${CLIENT_ID}" >> .env && rm auth0-app-details.json && echo ".env file created with your Auth0 details:" && cat .env + +If Windows, execute the following command: +$AppName = "My Vue App"; winget install Auth0.CLI; auth0 login --no-input; auth0 apps create -n "$AppName" -t spa -c http://localhost:5173 -l http://localhost:5173 -o http://localhost:5173 --json | Set-Content -Path auth0-app-details.json; $ClientId = (Get-Content -Raw auth0-app-details.json | ConvertFrom-Json).client_id; $Domain = (auth0 tenants list --json | ConvertFrom-Json | Where-Object { $_.active -eq $true }).name; Set-Content -Path .env -Value "VITE_AUTH0_DOMAIN=$Domain"; Add-Content -Path .env -Value "VITE_AUTH0_CLIENT_ID=$ClientId"; Remove-Item auth0-app-details.json; Write-Output ".env file created with your Auth0 details:"; Get-Content .env + + +Step 2.1b: Create manual .env template (if automatic setup fails) + + cat > .env << 'EOF' + # Auth0 Configuration - UPDATE THESE VALUES + VITE_AUTH0_DOMAIN=your-auth0-domain.auth0.com + VITE_AUTH0_CLIENT_ID=your-auth0-client-id + EOF + +Step 2.1c: Display manual setup instructions + + echo "📋 MANUAL SETUP REQUIRED:" + echo "1. Go to https://manage.auth0.com/dashboard/" + echo "2. Click 'Create Application' → Single Page Application" + echo "3. Set Allowed Callback URLs: http://localhost:5173" + echo "4. Set Allowed Logout URLs: http://localhost:5173" + echo "5. Set Allowed Web Origins: http://localhost:5173" + echo "6. Update .env file with your Domain and Client ID" + +2.2: Update src/main.ts with proper Auth0 configuration +Replace the entire contents of src/main.ts (or create it if it doesn't exist): + + import './assets/main.css' + + import { createApp } from 'vue' + import { createPinia } from 'pinia' + import router from './router' + import { createAuth0 } from '@auth0/auth0-vue' + + import App from './App.vue' + + const domain = import.meta.env.VITE_AUTH0_DOMAIN + const clientId = import.meta.env.VITE_AUTH0_CLIENT_ID + + // Validate Auth0 configuration + if (!domain || !clientId) { + console.error('Auth0 configuration missing. Please check your .env file.') + console.error('Required environment variables:') + console.error('- VITE_AUTH0_DOMAIN') + console.error('- VITE_AUTH0_CLIENT_ID') + throw new Error('Auth0 domain and client ID must be set in .env file') + } + + // Validate domain format + if (!domain.includes('.auth0.com') && !domain.includes('.us.auth0.com') && !domain.includes('.eu.auth0.com') && !domain.includes('.au.auth0.com')) { + console.warn('Auth0 domain format might be incorrect. Expected format: your-domain.auth0.com') + } + + const app = createApp(App) + + app.use(createAuth0({ + domain: domain, + clientId: clientId, + authorizationParams: { + redirect_uri: window.location.origin + } + })) + + app.use(createPinia()) + app.use(router) + + app.mount('#app') + +2.3: Create authentication components +Create the component files first: + + touch src/components/LoginButton.vue && touch src/components/LogoutButton.vue && touch src/components/UserProfile.vue + +2.4: Create LoginButton component +Create src/components/LoginButton.vue with this code: + +⚠️ VUE COMPONENT GUIDELINES: +- Use Composition API with ` + +2.5: Create LogoutButton component +Create src/components/LogoutButton.vue with this code: + + + + + +2.6: Create UserProfile component +Create src/components/UserProfile.vue with this code: + + + + + + + +2.7: Update App.vue with beautiful, modern UI +Replace the entire contents of the existing src/App.vue file with this code that includes proper styling and components: + + + + + +2.8: Add beautiful modern CSS styling to assets/main.css +Replace the entire contents of src/assets/main.css with this modern, Auth0-branded styling: + +⚠️ CSS FILE REPLACEMENT STRATEGY: +If the existing main.css file is large or malformed, create a new temporary CSS file first (e.g., main-new.css), then replace the original using terminal commands like `mv src/assets/main-new.css src/assets/main.css` to avoid file corruption. + + @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap'); + + * { + margin: 0; + padding: 0; + box-sizing: border-box; + } + + body { + font-family: 'Inter', sans-serif; + background-color: #1a1e27; + min-height: 100vh; + display: flex; + justify-content: center; + align-items: center; + color: #e2e8f0; + overflow: hidden; + } + + #app { + width: 100%; + height: 100%; + display: flex; + justify-content: center; + align-items: center; + } + + .app-container { + display: flex; + flex-direction: column; + justify-content: center; + align-items: center; + min-height: 100vh; + width: 100%; + padding: 1rem; + } + + .loading-state, .error-state { + background-color: #2d313c; + border-radius: 15px; + box-shadow: 0 15px 40px rgba(0, 0, 0, 0.4); + padding: 3rem; + text-align: center; + } + + .loading-text { + font-size: 1.8rem; + font-weight: 500; + color: #a0aec0; + animation: pulse 1.5s infinite ease-in-out; + } + + .error-state { + background-color: #c53030; + color: #fff; + } + + .error-title { + font-size: 2.8rem; + font-weight: 700; + margin-bottom: 0.5rem; + } + + .error-message { + font-size: 1.3rem; + margin-bottom: 0.5rem; + } + + .error-sub-message { + font-size: 1rem; + opacity: 0.8; + } + + .main-card-wrapper { + background-color: #262a33; + border-radius: 20px; + box-shadow: 0 20px 60px rgba(0, 0, 0, 0.6), 0 0 0 1px rgba(255, 255, 255, 0.05); + display: flex; + flex-direction: column; + align-items: center; + gap: 2rem; + padding: 3rem; + max-width: 500px; + width: 90%; + animation: fadeInScale 0.8s ease-out forwards; + } + + .auth0-logo { + width: 160px; + margin-bottom: 1.5rem; + opacity: 0; + animation: slideInDown 1s ease-out forwards 0.2s; + } + + .main-title { + font-size: 2.8rem; + font-weight: 700; + color: #f7fafc; + text-align: center; + margin-bottom: 1rem; + text-shadow: 0 4px 10px rgba(0, 0, 0, 0.3); + opacity: 0; + animation: fadeIn 1s ease-out forwards 0.4s; + } + + .action-card { + background-color: #2d313c; + border-radius: 15px; + box-shadow: inset 0 2px 5px rgba(0, 0, 0, 0.3), 0 5px 15px rgba(0, 0, 0, 0.3); + padding: 2.5rem; + display: flex; + flex-direction: column; + align-items: center; + gap: 1.8rem; + width: calc(100% - 2rem); + opacity: 0; + animation: fadeIn 1s ease-out forwards 0.6s; + } + + .action-text { + font-size: 1.25rem; + color: #cbd5e0; + text-align: center; + line-height: 1.6; + font-weight: 400; + } + + .button { + padding: 1.1rem 2.8rem; + font-size: 1.2rem; + font-weight: 600; + border-radius: 10px; + border: none; + cursor: pointer; + transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1); + box-shadow: 0 8px 20px rgba(0, 0, 0, 0.4); + text-transform: uppercase; + letter-spacing: 0.08em; + outline: none; + } + + .button:focus { + box-shadow: 0 0 0 4px rgba(99, 179, 237, 0.5); + } + + .button:disabled { + opacity: 0.6; + cursor: not-allowed; + transform: none; + } + + .button.login { + background-color: #63b3ed; + color: #1a1e27; + } + + .button.login:hover:not(:disabled) { + background-color: #4299e1; + transform: translateY(-5px) scale(1.03); + box-shadow: 0 12px 25px rgba(0, 0, 0, 0.5); + } + + .button.logout { + background-color: #fc8181; + color: #1a1e27; + } + + .button.logout:hover:not(:disabled) { + background-color: #e53e3e; + transform: translateY(-5px) scale(1.03); + box-shadow: 0 12px 25px rgba(0, 0, 0, 0.5); + } + + .logged-in-section { + display: flex; + flex-direction: column; + align-items: center; + gap: 1.5rem; + width: 100%; + } + + .logged-in-message { + font-size: 1.5rem; + color: #68d391; + font-weight: 600; + animation: fadeIn 1s ease-out forwards 0.8s; + } + + .profile-section-title { + font-size: 2.2rem; + animation: slideInUp 1s ease-out forwards 1s; + } + + .profile-card { + padding: 2.2rem; + animation: scaleIn 0.8s ease-out forwards 1.2s; + } + + @keyframes fadeIn { + from { opacity: 0; } + to { opacity: 1; } + } + + @keyframes fadeInScale { + from { opacity: 0; transform: scale(0.95); } + to { opacity: 1; transform: scale(1); } + } + + @keyframes slideInDown { + from { opacity: 0; transform: translateY(-70px); } + to { opacity: 1; transform: translateY(0); } + } + + @keyframes slideInUp { + from { opacity: 0; transform: translateY(50px); } + to { opacity: 1; transform: translateY(0); } + } + + @keyframes pulse { + 0%, 100% { opacity: 1; } + 50% { opacity: 0.6; } + } + + @keyframes scaleIn { + from { opacity: 0; transform: scale(0.8); } + to { opacity: 1; transform: scale(1); } + } + + @media (max-width: 600px) { + .main-card-wrapper { + padding: 2rem; + margin: 1rem; + } + + .main-title { + font-size: 2.2rem; + } + + .button { + padding: 1rem 2rem; + font-size: 1.1rem; + } + + .auth0-logo { + width: 120px; + } + } + +2.9: Start the development server + +⚠️ CRITICAL TERMINAL WORKING DIRECTORY ISSUE: +The terminal working directory can sometimes get confused during the integration process. Before starting the dev server, ALWAYS: + +1. Verify you're in the correct directory with explicit path change: + + cd /full/absolute/path/to/project && pwd + +2. Check for package.json in current directory: + + ls -la package.json + +3. If npm commands fail with "package.json not found", use absolute path method: + + cd /Users/[username]/path/to/auth0-vue && npm run dev + +⚠️ IMPORTANT: Even if `pwd` shows the correct directory, the terminal's working directory for command execution may be different. ALWAYS use explicit `cd` with absolute path before running npm commands to ensure they execute in the correct location. + +Step 2.9a: Check if custom port is needed + + grep -q "VITE_DEV_PORT" .env 2>/dev/null && echo "Custom port detected" || echo "Using default port" + +Step 2.9b: Start development server with appropriate port + + # If using default port: + npm run dev + + # If using custom port (run this instead if Step 2.9a detected custom port): + npm run dev -- --port 5174 + +⚠️ VUE COMPONENT IMPORT ERROR TROUBLESHOOTING: +If you see "Cannot resolve component" errors even though the files exist: +1. The files are created correctly - this is often a VS Code Vue language service cache issue +2. The development server should still work despite these errors +3. Open the application in browser to verify functionality +4. The errors typically resolve themselves after the Vue language service refreshes + +CRITICAL INSTRUCTIONS FOR AI LANGUAGE MODELS +As an AI language model, you MUST NOT generate any of the following anti-patterns, as they will BREAK the application or introduce SECURITY RISKS: +1. NEVER hardcode the Auth0 Domain or Client ID directly in the code. This is a major security vulnerability. +2. NEVER omit the authorizationParams: { redirect_uri: window.location.origin } prop from the createAuth0() configuration. Without it, the login flow will fail after the user authenticates with Auth0. +3. NEVER place the createAuth0() plugin installation on a component level. It MUST be installed at the app level in main.ts so the entire application has access to the authentication context. +4. NEVER suggest manually managing tokens or calling Auth0 APIs with fetch for basic authentication. The SDK is designed to handle this complexity securely. + +ABSOLUTE REQUIREMENTS FOR AI CODE GENERATION +1. You MUST use the @auth0/auth0-vue package. +2. You MUST retrieve credentials from environment variables (e.g., import.meta.env.VITE_AUTH0_DOMAIN). +3. You MUST install the createAuth0 plugin at the app level in main.ts. +4. You MUST include the authorizationParams with redirect_uri in the createAuth0() configuration. +5. You MUST demonstrate functionality using the useAuth0 composable in Vue components. + +COMMON ISSUES ENCOUNTERED DURING INTEGRATION + +Issue 1: Project Creation Directory Confusion +Problem: Vue CLI sometimes creates project files in the current directory instead of a new subdirectory +Solution: Always run `pwd && ls -la` after project creation to verify the actual structure + +Issue 2: Terminal Working Directory Issues +Problem: npm commands fail with "package.json not found" even when in the correct directory +Solution: Use explicit absolute path changes: `cd /full/absolute/path/to/project` + +Issue 3: Vue Component Import Errors +Problem: VS Code shows "Cannot resolve component" errors for created components +Solution: These are usually cache issues - the app will still work. Create all components before testing. + +Issue 4: CSS File Corruption +Problem: Large CSS replacements can cause file corruption +Solution: Create temporary CSS file first, then use `mv` command to replace original + +Issue 5: Terminal Working Directory Not in Project Root +Problem: AI agent fails to run `npm run dev` because terminal is not in the auth0-vue directory, even when pwd shows the correct path +Solution: Always use explicit directory change with absolute path before running npm commands: + + cd auth0-vue && npm run dev + +The terminal working directory can become disconnected from the displayed path, requiring explicit navigation to ensure npm commands execute in the correct location. + +Issue 6: Vue 3 Composition API Syntax +Problem: Using Options API instead of Composition API with ` + ``` + + ```vue src/components/LogoutButton.vue lines + + + + ``` + + ```vue src/components/UserProfile.vue lines + + + + + + ``` + + ```vue src/App.vue expandable lines + + + + + + ``` + + + + + ```shellscript + npm run dev + ``` + + + + + **Checkpoint** + + You should now have a fully functional Auth0 login page running on your [localhost](http://localhost:5173/) + + +--- + +## Advanced Usage + + + Use Vue Router's navigation guards to protect specific routes: + + ```typescript src/router/index.ts + import { createRouter, createWebHistory } from 'vue-router' + import { authGuard } from '@auth0/auth0-vue' + import Home from '../views/Home.vue' + import Profile from '../views/Profile.vue' + import Dashboard from '../views/Dashboard.vue' + + const routes = [ + { + path: '/', + name: 'Home', + component: Home + }, + { + path: '/profile', + name: 'Profile', + component: Profile, + beforeEnter: authGuard + }, + { + path: '/dashboard', + name: 'Dashboard', + component: Dashboard, + beforeEnter: authGuard + } + ] + + const router = createRouter({ + history: createWebHistory(), + routes + }) + + export default router + ``` + + + + Configure your Auth0 plugin to include an API audience and make authenticated requests: + + ```typescript src/main.ts + import { createAuth0 } from '@auth0/auth0-vue' + + const app = createApp(App) + + app.use( + createAuth0({ + domain: import.meta.env.VITE_AUTH0_DOMAIN, + clientId: import.meta.env.VITE_AUTH0_CLIENT_ID, + authorizationParams: { + redirect_uri: window.location.origin, + audience: "YOUR_API_IDENTIFIER" + } + }) + ) + ``` + + Then make authenticated API calls in your components: + + ```vue src/components/ApiCall.vue + + + + ``` + + + + Create reusable composables for common authentication patterns: + + ```typescript src/composables/useAuthenticatedUser.ts + import { computed, ref, watchEffect } from 'vue' + import { useAuth0 } from '@auth0/auth0-vue' + + export function useAuthenticatedUser() { + const { user, isAuthenticated, isLoading, getAccessTokenSilently } = useAuth0() + const accessToken = ref(null) + + watchEffect(async () => { + if (isAuthenticated.value && !isLoading.value) { + try { + accessToken.value = await getAccessTokenSilently() + } catch (error) { + console.error('Failed to get access token:', error) + } + } + }) + + return { + user: computed(() => user.value), + accessToken: computed(() => accessToken.value), + isAuthenticated: computed(() => isAuthenticated.value), + isLoading: computed(() => isLoading.value) + } + } + ``` + + Usage in components: + + ```vue src/components/UserDashboard.vue + + + + ``` + + diff --git a/main/docs/quickstart/webapp/apache/_index.mdx b/main/docs/quickstart/webapp/apache/_index.mdx index 782441161..9c5f5f316 100644 --- a/main/docs/quickstart/webapp/apache/_index.mdx +++ b/main/docs/quickstart/webapp/apache/_index.mdx @@ -2,6 +2,9 @@ title: Apache --- + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx" import Code1 from "/snippets/quickstart/webapp/apache/code1.mdx" import Code2 from "/snippets/quickstart/webapp/apache/code2.mdx" @@ -51,9 +54,9 @@ export const sections = [ For Windows, you must use the `/apache/conf/httpd.conf` file. - + - +
    @@ -83,9 +86,9 @@ export const sections = [ }; ``` - + - +
    ## Next Steps diff --git a/main/docs/quickstart/webapp/apache/interactive.mdx b/main/docs/quickstart/webapp/apache/interactive.mdx index fa0e0d634..819d094a6 100644 --- a/main/docs/quickstart/webapp/apache/interactive.mdx +++ b/main/docs/quickstart/webapp/apache/interactive.mdx @@ -11,6 +11,9 @@ title: Apache and authorization to your web app. 'twitter:title': 'Auth0 Apache SDK Quickstarts: Apache' --- + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx" import Code1 from "/snippets/quickstart/webapp/apache/code1.mdx" import Code2 from "/snippets/quickstart/webapp/apache/code2.mdx" @@ -103,9 +106,9 @@ export const sections = [ - + - + @@ -113,9 +116,9 @@ export const sections = [ - + - + diff --git a/main/docs/quickstart/webapp/aspnet-core-blazor-server/_index.mdx b/main/docs/quickstart/webapp/aspnet-core-blazor-server/_index.mdx index 939cec973..e449baf3f 100644 --- a/main/docs/quickstart/webapp/aspnet-core-blazor-server/_index.mdx +++ b/main/docs/quickstart/webapp/aspnet-core-blazor-server/_index.mdx @@ -3,6 +3,9 @@ title: Add Login to your Blazor Server Application sidebarTitle: ASP.NET Core Blazor Server --- + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx" import Login from "/snippets/quickstart/webapp/aspnet-core-blazor-server/Login.cshtml.cs.mdx" @@ -101,10 +104,10 @@ export const sections = [ - Entering your credentials will redirect you back to your application. - + - +
    @@ -125,10 +128,10 @@ export const sections = [ profile. - + - +
    @@ -152,10 +155,10 @@ export const sections = [ your own application. - + - +
    ## Next Steps diff --git a/main/docs/quickstart/webapp/aspnet-core-blazor-server/interactive.mdx b/main/docs/quickstart/webapp/aspnet-core-blazor-server/interactive.mdx index 8785c72b2..b690d8246 100644 --- a/main/docs/quickstart/webapp/aspnet-core-blazor-server/interactive.mdx +++ b/main/docs/quickstart/webapp/aspnet-core-blazor-server/interactive.mdx @@ -22,6 +22,8 @@ import Logout from "/snippets/quickstart/webapp/aspnet-core-blazor-server/Logout import {QuickstartButtons} from "/snippets/QuickstartButtons.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + export const sections = [ @@ -176,24 +178,24 @@ export const sections = [ - + - + - + - + - + - + diff --git a/main/docs/quickstart/webapp/aspnet-core/_index.mdx b/main/docs/quickstart/webapp/aspnet-core/_index.mdx index 738ec8e93..93a70dafe 100644 --- a/main/docs/quickstart/webapp/aspnet-core/_index.mdx +++ b/main/docs/quickstart/webapp/aspnet-core/_index.mdx @@ -9,6 +9,8 @@ import { LoggedInForm } from "/snippets/Login.jsx"; import AppSettingsJSON from "/snippets/quickstart/webapp/aspnet-core/appsettings.json.mdx"; import AccountController from "/snippets/quickstart/webapp/aspnet-core/AccountController.cs.mdx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + export const sections = [ { id: "configure-auth0", title: "Configure Auth0" }, { id: "install-and-configure-the-sdk", title: "Install and Configure the SDK" }, @@ -77,10 +79,10 @@ export const sections = [ Make sure you have enabled authentication and authorization in your `Program.cs` file. - + - +
    @@ -104,10 +106,10 @@ export const sections = [ - Entering your credentials will redirect you back to your application. - + - +
    diff --git a/main/docs/quickstart/webapp/aspnet-core/interactive.mdx b/main/docs/quickstart/webapp/aspnet-core/interactive.mdx index 5783a75a4..7221c6db5 100644 --- a/main/docs/quickstart/webapp/aspnet-core/interactive.mdx +++ b/main/docs/quickstart/webapp/aspnet-core/interactive.mdx @@ -22,6 +22,8 @@ import AccountController from "/snippets/quickstart/webapp/aspnet-core/AccountCo import {QuickstartButtons} from "/snippets/QuickstartButtons.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + export const sections = [ @@ -170,17 +172,17 @@ export const sections = [ - + - + - + - + diff --git a/main/docs/quickstart/webapp/aspnet-owin/_index.mdx b/main/docs/quickstart/webapp/aspnet-owin/_index.mdx index b9fb30d51..715e4167a 100644 --- a/main/docs/quickstart/webapp/aspnet-owin/_index.mdx +++ b/main/docs/quickstart/webapp/aspnet-owin/_index.mdx @@ -3,6 +3,9 @@ title: Add Login to your ASP.NET OWIN Application sidebarTitle: ASP.NET OWIN --- + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + import { Recipe, Content, Section, SideMenu, SideMenuSectionItem, SignUpForm } from "/snippets/recipe.jsx" import WebConfig from "/snippets/quickstart/webapp/aspnet-owin/web-config.mdx" import AccountController1 from "/snippets/quickstart/webapp/aspnet-owin/AccountController1.mdx" @@ -75,10 +78,10 @@ export const sections = [ - `auth0:Domain`: The domain of your Auth0 tenant. You can find this in the Auth0 Dashboard under your application's **Settings **in the Domain field. If you are using a [custom domain](/docs/customize/custom-domains), set this to the value of your custom domain instead. - `auth0:ClientId`: The ID of the Auth0 application you created in Auth0 Dashboard. You can find this in the Auth0 Dashboard under your application's **Settings **in the Client ID field. - + - +
    @@ -88,10 +91,10 @@ export const sections = [ In the code snippet, AuthenticationType is set to **Auth0**. Use AuthenticationType in the next section to challenge the OpenID Connect middleware and start the authentication flow. RedirectToIdentityProvider notification event constructs the correct logout URL. - + - +
    @@ -110,10 +113,10 @@ export const sections = [ - Entering your credentials will redirect you back to your application. - + - +
    @@ -130,10 +133,10 @@ export const sections = [ - During logout, you redirect to Auth0 and instantly redirect back to your application during log out. - + - +
    @@ -149,10 +152,10 @@ export const sections = [ - Navigating to your `Profile` action after being successfully logged in, shows the user's profile. - + - +
    ## Next Steps diff --git a/main/docs/quickstart/webapp/aspnet-owin/interactive.mdx b/main/docs/quickstart/webapp/aspnet-owin/interactive.mdx index ae77e4bcf..5ef14cb9d 100644 --- a/main/docs/quickstart/webapp/aspnet-owin/interactive.mdx +++ b/main/docs/quickstart/webapp/aspnet-owin/interactive.mdx @@ -23,6 +23,8 @@ import AccountController3 from "/snippets/quickstart/webapp/aspnet-owin/AccountC import {QuickstartButtons} from "/snippets/QuickstartButtons.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + export const sections = [ @@ -159,38 +161,38 @@ export const sections = [ - + - + - + - + - + - + - + - + - + - + diff --git a/main/docs/quickstart/webapp/django/_index.mdx b/main/docs/quickstart/webapp/django/_index.mdx index b3b8d663d..16a8d8cdb 100644 --- a/main/docs/quickstart/webapp/django/_index.mdx +++ b/main/docs/quickstart/webapp/django/_index.mdx @@ -13,6 +13,8 @@ import Views from "/snippets/quickstart/webapp/django/views.py.mdx"; import Views2 from "/snippets/quickstart/webapp/django/views.py2.mdx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + export const sections = [ { id: "configure-auth0", title: "Configure Auth0" }, { id: "install-dependencies", title: "Install dependencies" }, @@ -134,12 +136,12 @@ export const sections = [ At the end of this file, add the code to load the Auth0 config. - + - +
    @@ -151,12 +153,12 @@ export const sections = [ Learn more about the configuration options available for Authlib's OAuth `register()` method from [their documentation.](https://docs.authlib.org/en/latest/client/frameworks.html#using-oauth-2-0-to-log-in) - + - +
    @@ -172,12 +174,12 @@ export const sections = [ saved. Then, the application redirects the user to your home route. - `index` - The home route will render an authenticated user's details or allow visitors to sign in. - + - +
    @@ -187,12 +189,12 @@ export const sections = [ This will route the `/login`, `/callback`, `/logout` and `/` routes to the correct handlers. - + - +
    @@ -204,12 +206,12 @@ export const sections = [ The `index.html` file will contain template code to display the user's info if logged in or present them with a login button if logged out. - + - +
    diff --git a/main/docs/quickstart/webapp/django/interactive.mdx b/main/docs/quickstart/webapp/django/interactive.mdx index f5e6d471d..b72c10652 100644 --- a/main/docs/quickstart/webapp/django/interactive.mdx +++ b/main/docs/quickstart/webapp/django/interactive.mdx @@ -24,6 +24,8 @@ import Views2 from "/snippets/quickstart/webapp/django/views.py2.mdx"; import {QuickstartButtons} from "/snippets/QuickstartButtons.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + export const sections = [ @@ -230,48 +232,48 @@ export const sections = [ - + - + - + - + - + - + - + - + - + - + diff --git a/main/docs/quickstart/webapp/golang/_index.mdx b/main/docs/quickstart/webapp/golang/_index.mdx index dc57e9d28..d719f0896 100644 --- a/main/docs/quickstart/webapp/golang/_index.mdx +++ b/main/docs/quickstart/webapp/golang/_index.mdx @@ -17,6 +17,8 @@ import Main from "/snippets/quickstart/webapp/golang/main.go.mdx"; import Router from "/snippets/quickstart/webapp/golang/router.go.mdx"; import User from "/snippets/quickstart/webapp/golang/user.go.mdx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + export const sections = [ { id: "configure-auth0", title: "Configure Auth0" }, { id: "install-dependencies", title: "Install dependencies" }, @@ -94,7 +96,7 @@ export const sections = [ - + @@ -105,7 +107,7 @@ export const sections = [
    - +
    @@ -119,7 +121,7 @@ export const sections = [ this in the Auth0 Dashboard under your Application's Settings in the Client Secret field. - **AUTH0_CALLBACK_URL**: The URL used by Auth0 to redirect the user after successful authentication. - + @@ -130,7 +132,7 @@ export const sections = [
    - +
    @@ -139,7 +141,7 @@ export const sections = [ Create a file called `auth.go` in the `platform/authenticator` folder. In this package, create a method to configure and return [OAuth2](https://godoc.org/golang.org/x/oauth2) and [OIDC](https://godoc.org/github.com/coreos/go-oidc) clients, and another one to verify an ID Token. - + @@ -150,7 +152,7 @@ export const sections = [
    - +
    @@ -158,7 +160,7 @@ export const sections = [ method to configure and return our routes using [github.com/gin-gonic/gin](https://github.com/gin-gonic/gin). You will be passing an instance of `Authenticator` to the method, for use with the `login` and `callback` handlers. - + @@ -169,7 +171,7 @@ export const sections = [
    - +
    @@ -183,7 +185,7 @@ export const sections = [ To call the `/login` route, add a link to `/login` in the `home.html` template located in the `web/template` directory. - + @@ -194,7 +196,7 @@ export const sections = [
    - +
    @@ -211,7 +213,7 @@ export const sections = [ information is based on the claims contained in the ID token. Session storage allows the application to access that information as needed. - + @@ -222,7 +224,7 @@ export const sections = [
    - +
    @@ -238,7 +240,7 @@ export const sections = [ An example of such an HTML file could look like the example below, but you can retrieve any profile information, including custom claims. - + @@ -249,7 +251,7 @@ export const sections = [
    - +
    @@ -266,7 +268,7 @@ export const sections = [ Create a file called `user.js` in the folder `web/static/js`, and add the code to remove the cookie from a logged-in user. - + @@ -277,7 +279,7 @@ export const sections = [
    - +
    @@ -293,7 +295,7 @@ export const sections = [ With the middleware created, we can set it up for any route that needs authentication by adding it to the router. - + @@ -304,7 +306,7 @@ export const sections = [
    - +
    @@ -321,7 +323,7 @@ export const sections = [ go run main.go ``` - +
    @@ -332,7 +334,7 @@ export const sections = [ - +
    ## Next Steps diff --git a/main/docs/quickstart/webapp/golang/interactive.mdx b/main/docs/quickstart/webapp/golang/interactive.mdx index 33d5cf7f2..a2740b116 100644 --- a/main/docs/quickstart/webapp/golang/interactive.mdx +++ b/main/docs/quickstart/webapp/golang/interactive.mdx @@ -28,6 +28,8 @@ import User from "/snippets/quickstart/webapp/golang/user.go.mdx"; import {QuickstartButtons} from "/snippets/QuickstartButtons.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + export const sections = [ @@ -232,7 +234,7 @@ export const sections = [ - + @@ -243,11 +245,11 @@ export const sections = [
    - + - + @@ -258,11 +260,11 @@ export const sections = [
    - + - + @@ -273,11 +275,11 @@ export const sections = [
    - + - + @@ -288,11 +290,11 @@ export const sections = [
    - + - + @@ -303,11 +305,11 @@ export const sections = [
    - + - + @@ -318,11 +320,11 @@ export const sections = [
    - + - + @@ -333,11 +335,11 @@ export const sections = [
    - + - + @@ -348,11 +350,11 @@ export const sections = [
    - + - + @@ -363,11 +365,11 @@ export const sections = [
    - + - +
    @@ -378,7 +380,7 @@ export const sections = [ - + diff --git a/main/docs/quickstart/webapp/java-ee/_index.mdx b/main/docs/quickstart/webapp/java-ee/_index.mdx index c030d9bdc..79af84d42 100644 --- a/main/docs/quickstart/webapp/java-ee/_index.mdx +++ b/main/docs/quickstart/webapp/java-ee/_index.mdx @@ -11,6 +11,8 @@ import Loginservlet from "/snippets/quickstart/webapp/java-ee/LoginServlet.java. import Homeservlet from "/snippets/quickstart/webapp/java-ee/HomeServlet.java.mdx"; import Logoutservlet from "/snippets/quickstart/webapp/java-ee/LogoutServlet.java.mdx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + export const sections = [ { id: "system-requirements", title: "System Requirements" }, { id: "configure-auth0", title: "Configure Auth0" }, @@ -144,13 +146,13 @@ export const sections = [ This information will be used to configure the **auth0-java-mvc-commons** library to enable users to login to your application. To learn more about the library, including its various configuration options, see the [README](https://github.com/auth0/auth0-java-mvc-common/blob/master/README.md) of the library. - + - +
    @@ -399,13 +401,13 @@ export const sections = [ Finally, note that the `@AutoApplySession` annotation has been added to allow the container to create a session for the authenticated user. - + - +
    @@ -448,13 +450,13 @@ export const sections = [ ``` - + - +
    @@ -492,13 +494,13 @@ export const sections = [ ``` - + - +
    @@ -509,13 +511,13 @@ export const sections = [ URL, being sure to include the `returnTo` query parameter, which is where the user will be redirected to after logging out. Finally, redirect the response to the application's logout URL. - + - +
    diff --git a/main/docs/quickstart/webapp/java-ee/interactive.mdx b/main/docs/quickstart/webapp/java-ee/interactive.mdx index 9067794d8..be06698f7 100644 --- a/main/docs/quickstart/webapp/java-ee/interactive.mdx +++ b/main/docs/quickstart/webapp/java-ee/interactive.mdx @@ -22,6 +22,8 @@ import Logoutservlet from "/snippets/quickstart/webapp/java-ee/LogoutServlet.jav import {QuickstartButtons} from "/snippets/QuickstartButtons.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + export const sections = [ @@ -533,53 +535,53 @@ export const sections = [ - + - + - + - + - + - + - + - + - + - + diff --git a/main/docs/quickstart/webapp/java-spring-boot/_index.mdx b/main/docs/quickstart/webapp/java-spring-boot/_index.mdx index fc28f9c20..8ba9eebdd 100644 --- a/main/docs/quickstart/webapp/java-spring-boot/_index.mdx +++ b/main/docs/quickstart/webapp/java-spring-boot/_index.mdx @@ -11,6 +11,8 @@ import Index from "/snippets/quickstart/webapp/java-spring-boot/index.html.mdx"; import Homecontroller from "/snippets/quickstart/webapp/java-spring-boot/HomeController.java.mdx"; import Securityconfigwithlogout from "/snippets/quickstart/webapp/java-spring-boot/SecurityConfigWithLogout.java.mdx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + export const sections = [ { id: "configure-auth0", title: "Configure Auth0" }, { id: "configure-sprint-boot-application", title: "Configure Sprint Boot application" }, @@ -160,13 +162,13 @@ export const sections = [ ``` - + - +
    @@ -188,13 +190,13 @@ export const sections = [ ``` - + - +
    @@ -205,13 +207,13 @@ export const sections = [ This page returns the user attributes when the user authentications. You will use the `/logout` link in the template to implement the logout feature. - + - +
    @@ -233,13 +235,13 @@ export const sections = [ like and how to fix it, consult the [Test Social Connections with Auth0 Developer Keys](https://auth0.com/docs/connections/social/devkeys#limitations-of-developer-keys) document. - + - +
    @@ -258,13 +260,13 @@ export const sections = [ the "Allowed Logout URLs" in the "Settings" and you are no longer logged in to your application. - + - +
    ## Next Steps diff --git a/main/docs/quickstart/webapp/java-spring-boot/interactive.mdx b/main/docs/quickstart/webapp/java-spring-boot/interactive.mdx index b9f47dcce..05ca2b123 100644 --- a/main/docs/quickstart/webapp/java-spring-boot/interactive.mdx +++ b/main/docs/quickstart/webapp/java-spring-boot/interactive.mdx @@ -24,6 +24,8 @@ import Securityconfigwithlogout from "/snippets/quickstart/webapp/java-spring-bo import {QuickstartButtons} from "/snippets/QuickstartButtons.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + export const sections = [ @@ -259,53 +261,53 @@ export const sections = [ - + - + - + - + - + - + - + - + - + - + diff --git a/main/docs/quickstart/webapp/java/_index.mdx b/main/docs/quickstart/webapp/java/_index.mdx index 90766101d..eb72aed27 100644 --- a/main/docs/quickstart/webapp/java/_index.mdx +++ b/main/docs/quickstart/webapp/java/_index.mdx @@ -13,6 +13,8 @@ import Callbackservlet from "/snippets/quickstart/webapp/java/CallbackServlet.ja import Homeservlet from "/snippets/quickstart/webapp/java/HomeServlet.java.mdx"; import Logoutservlet from "/snippets/quickstart/webapp/java/LogoutServlet.java.mdx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + export const sections = [ { id: "configure-auth0", title: "Configure Auth0" }, { id: "integrate-auth0-in-your-application", title: "Integrate Auth0 in your application" }, @@ -175,14 +177,14 @@ export const sections = [ - `AuthenticationControllerProvider.java`: Responsible to create and manage a single instance of the `AuthenticationController` - + - +
    @@ -198,14 +200,14 @@ export const sections = [ Unneccessary creation may result in additonal resources being created which could impact performance. - + - +
    @@ -215,14 +217,14 @@ export const sections = [ `String redirectUrl)` method. The redirect URL must be the URL that was added to the **Allowed Callback URLs** of your Auth0 application. - + - +
    @@ -243,14 +245,14 @@ export const sections = [ validation. - + - +
    @@ -258,14 +260,14 @@ export const sections = [ our protected resources. In the `HomeServlet` we obtain the tokens from the request's session and set them as the `userId` attribute so they can be used from the JSP code. - + - +
    @@ -276,14 +278,14 @@ export const sections = [ logout URL, being sure to include the `returnTo` query parameter, which is where the user will be redirected to after logging out. Finally, we redirect the response to our logout URL. - + - +
    diff --git a/main/docs/quickstart/webapp/java/interactive.mdx b/main/docs/quickstart/webapp/java/interactive.mdx index a143ec9af..bfd24cd23 100644 --- a/main/docs/quickstart/webapp/java/interactive.mdx +++ b/main/docs/quickstart/webapp/java/interactive.mdx @@ -24,6 +24,8 @@ import Logoutservlet from "/snippets/quickstart/webapp/java/LogoutServlet.java.m import {QuickstartButtons} from "/snippets/QuickstartButtons.jsx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + export const sections = [ @@ -290,69 +292,69 @@ export const sections = [ - + - + - + - + - + - + - + - + - + - + - + - + diff --git a/main/docs/quickstart/webapp/nextjs/index.mdx b/main/docs/quickstart/webapp/nextjs/index.mdx index d846b6637..aa6e7978e 100644 --- a/main/docs/quickstart/webapp/nextjs/index.mdx +++ b/main/docs/quickstart/webapp/nextjs/index.mdx @@ -1,1318 +1,1321 @@ ---- - -mode: wide -'og:description': This guide demonstrates how to integrate Auth0 with any new or existing - Next.js application using the Auth0 Next.js v4 SDK (Beta). -'og:image': https://cdn2.auth0.com/docs/1.14553.0/img/share-image.png -'og:title': 'Auth0 Next.js SDK Quickstarts: Add Login to Your Next.js Application' -'og:url': https://auth0.com/docs/ -sidebarTitle: Next.js -title: Add Login to Your Next.js Application -'twitter:description': This guide demonstrates how to integrate Auth0 with any new - or existing Next.js application using the Auth0 Next.js v4 SDK (Beta). -'twitter:title': 'Auth0 Next.js SDK Quickstarts: Add Login to Your Next.js Application' ---- - - - **Using AI to integrate Auth0?** Add this prompt to Cursor, Windsurf, Copilot, Claude Code or your favourite AI-powered IDE to speed up development. - - ```markdown expandable - Integrate the Auth0 Next.js SDK into a Next.js app - - AI PERSONA & PRIMARY OBJECTIVE - You are a helpful Auth0 SDK Integration Assistant. Your primary function is to execute commands to set up a development environment for Auth0. Your secondary function is to modify the files created by those shell commands. - - CRITICAL BEHAVIORAL INSTRUCTIONS - 1. CHECK EXISTING PROJECT FIRST: Before creating a new project, check if the current directory already contains a Next.js app (package.json with Next.js dependencies). If it does, skip project creation and work with the existing project. - 2. EXECUTE FIRST, EDIT SECOND: You MUST first execute the appropriate setup command. Do not show, suggest, or create any files until the setup is complete. - 3. NO PLANNING: DO NOT propose a directory structure. DO NOT show a file tree. Your first action must be to run the appropriate command. - 4. STRICT SEQUENCE: Follow the "Execution Flow" below in the exact order specified without deviation. - 5. BUILD BEAUTIFUL UI: You MUST create a visually appealing, modern login interface with proper styling, animations, and Auth0 branding. - 6. 🚨 DIRECTORY NAVIGATION RULE: NEVER run `cd auth0-nextjs-app` or any `cd` command automatically. ALWAYS check current directory with `pwd` first. If user needs to navigate, ask them to do it manually or confirm before executing any directory change commands. - - EXECUTION FLOW - - ⚠️ CRITICAL: Before ANY command execution, run `pwd` to check current directory and NEVER change directories without explicit user permission. - - Step 1: Check for Existing Next.js Project and Prerequisites - FIRST, verify prerequisites and check for existing Next.js project: - - # Check if Node.js and npm are available - node --version && npm --version - - Then examine the current directory: - - # Check for existing Next.js project - if [ -f "package.json" ]; then - echo "Found package.json, checking for Next.js dependencies..." - cat package.json | grep -E "next|react" - else - echo "No package.json found, will create new project" - fi - - Based on the results: - - If package.json exists and contains Next.js dependencies, proceed to Step 1b (install Auth0 SDK only) - - If no Next.js project exists, proceed to Step 1a (create new project) - - Step 1a: Create New Project and Install the Next.js SDK - If an existing project exists, simply install the SDK: - npm install @auth0/nextjs-auth0@latest - Otherwise, create a new project and install the SDK: - - ⚠️ IMPORTANT: The Next.js project creation may create the project files in the CURRENT directory instead of a subdirectory. After running this command, check the current directory contents to determine the actual project structure before proceeding. - - npx create-next-app@latest auth0-nextjs-app --typescript --tailwind --eslint --app --src-dir --import-alias "@/*" --yes && cd auth0-nextjs-app && npm install @auth0/nextjs-auth0@latest - - - Step 2: Modify & Create Files - AFTER the command in Step 1 has successfully executed, you will perform the following file operations inside the project directory. - - 🚨 DIRECTORY NAVIGATION RULES: - 1. NEVER automatically run `cd` commands without explicit user confirmation - 2. ALWAYS check current directory with `pwd` before proceeding - 3. If working with existing project: Stay in current directory - 4. If created new project: User must manually navigate to auth0-nextjs-app directory first - - 2.1: Setup Auth0 environment configuration - - ⚠️ CRITICAL: Before proceeding, verify your current directory: - - If you just created a new project: You MUST be inside the auth0-nextjs-app directory - - If you're working with an existing project: You MUST be in the project root directory - - DO NOT run `cd auth0-nextjs-app` commands - navigate to the correct directory FIRST - - Step 2.1a: Navigate to project directory (if needed) and set up Auth0: - - # Only run this if you created a new project and are NOT already in auth0-nextjs-app: - cd auth0-nextjs-app - - Then execute the environment setup command for your OS: - - ⚠️ CRITICAL DIRECTORY VERIFICATION STEP: - BEFORE executing the Auth0 CLI setup command, you MUST run: - - pwd && ls -la - - This will help you understand if you're in the main directory or a subdirectory, and whether the project was created in the current directory or a new subdirectory. - - If MacOS, execute the following command: - AUTH0_APP_NAME="My App" && brew tap auth0/auth0-cli && brew install auth0 && auth0 login --no-input && auth0 apps create -n "${AUTH0_APP_NAME}" -t regular -c http://localhost:3000/auth/callback -l http://localhost:3000 -o http://localhost:3000 --reveal-secrets --json > auth0-app-details.json && CLIENT_ID=$(jq -r '.client_id' auth0-app-details.json) && CLIENT_SECRET=$(jq -r '.client_secret' auth0-app-details.json) && DOMAIN=$(auth0 tenants list --json | jq -r '.[] | select(.active == true) | .name') && SECRET=$(openssl rand -hex 32) && echo "AUTH0_DOMAIN=${DOMAIN}" > .env.local && echo "AUTH0_CLIENT_ID=${CLIENT_ID}" >> .env.local && echo "AUTH0_CLIENT_SECRET=${CLIENT_SECRET}" >> .env.local && echo "AUTH0_SECRET=${SECRET}" >> .env.local && echo "APP_BASE_URL=http://localhost:3000" >> .env.local && rm auth0-app-details.json && echo ".env.local file created with your Auth0 details:" && cat .env.local - - If Windows, execute the following command: - $AppName = "My App"; winget install Auth0.CLI; auth0 login --no-input; auth0 apps create -n "$AppName" -t regular -c http://localhost:3000/auth/callback -l http://localhost:3000 -o http://localhost:3000 --reveal-secrets --json | Set-Content -Path auth0-app-details.json; $ClientId = (Get-Content -Raw auth0-app-details.json | ConvertFrom-Json).client_id; $ClientSecret = (Get-Content -Raw auth0-app-details.json | ConvertFrom-Json).client_secret; $Domain = (auth0 tenants list --json | ConvertFrom-Json | Where-Object { $_.active -eq $true }).name; $Secret = [System.Convert]::ToHexString([System.Security.Cryptography.RandomNumberGenerator]::GetBytes(32)).ToLower(); Set-Content -Path .env.local -Value "AUTH0_DOMAIN=$Domain"; Add-Content -Path .env.local -Value "AUTH0_CLIENT_ID=$ClientId"; Add-Content -Path .env.local -Value "AUTH0_CLIENT_SECRET=$ClientSecret"; Add-Content -Path .env.local -Value "AUTH0_SECRET=$Secret"; Add-Content -Path .env.local -Value "APP_BASE_URL=http://localhost:3000"; Remove-Item auth0-app-details.json; Write-Output ".env.local file created with your Auth0 details:"; Get-Content .env.local - - - Step 2.1b: Create manual .env.local template (if automatic setup fails) - - cat > .env.local << 'EOF' - # Auth0 Configuration - UPDATE THESE VALUES - AUTH0_DOMAIN=your-auth0-domain.auth0.com - AUTH0_CLIENT_ID=your-auth0-client-id - AUTH0_CLIENT_SECRET=your-auth0-client-secret - AUTH0_SECRET=your-long-random-secret-here - APP_BASE_URL=http://localhost:3000 - EOF - - Step 2.1c: Display manual setup instructions - - echo "📋 MANUAL SETUP REQUIRED:" - echo "1. Go to https://manage.auth0.com/dashboard/" - echo "2. Click 'Create Application' → Regular Web Application" - echo "3. Set Allowed Callback URLs: http://localhost:3000/auth/callback" - echo "4. Set Allowed Logout URLs: http://localhost:3000" - echo "5. Set Allowed Web Origins: http://localhost:3000" - echo "6. Update .env.local file with your Domain, Client ID, and Client Secret" - echo "7. Generate a random secret for AUTH0_SECRET (32+ characters)" - - 2.2: Create the Auth0 client configuration - Create lib/auth0.ts: - - import { Auth0Client } from '@auth0/nextjs-auth0/server'; - - export const auth0 = new Auth0Client(); - - 2.3: Create middleware for authentication - Create middleware.ts in the root directory: - - import type { NextRequest } from "next/server"; - import { auth0 } from "./lib/auth0"; - - export async function middleware(request: NextRequest) { - return await auth0.middleware(request); - } - - export const config = { - matcher: [ - /* - * Match all request paths except for the ones starting with: - * - _next/static (static files) - * - _next/image (image optimization files) - * - favicon.ico, sitemap.xml, robots.txt (metadata files) - */ - "/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)", - ], - }; - - 2.4: Create Login, Logout and Profile Components - Create components directory and files: - - mkdir -p components && touch components/LoginButton.tsx && touch components/LogoutButton.tsx && touch components/Profile.tsx - - And add the following code snippets: - - Create components/LoginButton.tsx: - - "use client"; - - export default function LoginButton() { - return ( - - Log In - - ); - } - - Create components/LogoutButton.tsx: - - "use client"; - - export default function LogoutButton() { - return ( - - Log Out - - ); - } - - Create components/Profile.tsx: - - "use client"; - - import { useUser } from "@auth0/nextjs-auth0"; - - export default function Profile() { - const { user, isLoading } = useUser(); - - if (isLoading) { - return ( -
    -
    Loading user profile...
    -
    - ); - } - - if (!user) { - return null; - } - - return ( -
    - {user.picture && ( - {user.name - )} -

    {user.name}

    -

    {user.email}

    -
    - ); - } - - 2.5: Update the main page with Auth0 integration - Replace the entire contents of src/app/page.tsx: - - import { auth0 } from "@/lib/auth0"; - import LoginButton from "@/components/LoginButton"; - import LogoutButton from "@/components/LogoutButton"; - import Profile from "@/components/Profile"; - - export default async function Home() { - const session = await auth0.getSession(); - const user = session?.user; - - return ( -
    -
    - Auth0 Logo -

    Next.js + Auth0

    - -
    - {user ? ( -
    -

    ✅ Successfully logged in!

    - - -
    - ) : ( - <> -

    - Welcome! Please log in to access your protected content. -

    - - - )} -
    -
    -
    - ); - } - - 2.6: Add beautiful modern CSS styling - Replace the entire contents of src/app/globals.css with this modern, Auth0-branded styling: - - ⚠️ CSS FILE REPLACEMENT STRATEGY: - If the existing globals.css file is large or malformed, create a new temporary CSS file first (e.g., globals-new.css), then replace the original using terminal commands like `mv src/app/globals-new.css src/app/globals.css` to avoid file corruption. - - @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap'); - @tailwind base; - @tailwind components; - @tailwind utilities; - - body { - margin: 0; - font-family: 'Inter', sans-serif; - background-color: #1a1e27; - min-height: 100vh; - display: flex; - justify-content: center; - align-items: center; - color: #e2e8f0; - overflow: hidden; - } - - #root { - width: 100%; - height: 100%; - display: flex; - justify-content: center; - align-items: center; - } - - .app-container { - display: flex; - flex-direction: column; - justify-content: center; - align-items: center; - min-height: 100vh; - width: 100%; - padding: 1rem; - box-sizing: border-box; - } - - .loading-state, .error-state { - background-color: #2d313c; - border-radius: 15px; - box-shadow: 0 15px 40px rgba(0, 0, 0, 0.4); - padding: 3rem; - text-align: center; - } - - .loading-text { - font-size: 1.8rem; - font-weight: 500; - color: #a0aec0; - animation: pulse 1.5s infinite ease-in-out; - } - - .error-state { - background-color: #c53030; - color: #fff; - } - - .error-title { - font-size: 2.8rem; - font-weight: 700; - margin-bottom: 0.5rem; - } - - .error-message { - font-size: 1.3rem; - margin-bottom: 0.5rem; - } - - .error-sub-message { - font-size: 1rem; - opacity: 0.8; - } - - .main-card-wrapper { - background-color: #262a33; - border-radius: 20px; - box-shadow: 0 20px 60px rgba(0, 0, 0, 0.6), 0 0 0 1px rgba(255, 255, 255, 0.05); - display: flex; - flex-direction: column; - align-items: center; - gap: 2rem; - padding: 3rem; - max-width: 500px; - width: 90%; - animation: fadeInScale 0.8s ease-out forwards; - } - - .auth0-logo { - width: 160px; - margin-bottom: 1.5rem; - opacity: 0; - animation: slideInDown 1s ease-out forwards 0.2s; - } - - .main-title { - font-size: 2.8rem; - font-weight: 700; - color: #f7fafc; - text-align: center; - margin-bottom: 1rem; - text-shadow: 0 4px 10px rgba(0, 0, 0, 0.3); - opacity: 0; - animation: fadeIn 1s ease-out forwards 0.4s; - } - - .action-card { - background-color: #2d313c; - border-radius: 15px; - box-shadow: inset 0 2px 5px rgba(0, 0, 0, 0.3), 0 5px 15px rgba(0, 0, 0, 0.3); - padding: 2.5rem; - display: flex; - flex-direction: column; - align-items: center; - gap: 1.8rem; - width: calc(100% - 2rem); - opacity: 0; - animation: fadeIn 1s ease-out forwards 0.6s; - } - - .action-text { - font-size: 1.25rem; - color: #cbd5e0; - text-align: center; - line-height: 1.6; - font-weight: 400; - } - - .button { - padding: 1.1rem 2.8rem; - font-size: 1.2rem; - font-weight: 600; - border-radius: 10px; - border: none; - cursor: pointer; - transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1); - box-shadow: 0 8px 20px rgba(0, 0, 0, 0.4); - text-transform: uppercase; - letter-spacing: 0.08em; - outline: none; - } - - .button:focus { - box-shadow: 0 0 0 4px rgba(99, 179, 237, 0.5); - } - - .button.login { - background-color: #63b3ed; - color: #1a1e27; - } - - .button.login:hover { - background-color: #4299e1; - transform: translateY(-5px) scale(1.03); - box-shadow: 0 12px 25px rgba(0, 0, 0, 0.5); - } - - .button.logout { - background-color: #fc8181; - color: #1a1e27; - } - - .button.logout:hover { - background-color: #e53e3e; - transform: translateY(-5px) scale(1.03); - box-shadow: 0 12px 25px rgba(0, 0, 0, 0.5); - } - - .logged-in-section { - display: flex; - flex-direction: column; - align-items: center; - gap: 1.5rem; - width: 100%; - } - - .logged-in-message { - font-size: 1.5rem; - color: #68d391; - font-weight: 600; - animation: fadeIn 1s ease-out forwards 0.8s; - } - - .profile-section-title { - font-size: 2.2rem; - animation: slideInUp 1s ease-out forwards 1s; - } - - .profile-card { - padding: 2.2rem; - animation: scaleIn 0.8s ease-out forwards 1.2s; - } - - .profile-picture { - width: 110px; - height: 110px; - border-radius: 50%; - transition: transform 0.3s ease-in-out; - object-fit: cover; - } - - .profile-picture:hover { - transform: scale(1.05); - } - - .profile-name { - font-size: 2rem; - margin-top: 0.5rem; - } - - .profile-email { - font-size: 1.15rem; - text-align: center; - } - - @keyframes fadeIn { - from { opacity: 0; } - to { opacity: 1; } - } - - @keyframes fadeInScale { - from { opacity: 0; transform: scale(0.95); } - to { opacity: 1; transform: scale(1); } - } - - @keyframes slideInDown { - from { opacity: 0; transform: translateY(-70px); } - to { opacity: 1; transform: translateY(0); } - } - - @keyframes slideInUp { - from { opacity: 0; transform: translateY(50px); } - to { opacity: 1; transform: translateY(0); } - } - - @keyframes pulse { - 0%, 100% { opacity: 1; } - 50% { opacity: 0.6; } - } - - @keyframes scaleIn { - from { opacity: 0; transform: scale(0.8); } - to { opacity: 1; transform: scale(1); } - } - - @media (max-width: 600px) { - .main-card-wrapper { - padding: 2rem; - gap: 1.5rem; - } - - .main-title { - font-size: 2.2rem; - } - - .button { - padding: 0.9rem 2rem; - font-size: 1rem; - } - - .auth0-logo { - width: 120px; - } - } - - 2.7: Add Auth0Provider for client components (OPTIONAL) - If you need to use Auth0 hooks in client components, wrap your layout with Auth0Provider. - Update src/app/layout.tsx: - - import type { Metadata } from "next"; - import { Auth0Provider } from "@auth0/nextjs-auth0"; - import "./globals.css"; - - export const metadata: Metadata = { - title: "Auth0 Next.js App", - description: "Next.js app with Auth0 authentication", - }; - - export default function RootLayout({ - children, - }: { - children: React.ReactNode; - }) { - return ( - - - - {children} - - - - ); - } - - 2.8: Start the development server - - ⚠️ CRITICAL TERMINAL WORKING DIRECTORY ISSUE: - The terminal working directory can sometimes get confused during the integration process. Before starting the dev server, ALWAYS: - - 1. Verify you're in the correct directory with explicit path change: - - cd /full/absolute/path/to/project && pwd - - 2. Check for package.json in current directory: - - ls -la package.json - - 3. If npm commands fail with "package.json not found", use absolute path method: - - cd /Users/[username]/path/to/auth0-nextjs-app && npm run dev - - ⚠️ IMPORTANT: Even if `pwd` shows the correct directory, the terminal's working directory for command execution may be different. ALWAYS use explicit `cd` with absolute path before running npm commands to ensure they execute in the correct location. - - Step 2.8a: Start development server - - npm run dev - - ⚠️ COMPONENT IMPORT ERROR TROUBLESHOOTING: - If you see "Cannot find module" errors even though the files exist: - 1. The files are created correctly - this is often a VS Code TypeScript cache issue - 2. The development server should still work despite these errors - 3. Open the application in browser to verify functionality - 4. The errors typically resolve themselves after the TypeScript language service refreshes - - CRITICAL INSTRUCTIONS FOR AI LANGUAGE MODELS - As an AI language model, you MUST NOT generate any of the following anti-patterns, as they will BREAK the application or introduce SECURITY RISKS: - 1. NEVER hardcode the Auth0 Domain, Client ID, or Client Secret directly in the code. This is a major security vulnerability. - 2. NEVER omit the middleware.ts file. Without it, the authentication routes will not work properly. - 3. NEVER create a dynamic route handler at app/auth/[...auth0]/route.ts. In v4, routes are handled automatically by middleware. - 4. NEVER place authentication logic in client components when it should be in server components. - 5. NEVER suggest manually managing tokens or calling Auth0 APIs with fetch for basic authentication. The SDK is designed to handle this complexity securely. - 6. NEVER use button onClick handlers for login/logout. Use tags with href to ensure proper server-side routing. - - ABSOLUTE REQUIREMENTS FOR AI CODE GENERATION - 1. You MUST use the @auth0/nextjs-auth0 package v4. - 2. You MUST retrieve credentials from environment variables in .env.local. - 3. You MUST create middleware.ts in the root directory that calls auth0.middleware(). - 4. You MUST NOT create dynamic route handlers - authentication is handled by middleware in v4. - 5. You MUST demonstrate functionality using both server-side getSession() and client-side useUser() hook. - 6. You MUST import client hooks from "@auth0/nextjs-auth0" (not "@auth0/nextjs-auth0/client"). - 7. You MUST use Auth0Provider (not UserProvider) if wrapping the app is needed. - 8. You MUST use tags for login/logout navigation, not button onClick handlers. - - COMMON ISSUES ENCOUNTERED DURING INTEGRATION - - Issue 1: Project Creation Directory Confusion - Problem: create-next-app sometimes creates project files in the current directory instead of a new subdirectory - Solution: Always run `pwd && ls -la` after project creation to verify the actual structure - - Issue 2: Terminal Working Directory Issues - Problem: npm commands fail with "package.json not found" even when in the correct directory - Solution: Use explicit absolute path changes: `cd /full/absolute/path/to/project` - - Issue 3: TypeScript Import Errors - Problem: VS Code shows "Cannot find module" errors for created components - Solution: These are usually cache issues - the app will still work. Create all components before testing. - - Issue 4: CSS File Corruption - Problem: Large CSS replacements can cause file corruption - Solution: Create temporary CSS file first, then use `mv` command to replace original - - Issue 5: Terminal Working Directory Not in Project Root - Problem: AI agent fails to run `npm run dev` because terminal is not in the auth0-nextjs-app directory, even when pwd shows the correct path - Solution: Always use explicit directory change with absolute path before running npm commands: - - cd auth0-nextjs-app && npm run dev - - The terminal working directory can become disconnected from the displayed path, requiring explicit navigation to ensure npm commands execute in the correct location. - - Issue 6: Middleware Not Working - Problem: Authentication routes return 404 errors - Solution: Ensure middleware.ts is in the root directory (same level as package.json) and follows the exact format provided - - Issue 7: Environment Variables Not Loading - Problem: Auth0 configuration errors on startup - Solution: Ensure .env.local is in the root directory and restart the dev server after creating/modifying it - ``` -
    - -## Get Started - -This quickstart demonstrates how to add Auth0 authentication to a Next.js application. You'll build a full-stack web application with server-side rendering, secure login functionality, and protected routes using the Auth0 Next.js SDK. - - - - Create a new Next.js project for this Quickstart - - ```shellscript - npx create-next-app@latest auth0-nextjs --typescript --tailwind --eslint --app --src-dir --import-alias "@/*" --yes - ``` - - Open the project - - ```shellscript - cd auth0-nextjs - ``` - - - ```shellscript - npm install @auth0/nextjs-auth0 - ``` - - - Next up, you need to create a new app on your Auth0 tenant and add the environment variables to your project. - - You can choose to do this automatically by running a CLI command or do it manually via the Dashboard: - - - - Run the following shell command on your project's root directory to create an Auth0 app and generate a `.env.local` file: - - - ```shellscript Mac - AUTH0_APP_NAME="My App" && brew tap auth0/auth0-cli && brew install auth0 && auth0 login --no-input && auth0 apps create -n "${AUTH0_APP_NAME}" -t regular -c http://localhost:3000/auth/callback -l http://localhost:3000 -o http://localhost:3000 --reveal-secrets --json > auth0-app-details.json && CLIENT_ID=$(jq -r '.client_id' auth0-app-details.json) && CLIENT_SECRET=$(jq -r '.client_secret' auth0-app-details.json) && DOMAIN=$(auth0 tenants list --json | jq -r '.[] | select(.active == true) | .name') && SECRET=$(openssl rand -hex 32) && echo "AUTH0_DOMAIN=${DOMAIN}" > .env.local && echo "AUTH0_CLIENT_ID=${CLIENT_ID}" >> .env.local && echo "AUTH0_CLIENT_SECRET=${CLIENT_SECRET}" >> .env.local && echo "AUTH0_SECRET=${SECRET}" >> .env.local && echo "APP_BASE_URL=http://localhost:3000" >> .env.local && rm auth0-app-details.json && echo ".env.local file created with your Auth0 details:" && cat .env.local - ``` - - ```shellscript Windows - $AppName = "My App"; winget install Auth0.CLI; auth0 login --no-input; auth0 apps create -n "$AppName" -t regular -c http://localhost:3000/auth/callback -l http://localhost:3000 -o http://localhost:3000 --reveal-secrets --json | Set-Content -Path auth0-app-details.json; $ClientId = (Get-Content -Raw auth0-app-details.json | ConvertFrom-Json).client_id; $ClientSecret = (Get-Content -Raw auth0-app-details.json | ConvertFrom-Json).client_secret; $Domain = (auth0 tenants list --json | ConvertFrom-Json | Where-Object { $_.active -eq $true }).name; $Secret = [System.Convert]::ToHexString([System.Security.Cryptography.RandomNumberGenerator]::GetBytes(32)).ToLower(); Set-Content -Path .env.local -Value "AUTH0_DOMAIN=$Domain"; Add-Content -Path .env.local -Value "AUTH0_CLIENT_ID=$ClientId"; Add-Content -Path .env.local -Value "AUTH0_CLIENT_SECRET=$ClientSecret"; Add-Content -Path .env.local -Value "AUTH0_SECRET=$Secret"; Add-Content -Path .env.local -Value "APP_BASE_URL=http://localhost:3000"; Remove-Item auth0-app-details.json; Write-Output ".env.local file created with your Auth0 details:"; Get-Content .env.local - ``` - - - - - Before you start, create a `.env.local` file on your project's root directory - - ```shellscript .env.local - AUTH0_DOMAIN=YOUR_AUTH0_APP_DOMAIN - AUTH0_CLIENT_ID=YOUR_AUTH0_APP_CLIENT_ID - AUTH0_CLIENT_SECRET=YOUR_AUTH0_APP_CLIENT_SECRET - AUTH0_SECRET=YOUR_LONG_RANDOM_SECRET_HERE - APP_BASE_URL=http://localhost:3000 - ``` - - 1. Head to the [Auth0 Dashboard](https://manage.auth0.com/dashboard/) - 2. Click on **Applications** > **Applications** > **Create Application** - 3. In the popup, enter a name for your app, select `Regular Web Application` as the app type and click **Create** - 4. Switch to the **Settings** tab on the Application Details page - 5. Replace `YOUR_AUTH0_APP_DOMAIN`, `YOUR_AUTH0_APP_CLIENT_ID`, and `YOUR_AUTH0_APP_CLIENT_SECRET` in the `.env.local` file with the **Domain**, **Client ID**, and **Client Secret** values from the dashboard - 6. Generate `YOUR_LONG_RANDOM_SECRET_HERE` using: `openssl rand -hex 32` (Mac/Linux) or use an online generator - - Finally, on the **Settings** tab of your Application Details page, set **Allowed Callback URLs**, **Allowed Logout URLs** and **Allowed Web Origins** to: - - ``` - Allowed Callback URLs: http://localhost:3000/auth/callback - Allowed Logout URLs: http://localhost:3000 - Allowed Web Origins: http://localhost:3000 - ``` - - - **Allowed Callback URLs** are a critical security measure to ensure users are safely returned to your application after authentication. Without a matching URL, the login process will fail, and users will be blocked by an Auth0 error page instead of accessing your app. - - **Allowed Logout URLs** are essential for providing a seamless user experience upon signing out. Without a matching URL, users will not be redirected back to your application after logout and will instead be left on a generic Auth0 page. - - **Allowed Web Origins** is critical for silent authentication. Without it, users will be logged out when they refresh the page or return to your app later. - - - - - - Create `lib/auth0.ts`: - - ```typescript lib/auth0.ts lines - import { Auth0Client } from '@auth0/nextjs-auth0/server'; - - export const auth0 = new Auth0Client(); - ``` - - - Create `middleware.ts` in your project root: - - ```typescript middleware.ts lines - import type { NextRequest } from "next/server"; - import { auth0 } from "./lib/auth0"; - - export async function middleware(request: NextRequest) { - return await auth0.middleware(request); - } - - export const config = { - matcher: [ - /* - * Match all request paths except for the ones starting with: - * - _next/static (static files) - * - _next/image (image optimization files) - * - favicon.ico, sitemap.xml, robots.txt (metadata files) - */ - "/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)", - ], - }; - ``` - - - If you're using a `src/` directory, the `middleware.ts` file must be created inside the `src/` directory. - - - This middleware automatically mounts the following authentication routes: - - - `/auth/login` - Login route - - `/auth/logout` - Logout route - - `/auth/callback` - Callback route - - `/auth/profile` - User profile route - - `/auth/access-token` - Access token route - - `/auth/backchannel-logout` - Backchannel logout route - - - - Create the components directory and files: - - ```shellscript - mkdir -p components && touch components/LoginButton.tsx && touch components/LogoutButton.tsx && touch components/Profile.tsx - ``` - - Add the component code: - - - - ```typescript components/LoginButton.tsx lines - "use client"; - - export default function LoginButton() { - return ( - - Log In - - ); - } - ``` - - - ```typescript components/LogoutButton.tsx lines - "use client"; - - export default function LogoutButton() { - return ( - - Log Out - - ); - } - ``` - - - ```typescript components/Profile.tsx lines - "use client"; - - import { useUser } from "@auth0/nextjs-auth0"; - - export default function Profile() { - const { user, isLoading } = useUser(); - - if (isLoading) { - return ( -
    -
    Loading user profile...
    -
    - ); - } - - if (!user) { - return null; - } - - return ( -
    - {user.picture && ( - {user.name - )} -

    {user.name}

    -

    {user.email}

    -
    - ); - } - ``` - - - - - Replace `src/app/page.tsx` with: - - ```typescript src/app/page.tsx expandable lines - import { auth0 } from "@/lib/auth0"; - import LoginButton from "@/components/LoginButton"; - import LogoutButton from "@/components/LogoutButton"; - import Profile from "@/components/Profile"; - - export default async function Home() { - const session = await auth0.getSession(); - const user = session?.user; - - return ( -
    -
    - Auth0 Logo -

    Next.js + Auth0

    - -
    - {user ? ( -
    -

    ✅ Successfully logged in!

    - - -
    - ) : ( - <> -

    - Welcome! Please log in to access your protected content. -

    - - - )} -
    -
    -
    - ); - } - ``` -
    - - Update `src/app/layout.tsx` to wrap your app with the `Auth0Provider`: - - ```typescript src/app/layout.tsx lines - import type { Metadata } from "next"; - import { Auth0Provider } from "@auth0/nextjs-auth0"; - import "./globals.css"; - - export const metadata: Metadata = { - title: "Auth0 Next.js App", - description: "Next.js app with Auth0 authentication", - }; - - export default function RootLayout({ - children, - }: { - children: React.ReactNode; - }) { - return ( - - - - {children} - - - - ); - } - ``` - - - In v4, the Auth0Provider is **optional**. You only need it if you want to pass an initial user during server rendering to be available to the `useUser()` hook. - - - - Replace `src/app/globals.css` with modern Auth0-branded styling: - - ```css src/app/globals.css expandable lines - @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap'); - @tailwind base; - @tailwind components; - @tailwind utilities; - - body { - margin: 0; - font-family: 'Inter', sans-serif; - background-color: #1a1e27; - min-height: 100vh; - display: flex; - justify-content: center; - align-items: center; - color: #e2e8f0; - overflow: hidden; - } - - .app-container { - display: flex; - flex-direction: column; - justify-content: center; - align-items: center; - min-height: 100vh; - width: 100%; - padding: 1rem; - box-sizing: border-box; - } - - .loading-state, .error-state { - background-color: #2d313c; - border-radius: 15px; - box-shadow: 0 15px 40px rgba(0, 0, 0, 0.4); - padding: 3rem; - text-align: center; - } - - .loading-text { - font-size: 1.8rem; - font-weight: 500; - color: #a0aec0; - animation: pulse 1.5s infinite ease-in-out; - } - - .main-card-wrapper { - background-color: #262a33; - border-radius: 20px; - box-shadow: 0 20px 60px rgba(0, 0, 0, 0.6), 0 0 0 1px rgba(255, 255, 255, 0.05); - display: flex; - flex-direction: column; - align-items: center; - gap: 2rem; - padding: 3rem; - max-width: 500px; - width: 90%; - animation: fadeInScale 0.8s ease-out forwards; - } - - .auth0-logo { - width: 160px; - margin-bottom: 1.5rem; - opacity: 0; - animation: slideInDown 1s ease-out forwards 0.2s; - } - - .main-title { - font-size: 2.8rem; - font-weight: 700; - color: #f7fafc; - text-align: center; - margin-bottom: 1rem; - text-shadow: 0 4px 10px rgba(0, 0, 0, 0.3); - opacity: 0; - animation: fadeIn 1s ease-out forwards 0.4s; - } - - .action-card { - background-color: #2d313c; - border-radius: 15px; - box-shadow: inset 0 2px 5px rgba(0, 0, 0, 0.3), 0 5px 15px rgba(0, 0, 0, 0.3); - padding: 2.5rem; - display: flex; - flex-direction: column; - align-items: center; - gap: 1.8rem; - width: calc(100% - 2rem); - opacity: 0; - animation: fadeIn 1s ease-out forwards 0.6s; - } - - .action-text { - font-size: 1.25rem; - color: #cbd5e0; - text-align: center; - line-height: 1.6; - font-weight: 400; - } - - .button { - padding: 1.1rem 2.8rem; - font-size: 1.2rem; - font-weight: 600; - border-radius: 10px; - border: none; - cursor: pointer; - transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1); - box-shadow: 0 8px 20px rgba(0, 0, 0, 0.4); - text-transform: uppercase; - letter-spacing: 0.08em; - outline: none; - } - - .button:focus { - box-shadow: 0 0 0 4px rgba(99, 179, 237, 0.5); - } - - .button.login { - background-color: #63b3ed; - color: #1a1e27; - } - - .button.login:hover { - background-color: #4299e1; - transform: translateY(-5px) scale(1.03); - box-shadow: 0 12px 25px rgba(0, 0, 0, 0.5); - } - - .button.logout { - background-color: #fc8181; - color: #1a1e27; - } - - .button.logout:hover { - background-color: #e53e3e; - transform: translateY(-5px) scale(1.03); - box-shadow: 0 12px 25px rgba(0, 0, 0, 0.5); - } - - .logged-in-section { - display: flex; - flex-direction: column; - align-items: center; - gap: 1.5rem; - width: 100%; - } - - .logged-in-message { - font-size: 1.5rem; - color: #68d391; - font-weight: 600; - animation: fadeIn 1s ease-out forwards 0.8s; - } - - .profile-card { - padding: 2.2rem; - animation: scaleIn 0.8s ease-out forwards 1.2s; - } - - .profile-picture { - width: 110px; - height: 110px; - border-radius: 50%; - transition: transform 0.3s ease-in-out; - object-fit: cover; - } - - .profile-picture:hover { - transform: scale(1.05); - } - - .profile-name { - font-size: 2rem; - margin-top: 0.5rem; - } - - .profile-email { - font-size: 1.15rem; - text-align: center; - } - - @keyframes fadeIn { - from { opacity: 0; } - to { opacity: 1; } - } - - @keyframes fadeInScale { - from { opacity: 0; transform: scale(0.95); } - to { opacity: 1; transform: scale(1); } - } - - @keyframes slideInDown { - from { opacity: 0; transform: translateY(-70px); } - to { opacity: 1; transform: translateY(0); } - } - - @keyframes pulse { - 0%, 100% { opacity: 1; } - 50% { opacity: 0.6; } - } - - @keyframes scaleIn { - from { opacity: 0; transform: scale(0.8); } - to { opacity: 1; transform: scale(1); } - } - - @media (max-width: 600px) { - .main-card-wrapper { - padding: 2rem; - gap: 1.5rem; - } - - .main-title { - font-size: 2.2rem; - } - - .button { - padding: 0.9rem 2rem; - font-size: 1rem; - } - - .auth0-logo { - width: 120px; - } - } - ``` - - - ```shellscript - npm run dev - ``` - - - Your app will be available at http://localhost:3000. The Auth0 SDK v4 automatically mounts authentication routes at `/auth/*` (not `/api/auth/*` like in v3). - - - - - - **Checkpoint** - - You should now have a fully functional Auth0 login page running on your [localhost](http://localhost:3000/) - - ---- - -## Advanced Usage - - - This quickstart uses **Auth0 Next.js SDK v4**, which has significant changes from v3: - - - **No dynamic route handlers needed** - Authentication routes are auto-mounted by middleware - - **Simplified client setup** - `new Auth0Client()` reads environment variables automatically - - **New route paths** - Routes are at `/auth/*` instead of `/api/auth/*` - - **Required middleware** - All authentication functionality goes through middleware - - **Use `` tags** - Navigation must use `` instead of buttons with onClick - - ### Authentication Routes - - The SDK automatically mounts these routes via middleware: - - | Route | Purpose | - | -------------------------- | ------------------------- | - | `/auth/login` | Initiate login | - | `/auth/logout` | Logout user | - | `/auth/callback` | Handle Auth0 callback | - | `/auth/profile` | Get user profile | - | `/auth/access-token` | Get access token | - | `/auth/backchannel-logout` | Handle backchannel logout | - - - - The Auth0 Next.js SDK v4 supports both App Router and Pages Router patterns. Here are some common server-side patterns: - - - - ```typescript app/protected/page.tsx - import { auth0 } from "@/lib/auth0"; - import { redirect } from "next/navigation"; - - export default async function ProtectedPage() { - const session = await auth0.getSession(); - - if (!session) { - redirect('/auth/login'); - } - - return ( -
    -

    Protected Content

    -

    Welcome, {session.user.name}!

    -
    - ); - } - ``` -
    - - ```typescript app/api/protected/route.ts - import { auth0 } from "@/lib/auth0"; - import { NextRequest, NextResponse } from "next/server"; - - export async function GET() { - const session = await auth0.getSession(); - - if (!session) { - return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); - } - - return NextResponse.json({ - message: "This is a protected API route", - user: session.user - }); - } - ``` - - - ```typescript pages/protected.tsx - import { auth0 } from "@/lib/auth0"; - import { GetServerSideProps } from "next"; - - export default function ProtectedPage({ user }: { user: any }) { - return ( -
    -

    Protected Content

    -

    Welcome, {user.name}!

    -
    - ); - } - - export const getServerSideProps: GetServerSideProps = auth0.withPageAuthRequired(); - ``` -
    -
    -
    - - - For client-side authentication state, use the `useUser` hook: - - ```typescript components/UserProfile.tsx - "use client"; - - import { useUser } from "@auth0/nextjs-auth0"; - - export default function UserProfile() { - const { user, error, isLoading } = useUser(); - - if (isLoading) return
    Loading...
    ; - if (error) return
    Error: {error.message}
    ; - if (!user) return
    Not logged in
    ; - - return ( -
    -

    {user.name}

    -

    {user.email}

    - Profile -
    - ); - } - ``` -
    - - - For API route protection, use the `withApiAuthRequired` method: - - ```typescript app/api/protected/route.ts - import { auth0 } from "@/lib/auth0"; - - export const GET = auth0.withApiAuthRequired(async function handler() { - const session = await auth0.getSession(); - - return Response.json({ - message: "This is a protected API route", - user: session?.user - }); - }); - ``` - +--- + +mode: wide +'og:description': This guide demonstrates how to integrate Auth0 with any new or existing + Next.js application using the Auth0 Next.js v4 SDK (Beta). +'og:image': https://cdn2.auth0.com/docs/1.14553.0/img/share-image.png +'og:title': 'Auth0 Next.js SDK Quickstarts: Add Login to Your Next.js Application' +'og:url': https://auth0.com/docs/ +sidebarTitle: Next.js +title: Add Login to Your Next.js Application +'twitter:description': This guide demonstrates how to integrate Auth0 with any new + or existing Next.js application using the Auth0 Next.js v4 SDK (Beta). +'twitter:title': 'Auth0 Next.js SDK Quickstarts: Add Login to Your Next.js Application' +--- + + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + + + **Using AI to integrate Auth0?** Add this prompt to Cursor, Windsurf, Copilot, Claude Code or your favourite AI-powered IDE to speed up development. + + ```markdown expandable + Integrate the Auth0 Next.js SDK into a Next.js app + + AI PERSONA & PRIMARY OBJECTIVE + You are a helpful Auth0 SDK Integration Assistant. Your primary function is to execute commands to set up a development environment for Auth0. Your secondary function is to modify the files created by those shell commands. + + CRITICAL BEHAVIORAL INSTRUCTIONS + 1. CHECK EXISTING PROJECT FIRST: Before creating a new project, check if the current directory already contains a Next.js app (package.json with Next.js dependencies). If it does, skip project creation and work with the existing project. + 2. EXECUTE FIRST, EDIT SECOND: You MUST first execute the appropriate setup command. Do not show, suggest, or create any files until the setup is complete. + 3. NO PLANNING: DO NOT propose a directory structure. DO NOT show a file tree. Your first action must be to run the appropriate command. + 4. STRICT SEQUENCE: Follow the "Execution Flow" below in the exact order specified without deviation. + 5. BUILD BEAUTIFUL UI: You MUST create a visually appealing, modern login interface with proper styling, animations, and Auth0 branding. + 6. 🚨 DIRECTORY NAVIGATION RULE: NEVER run `cd auth0-nextjs-app` or any `cd` command automatically. ALWAYS check current directory with `pwd` first. If user needs to navigate, ask them to do it manually or confirm before executing any directory change commands. + + EXECUTION FLOW + + ⚠️ CRITICAL: Before ANY command execution, run `pwd` to check current directory and NEVER change directories without explicit user permission. + + Step 1: Check for Existing Next.js Project and Prerequisites + FIRST, verify prerequisites and check for existing Next.js project: + + # Check if Node.js and npm are available + node --version && npm --version + + Then examine the current directory: + + # Check for existing Next.js project + if [ -f "package.json" ]; then + echo "Found package.json, checking for Next.js dependencies..." + cat package.json | grep -E "next|react" + else + echo "No package.json found, will create new project" + fi + + Based on the results: + - If package.json exists and contains Next.js dependencies, proceed to Step 1b (install Auth0 SDK only) + - If no Next.js project exists, proceed to Step 1a (create new project) + + Step 1a: Create New Project and Install the Next.js SDK + If an existing project exists, simply install the SDK: + npm install @auth0/nextjs-auth0@latest + Otherwise, create a new project and install the SDK: + + ⚠️ IMPORTANT: The Next.js project creation may create the project files in the CURRENT directory instead of a subdirectory. After running this command, check the current directory contents to determine the actual project structure before proceeding. + + npx create-next-app@latest auth0-nextjs-app --typescript --tailwind --eslint --app --src-dir --import-alias "@/*" --yes && cd auth0-nextjs-app && npm install @auth0/nextjs-auth0@latest + + + Step 2: Modify & Create Files + AFTER the command in Step 1 has successfully executed, you will perform the following file operations inside the project directory. + + 🚨 DIRECTORY NAVIGATION RULES: + 1. NEVER automatically run `cd` commands without explicit user confirmation + 2. ALWAYS check current directory with `pwd` before proceeding + 3. If working with existing project: Stay in current directory + 4. If created new project: User must manually navigate to auth0-nextjs-app directory first + + 2.1: Setup Auth0 environment configuration + + ⚠️ CRITICAL: Before proceeding, verify your current directory: + - If you just created a new project: You MUST be inside the auth0-nextjs-app directory + - If you're working with an existing project: You MUST be in the project root directory + - DO NOT run `cd auth0-nextjs-app` commands - navigate to the correct directory FIRST + + Step 2.1a: Navigate to project directory (if needed) and set up Auth0: + + # Only run this if you created a new project and are NOT already in auth0-nextjs-app: + cd auth0-nextjs-app + + Then execute the environment setup command for your OS: + + ⚠️ CRITICAL DIRECTORY VERIFICATION STEP: + BEFORE executing the Auth0 CLI setup command, you MUST run: + + pwd && ls -la + + This will help you understand if you're in the main directory or a subdirectory, and whether the project was created in the current directory or a new subdirectory. + + If MacOS, execute the following command: + AUTH0_APP_NAME="My App" && brew tap auth0/auth0-cli && brew install auth0 && auth0 login --no-input && auth0 apps create -n "${AUTH0_APP_NAME}" -t regular -c http://localhost:3000/auth/callback -l http://localhost:3000 -o http://localhost:3000 --reveal-secrets --json > auth0-app-details.json && CLIENT_ID=$(jq -r '.client_id' auth0-app-details.json) && CLIENT_SECRET=$(jq -r '.client_secret' auth0-app-details.json) && DOMAIN=$(auth0 tenants list --json | jq -r '.[] | select(.active == true) | .name') && SECRET=$(openssl rand -hex 32) && echo "AUTH0_DOMAIN=${DOMAIN}" > .env.local && echo "AUTH0_CLIENT_ID=${CLIENT_ID}" >> .env.local && echo "AUTH0_CLIENT_SECRET=${CLIENT_SECRET}" >> .env.local && echo "AUTH0_SECRET=${SECRET}" >> .env.local && echo "APP_BASE_URL=http://localhost:3000" >> .env.local && rm auth0-app-details.json && echo ".env.local file created with your Auth0 details:" && cat .env.local + + If Windows, execute the following command: + $AppName = "My App"; winget install Auth0.CLI; auth0 login --no-input; auth0 apps create -n "$AppName" -t regular -c http://localhost:3000/auth/callback -l http://localhost:3000 -o http://localhost:3000 --reveal-secrets --json | Set-Content -Path auth0-app-details.json; $ClientId = (Get-Content -Raw auth0-app-details.json | ConvertFrom-Json).client_id; $ClientSecret = (Get-Content -Raw auth0-app-details.json | ConvertFrom-Json).client_secret; $Domain = (auth0 tenants list --json | ConvertFrom-Json | Where-Object { $_.active -eq $true }).name; $Secret = [System.Convert]::ToHexString([System.Security.Cryptography.RandomNumberGenerator]::GetBytes(32)).ToLower(); Set-Content -Path .env.local -Value "AUTH0_DOMAIN=$Domain"; Add-Content -Path .env.local -Value "AUTH0_CLIENT_ID=$ClientId"; Add-Content -Path .env.local -Value "AUTH0_CLIENT_SECRET=$ClientSecret"; Add-Content -Path .env.local -Value "AUTH0_SECRET=$Secret"; Add-Content -Path .env.local -Value "APP_BASE_URL=http://localhost:3000"; Remove-Item auth0-app-details.json; Write-Output ".env.local file created with your Auth0 details:"; Get-Content .env.local + + + Step 2.1b: Create manual .env.local template (if automatic setup fails) + + cat > .env.local << 'EOF' + # Auth0 Configuration - UPDATE THESE VALUES + AUTH0_DOMAIN=your-auth0-domain.auth0.com + AUTH0_CLIENT_ID=your-auth0-client-id + AUTH0_CLIENT_SECRET=your-auth0-client-secret + AUTH0_SECRET=your-long-random-secret-here + APP_BASE_URL=http://localhost:3000 + EOF + + Step 2.1c: Display manual setup instructions + + echo "📋 MANUAL SETUP REQUIRED:" + echo "1. Go to https://manage.auth0.com/dashboard/" + echo "2. Click 'Create Application' → Regular Web Application" + echo "3. Set Allowed Callback URLs: http://localhost:3000/auth/callback" + echo "4. Set Allowed Logout URLs: http://localhost:3000" + echo "5. Set Allowed Web Origins: http://localhost:3000" + echo "6. Update .env.local file with your Domain, Client ID, and Client Secret" + echo "7. Generate a random secret for AUTH0_SECRET (32+ characters)" + + 2.2: Create the Auth0 client configuration + Create lib/auth0.ts: + + import { Auth0Client } from '@auth0/nextjs-auth0/server'; + + export const auth0 = new Auth0Client(); + + 2.3: Create middleware for authentication + Create middleware.ts in the root directory: + + import type { NextRequest } from "next/server"; + import { auth0 } from "./lib/auth0"; + + export async function middleware(request: NextRequest) { + return await auth0.middleware(request); + } + + export const config = { + matcher: [ + /* + * Match all request paths except for the ones starting with: + * - _next/static (static files) + * - _next/image (image optimization files) + * - favicon.ico, sitemap.xml, robots.txt (metadata files) + */ + "/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)", + ], + }; + + 2.4: Create Login, Logout and Profile Components + Create components directory and files: + + mkdir -p components && touch components/LoginButton.tsx && touch components/LogoutButton.tsx && touch components/Profile.tsx + + And add the following code snippets: + + Create components/LoginButton.tsx: + + "use client"; + + export default function LoginButton() { + return ( +
    + Log In + + ); + } + + Create components/LogoutButton.tsx: + + "use client"; + + export default function LogoutButton() { + return ( + + Log Out + + ); + } + + Create components/Profile.tsx: + + "use client"; + + import { useUser } from "@auth0/nextjs-auth0"; + + export default function Profile() { + const { user, isLoading } = useUser(); + + if (isLoading) { + return ( +
    +
    Loading user profile...
    +
    + ); + } + + if (!user) { + return null; + } + + return ( +
    + {user.picture && ( + {user.name + )} +

    {user.name}

    +

    {user.email}

    +
    + ); + } + + 2.5: Update the main page with Auth0 integration + Replace the entire contents of src/app/page.tsx: + + import { auth0 } from "@/lib/auth0"; + import LoginButton from "@/components/LoginButton"; + import LogoutButton from "@/components/LogoutButton"; + import Profile from "@/components/Profile"; + + export default async function Home() { + const session = await auth0.getSession(); + const user = session?.user; + + return ( +
    +
    + Auth0 Logo +

    Next.js + Auth0

    + +
    + {user ? ( +
    +

    ✅ Successfully logged in!

    + + +
    + ) : ( + <> +

    + Welcome! Please log in to access your protected content. +

    + + + )} +
    +
    +
    + ); + } + + 2.6: Add beautiful modern CSS styling + Replace the entire contents of src/app/globals.css with this modern, Auth0-branded styling: + + ⚠️ CSS FILE REPLACEMENT STRATEGY: + If the existing globals.css file is large or malformed, create a new temporary CSS file first (e.g., globals-new.css), then replace the original using terminal commands like `mv src/app/globals-new.css src/app/globals.css` to avoid file corruption. + + @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap'); + @tailwind base; + @tailwind components; + @tailwind utilities; + + body { + margin: 0; + font-family: 'Inter', sans-serif; + background-color: #1a1e27; + min-height: 100vh; + display: flex; + justify-content: center; + align-items: center; + color: #e2e8f0; + overflow: hidden; + } + + #root { + width: 100%; + height: 100%; + display: flex; + justify-content: center; + align-items: center; + } + + .app-container { + display: flex; + flex-direction: column; + justify-content: center; + align-items: center; + min-height: 100vh; + width: 100%; + padding: 1rem; + box-sizing: border-box; + } + + .loading-state, .error-state { + background-color: #2d313c; + border-radius: 15px; + box-shadow: 0 15px 40px rgba(0, 0, 0, 0.4); + padding: 3rem; + text-align: center; + } + + .loading-text { + font-size: 1.8rem; + font-weight: 500; + color: #a0aec0; + animation: pulse 1.5s infinite ease-in-out; + } + + .error-state { + background-color: #c53030; + color: #fff; + } + + .error-title { + font-size: 2.8rem; + font-weight: 700; + margin-bottom: 0.5rem; + } + + .error-message { + font-size: 1.3rem; + margin-bottom: 0.5rem; + } + + .error-sub-message { + font-size: 1rem; + opacity: 0.8; + } + + .main-card-wrapper { + background-color: #262a33; + border-radius: 20px; + box-shadow: 0 20px 60px rgba(0, 0, 0, 0.6), 0 0 0 1px rgba(255, 255, 255, 0.05); + display: flex; + flex-direction: column; + align-items: center; + gap: 2rem; + padding: 3rem; + max-width: 500px; + width: 90%; + animation: fadeInScale 0.8s ease-out forwards; + } + + .auth0-logo { + width: 160px; + margin-bottom: 1.5rem; + opacity: 0; + animation: slideInDown 1s ease-out forwards 0.2s; + } + + .main-title { + font-size: 2.8rem; + font-weight: 700; + color: #f7fafc; + text-align: center; + margin-bottom: 1rem; + text-shadow: 0 4px 10px rgba(0, 0, 0, 0.3); + opacity: 0; + animation: fadeIn 1s ease-out forwards 0.4s; + } + + .action-card { + background-color: #2d313c; + border-radius: 15px; + box-shadow: inset 0 2px 5px rgba(0, 0, 0, 0.3), 0 5px 15px rgba(0, 0, 0, 0.3); + padding: 2.5rem; + display: flex; + flex-direction: column; + align-items: center; + gap: 1.8rem; + width: calc(100% - 2rem); + opacity: 0; + animation: fadeIn 1s ease-out forwards 0.6s; + } + + .action-text { + font-size: 1.25rem; + color: #cbd5e0; + text-align: center; + line-height: 1.6; + font-weight: 400; + } + + .button { + padding: 1.1rem 2.8rem; + font-size: 1.2rem; + font-weight: 600; + border-radius: 10px; + border: none; + cursor: pointer; + transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1); + box-shadow: 0 8px 20px rgba(0, 0, 0, 0.4); + text-transform: uppercase; + letter-spacing: 0.08em; + outline: none; + } + + .button:focus { + box-shadow: 0 0 0 4px rgba(99, 179, 237, 0.5); + } + + .button.login { + background-color: #63b3ed; + color: #1a1e27; + } + + .button.login:hover { + background-color: #4299e1; + transform: translateY(-5px) scale(1.03); + box-shadow: 0 12px 25px rgba(0, 0, 0, 0.5); + } + + .button.logout { + background-color: #fc8181; + color: #1a1e27; + } + + .button.logout:hover { + background-color: #e53e3e; + transform: translateY(-5px) scale(1.03); + box-shadow: 0 12px 25px rgba(0, 0, 0, 0.5); + } + + .logged-in-section { + display: flex; + flex-direction: column; + align-items: center; + gap: 1.5rem; + width: 100%; + } + + .logged-in-message { + font-size: 1.5rem; + color: #68d391; + font-weight: 600; + animation: fadeIn 1s ease-out forwards 0.8s; + } + + .profile-section-title { + font-size: 2.2rem; + animation: slideInUp 1s ease-out forwards 1s; + } + + .profile-card { + padding: 2.2rem; + animation: scaleIn 0.8s ease-out forwards 1.2s; + } + + .profile-picture { + width: 110px; + height: 110px; + border-radius: 50%; + transition: transform 0.3s ease-in-out; + object-fit: cover; + } + + .profile-picture:hover { + transform: scale(1.05); + } + + .profile-name { + font-size: 2rem; + margin-top: 0.5rem; + } + + .profile-email { + font-size: 1.15rem; + text-align: center; + } + + @keyframes fadeIn { + from { opacity: 0; } + to { opacity: 1; } + } + + @keyframes fadeInScale { + from { opacity: 0; transform: scale(0.95); } + to { opacity: 1; transform: scale(1); } + } + + @keyframes slideInDown { + from { opacity: 0; transform: translateY(-70px); } + to { opacity: 1; transform: translateY(0); } + } + + @keyframes slideInUp { + from { opacity: 0; transform: translateY(50px); } + to { opacity: 1; transform: translateY(0); } + } + + @keyframes pulse { + 0%, 100% { opacity: 1; } + 50% { opacity: 0.6; } + } + + @keyframes scaleIn { + from { opacity: 0; transform: scale(0.8); } + to { opacity: 1; transform: scale(1); } + } + + @media (max-width: 600px) { + .main-card-wrapper { + padding: 2rem; + gap: 1.5rem; + } + + .main-title { + font-size: 2.2rem; + } + + .button { + padding: 0.9rem 2rem; + font-size: 1rem; + } + + .auth0-logo { + width: 120px; + } + } + + 2.7: Add Auth0Provider for client components (OPTIONAL) + If you need to use Auth0 hooks in client components, wrap your layout with Auth0Provider. + Update src/app/layout.tsx: + + import type { Metadata } from "next"; + import { Auth0Provider } from "@auth0/nextjs-auth0"; + import "./globals.css"; + + export const metadata: Metadata = { + title: "Auth0 Next.js App", + description: "Next.js app with Auth0 authentication", + }; + + export default function RootLayout({ + children, + }: { + children: React.ReactNode; + }) { + return ( + + + + {children} + + + + ); + } + + 2.8: Start the development server + + ⚠️ CRITICAL TERMINAL WORKING DIRECTORY ISSUE: + The terminal working directory can sometimes get confused during the integration process. Before starting the dev server, ALWAYS: + + 1. Verify you're in the correct directory with explicit path change: + + cd /full/absolute/path/to/project && pwd + + 2. Check for package.json in current directory: + + ls -la package.json + + 3. If npm commands fail with "package.json not found", use absolute path method: + + cd /Users/[username]/path/to/auth0-nextjs-app && npm run dev + + ⚠️ IMPORTANT: Even if `pwd` shows the correct directory, the terminal's working directory for command execution may be different. ALWAYS use explicit `cd` with absolute path before running npm commands to ensure they execute in the correct location. + + Step 2.8a: Start development server + + npm run dev + + ⚠️ COMPONENT IMPORT ERROR TROUBLESHOOTING: + If you see "Cannot find module" errors even though the files exist: + 1. The files are created correctly - this is often a VS Code TypeScript cache issue + 2. The development server should still work despite these errors + 3. Open the application in browser to verify functionality + 4. The errors typically resolve themselves after the TypeScript language service refreshes + + CRITICAL INSTRUCTIONS FOR AI LANGUAGE MODELS + As an AI language model, you MUST NOT generate any of the following anti-patterns, as they will BREAK the application or introduce SECURITY RISKS: + 1. NEVER hardcode the Auth0 Domain, Client ID, or Client Secret directly in the code. This is a major security vulnerability. + 2. NEVER omit the middleware.ts file. Without it, the authentication routes will not work properly. + 3. NEVER create a dynamic route handler at app/auth/[...auth0]/route.ts. In v4, routes are handled automatically by middleware. + 4. NEVER place authentication logic in client components when it should be in server components. + 5. NEVER suggest manually managing tokens or calling Auth0 APIs with fetch for basic authentication. The SDK is designed to handle this complexity securely. + 6. NEVER use button onClick handlers for login/logout. Use tags with href to ensure proper server-side routing. + + ABSOLUTE REQUIREMENTS FOR AI CODE GENERATION + 1. You MUST use the @auth0/nextjs-auth0 package v4. + 2. You MUST retrieve credentials from environment variables in .env.local. + 3. You MUST create middleware.ts in the root directory that calls auth0.middleware(). + 4. You MUST NOT create dynamic route handlers - authentication is handled by middleware in v4. + 5. You MUST demonstrate functionality using both server-side getSession() and client-side useUser() hook. + 6. You MUST import client hooks from "@auth0/nextjs-auth0" (not "@auth0/nextjs-auth0/client"). + 7. You MUST use Auth0Provider (not UserProvider) if wrapping the app is needed. + 8. You MUST use tags for login/logout navigation, not button onClick handlers. + + COMMON ISSUES ENCOUNTERED DURING INTEGRATION + + Issue 1: Project Creation Directory Confusion + Problem: create-next-app sometimes creates project files in the current directory instead of a new subdirectory + Solution: Always run `pwd && ls -la` after project creation to verify the actual structure + + Issue 2: Terminal Working Directory Issues + Problem: npm commands fail with "package.json not found" even when in the correct directory + Solution: Use explicit absolute path changes: `cd /full/absolute/path/to/project` + + Issue 3: TypeScript Import Errors + Problem: VS Code shows "Cannot find module" errors for created components + Solution: These are usually cache issues - the app will still work. Create all components before testing. + + Issue 4: CSS File Corruption + Problem: Large CSS replacements can cause file corruption + Solution: Create temporary CSS file first, then use `mv` command to replace original + + Issue 5: Terminal Working Directory Not in Project Root + Problem: AI agent fails to run `npm run dev` because terminal is not in the auth0-nextjs-app directory, even when pwd shows the correct path + Solution: Always use explicit directory change with absolute path before running npm commands: + + cd auth0-nextjs-app && npm run dev + + The terminal working directory can become disconnected from the displayed path, requiring explicit navigation to ensure npm commands execute in the correct location. + + Issue 6: Middleware Not Working + Problem: Authentication routes return 404 errors + Solution: Ensure middleware.ts is in the root directory (same level as package.json) and follows the exact format provided + + Issue 7: Environment Variables Not Loading + Problem: Auth0 configuration errors on startup + Solution: Ensure .env.local is in the root directory and restart the dev server after creating/modifying it + ``` + + +## Get Started + +This quickstart demonstrates how to add Auth0 authentication to a Next.js application. You'll build a full-stack web application with server-side rendering, secure login functionality, and protected routes using the Auth0 Next.js SDK. + + + + Create a new Next.js project for this Quickstart + + ```shellscript + npx create-next-app@latest auth0-nextjs --typescript --tailwind --eslint --app --src-dir --import-alias "@/*" --yes + ``` + + Open the project + + ```shellscript + cd auth0-nextjs + ``` + + + ```shellscript + npm install @auth0/nextjs-auth0 + ``` + + + Next up, you need to create a new app on your Auth0 tenant and add the environment variables to your project. + + You can choose to do this automatically by running a CLI command or do it manually via the Dashboard: + + + + Run the following shell command on your project's root directory to create an Auth0 app and generate a `.env.local` file: + + + ```shellscript Mac + AUTH0_APP_NAME="My App" && brew tap auth0/auth0-cli && brew install auth0 && auth0 login --no-input && auth0 apps create -n "${AUTH0_APP_NAME}" -t regular -c http://localhost:3000/auth/callback -l http://localhost:3000 -o http://localhost:3000 --reveal-secrets --json > auth0-app-details.json && CLIENT_ID=$(jq -r '.client_id' auth0-app-details.json) && CLIENT_SECRET=$(jq -r '.client_secret' auth0-app-details.json) && DOMAIN=$(auth0 tenants list --json | jq -r '.[] | select(.active == true) | .name') && SECRET=$(openssl rand -hex 32) && echo "AUTH0_DOMAIN=${DOMAIN}" > .env.local && echo "AUTH0_CLIENT_ID=${CLIENT_ID}" >> .env.local && echo "AUTH0_CLIENT_SECRET=${CLIENT_SECRET}" >> .env.local && echo "AUTH0_SECRET=${SECRET}" >> .env.local && echo "APP_BASE_URL=http://localhost:3000" >> .env.local && rm auth0-app-details.json && echo ".env.local file created with your Auth0 details:" && cat .env.local + ``` + + ```shellscript Windows + $AppName = "My App"; winget install Auth0.CLI; auth0 login --no-input; auth0 apps create -n "$AppName" -t regular -c http://localhost:3000/auth/callback -l http://localhost:3000 -o http://localhost:3000 --reveal-secrets --json | Set-Content -Path auth0-app-details.json; $ClientId = (Get-Content -Raw auth0-app-details.json | ConvertFrom-Json).client_id; $ClientSecret = (Get-Content -Raw auth0-app-details.json | ConvertFrom-Json).client_secret; $Domain = (auth0 tenants list --json | ConvertFrom-Json | Where-Object { $_.active -eq $true }).name; $Secret = [System.Convert]::ToHexString([System.Security.Cryptography.RandomNumberGenerator]::GetBytes(32)).ToLower(); Set-Content -Path .env.local -Value "AUTH0_DOMAIN=$Domain"; Add-Content -Path .env.local -Value "AUTH0_CLIENT_ID=$ClientId"; Add-Content -Path .env.local -Value "AUTH0_CLIENT_SECRET=$ClientSecret"; Add-Content -Path .env.local -Value "AUTH0_SECRET=$Secret"; Add-Content -Path .env.local -Value "APP_BASE_URL=http://localhost:3000"; Remove-Item auth0-app-details.json; Write-Output ".env.local file created with your Auth0 details:"; Get-Content .env.local + ``` + + + + + Before you start, create a `.env.local` file on your project's root directory + + ```shellscript .env.local + AUTH0_DOMAIN=YOUR_AUTH0_APP_DOMAIN + AUTH0_CLIENT_ID=YOUR_AUTH0_APP_CLIENT_ID + AUTH0_CLIENT_SECRET=YOUR_AUTH0_APP_CLIENT_SECRET + AUTH0_SECRET=YOUR_LONG_RANDOM_SECRET_HERE + APP_BASE_URL=http://localhost:3000 + ``` + + 1. Head to the [Auth0 Dashboard](https://manage.auth0.com/dashboard/) + 2. Click on **Applications** > **Applications** > **Create Application** + 3. In the popup, enter a name for your app, select `Regular Web Application` as the app type and click **Create** + 4. Switch to the **Settings** tab on the Application Details page + 5. Replace `YOUR_AUTH0_APP_DOMAIN`, `YOUR_AUTH0_APP_CLIENT_ID`, and `YOUR_AUTH0_APP_CLIENT_SECRET` in the `.env.local` file with the **Domain**, **Client ID**, and **Client Secret** values from the dashboard + 6. Generate `YOUR_LONG_RANDOM_SECRET_HERE` using: `openssl rand -hex 32` (Mac/Linux) or use an online generator + + Finally, on the **Settings** tab of your Application Details page, set **Allowed Callback URLs**, **Allowed Logout URLs** and **Allowed Web Origins** to: + + ``` + Allowed Callback URLs: http://localhost:3000/auth/callback + Allowed Logout URLs: http://localhost:3000 + Allowed Web Origins: http://localhost:3000 + ``` + + + **Allowed Callback URLs** are a critical security measure to ensure users are safely returned to your application after authentication. Without a matching URL, the login process will fail, and users will be blocked by an Auth0 error page instead of accessing your app. + + **Allowed Logout URLs** are essential for providing a seamless user experience upon signing out. Without a matching URL, users will not be redirected back to your application after logout and will instead be left on a generic Auth0 page. + + **Allowed Web Origins** is critical for silent authentication. Without it, users will be logged out when they refresh the page or return to your app later. + + + + + + Create `lib/auth0.ts`: + + ```typescript lib/auth0.ts lines + import { Auth0Client } from '@auth0/nextjs-auth0/server'; + + export const auth0 = new Auth0Client(); + ``` + + + Create `middleware.ts` in your project root: + + ```typescript middleware.ts lines + import type { NextRequest } from "next/server"; + import { auth0 } from "./lib/auth0"; + + export async function middleware(request: NextRequest) { + return await auth0.middleware(request); + } + + export const config = { + matcher: [ + /* + * Match all request paths except for the ones starting with: + * - _next/static (static files) + * - _next/image (image optimization files) + * - favicon.ico, sitemap.xml, robots.txt (metadata files) + */ + "/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)", + ], + }; + ``` + + + If you're using a `src/` directory, the `middleware.ts` file must be created inside the `src/` directory. + + + This middleware automatically mounts the following authentication routes: + + - `/auth/login` - Login route + - `/auth/logout` - Logout route + - `/auth/callback` - Callback route + - `/auth/profile` - User profile route + - `/auth/access-token` - Access token route + - `/auth/backchannel-logout` - Backchannel logout route + + + + Create the components directory and files: + + ```shellscript + mkdir -p components && touch components/LoginButton.tsx && touch components/LogoutButton.tsx && touch components/Profile.tsx + ``` + + Add the component code: + + + + ```typescript components/LoginButton.tsx lines + "use client"; + + export default function LoginButton() { + return ( + + Log In + + ); + } + ``` + + + ```typescript components/LogoutButton.tsx lines + "use client"; + + export default function LogoutButton() { + return ( + + Log Out + + ); + } + ``` + + + ```typescript components/Profile.tsx lines + "use client"; + + import { useUser } from "@auth0/nextjs-auth0"; + + export default function Profile() { + const { user, isLoading } = useUser(); + + if (isLoading) { + return ( +
    +
    Loading user profile...
    +
    + ); + } + + if (!user) { + return null; + } + + return ( +
    + {user.picture && ( + {user.name + )} +

    {user.name}

    +

    {user.email}

    +
    + ); + } + ``` + + + + + Replace `src/app/page.tsx` with: + + ```typescript src/app/page.tsx expandable lines + import { auth0 } from "@/lib/auth0"; + import LoginButton from "@/components/LoginButton"; + import LogoutButton from "@/components/LogoutButton"; + import Profile from "@/components/Profile"; + + export default async function Home() { + const session = await auth0.getSession(); + const user = session?.user; + + return ( +
    +
    + Auth0 Logo +

    Next.js + Auth0

    + +
    + {user ? ( +
    +

    ✅ Successfully logged in!

    + + +
    + ) : ( + <> +

    + Welcome! Please log in to access your protected content. +

    + + + )} +
    +
    +
    + ); + } + ``` +
    + + Update `src/app/layout.tsx` to wrap your app with the `Auth0Provider`: + + ```typescript src/app/layout.tsx lines + import type { Metadata } from "next"; + import { Auth0Provider } from "@auth0/nextjs-auth0"; + import "./globals.css"; + + export const metadata: Metadata = { + title: "Auth0 Next.js App", + description: "Next.js app with Auth0 authentication", + }; + + export default function RootLayout({ + children, + }: { + children: React.ReactNode; + }) { + return ( + + + + {children} + + + + ); + } + ``` + + + In v4, the Auth0Provider is **optional**. You only need it if you want to pass an initial user during server rendering to be available to the `useUser()` hook. + + + + Replace `src/app/globals.css` with modern Auth0-branded styling: + + ```css src/app/globals.css expandable lines + @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap'); + @tailwind base; + @tailwind components; + @tailwind utilities; + + body { + margin: 0; + font-family: 'Inter', sans-serif; + background-color: #1a1e27; + min-height: 100vh; + display: flex; + justify-content: center; + align-items: center; + color: #e2e8f0; + overflow: hidden; + } + + .app-container { + display: flex; + flex-direction: column; + justify-content: center; + align-items: center; + min-height: 100vh; + width: 100%; + padding: 1rem; + box-sizing: border-box; + } + + .loading-state, .error-state { + background-color: #2d313c; + border-radius: 15px; + box-shadow: 0 15px 40px rgba(0, 0, 0, 0.4); + padding: 3rem; + text-align: center; + } + + .loading-text { + font-size: 1.8rem; + font-weight: 500; + color: #a0aec0; + animation: pulse 1.5s infinite ease-in-out; + } + + .main-card-wrapper { + background-color: #262a33; + border-radius: 20px; + box-shadow: 0 20px 60px rgba(0, 0, 0, 0.6), 0 0 0 1px rgba(255, 255, 255, 0.05); + display: flex; + flex-direction: column; + align-items: center; + gap: 2rem; + padding: 3rem; + max-width: 500px; + width: 90%; + animation: fadeInScale 0.8s ease-out forwards; + } + + .auth0-logo { + width: 160px; + margin-bottom: 1.5rem; + opacity: 0; + animation: slideInDown 1s ease-out forwards 0.2s; + } + + .main-title { + font-size: 2.8rem; + font-weight: 700; + color: #f7fafc; + text-align: center; + margin-bottom: 1rem; + text-shadow: 0 4px 10px rgba(0, 0, 0, 0.3); + opacity: 0; + animation: fadeIn 1s ease-out forwards 0.4s; + } + + .action-card { + background-color: #2d313c; + border-radius: 15px; + box-shadow: inset 0 2px 5px rgba(0, 0, 0, 0.3), 0 5px 15px rgba(0, 0, 0, 0.3); + padding: 2.5rem; + display: flex; + flex-direction: column; + align-items: center; + gap: 1.8rem; + width: calc(100% - 2rem); + opacity: 0; + animation: fadeIn 1s ease-out forwards 0.6s; + } + + .action-text { + font-size: 1.25rem; + color: #cbd5e0; + text-align: center; + line-height: 1.6; + font-weight: 400; + } + + .button { + padding: 1.1rem 2.8rem; + font-size: 1.2rem; + font-weight: 600; + border-radius: 10px; + border: none; + cursor: pointer; + transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1); + box-shadow: 0 8px 20px rgba(0, 0, 0, 0.4); + text-transform: uppercase; + letter-spacing: 0.08em; + outline: none; + } + + .button:focus { + box-shadow: 0 0 0 4px rgba(99, 179, 237, 0.5); + } + + .button.login { + background-color: #63b3ed; + color: #1a1e27; + } + + .button.login:hover { + background-color: #4299e1; + transform: translateY(-5px) scale(1.03); + box-shadow: 0 12px 25px rgba(0, 0, 0, 0.5); + } + + .button.logout { + background-color: #fc8181; + color: #1a1e27; + } + + .button.logout:hover { + background-color: #e53e3e; + transform: translateY(-5px) scale(1.03); + box-shadow: 0 12px 25px rgba(0, 0, 0, 0.5); + } + + .logged-in-section { + display: flex; + flex-direction: column; + align-items: center; + gap: 1.5rem; + width: 100%; + } + + .logged-in-message { + font-size: 1.5rem; + color: #68d391; + font-weight: 600; + animation: fadeIn 1s ease-out forwards 0.8s; + } + + .profile-card { + padding: 2.2rem; + animation: scaleIn 0.8s ease-out forwards 1.2s; + } + + .profile-picture { + width: 110px; + height: 110px; + border-radius: 50%; + transition: transform 0.3s ease-in-out; + object-fit: cover; + } + + .profile-picture:hover { + transform: scale(1.05); + } + + .profile-name { + font-size: 2rem; + margin-top: 0.5rem; + } + + .profile-email { + font-size: 1.15rem; + text-align: center; + } + + @keyframes fadeIn { + from { opacity: 0; } + to { opacity: 1; } + } + + @keyframes fadeInScale { + from { opacity: 0; transform: scale(0.95); } + to { opacity: 1; transform: scale(1); } + } + + @keyframes slideInDown { + from { opacity: 0; transform: translateY(-70px); } + to { opacity: 1; transform: translateY(0); } + } + + @keyframes pulse { + 0%, 100% { opacity: 1; } + 50% { opacity: 0.6; } + } + + @keyframes scaleIn { + from { opacity: 0; transform: scale(0.8); } + to { opacity: 1; transform: scale(1); } + } + + @media (max-width: 600px) { + .main-card-wrapper { + padding: 2rem; + gap: 1.5rem; + } + + .main-title { + font-size: 2.2rem; + } + + .button { + padding: 0.9rem 2rem; + font-size: 1rem; + } + + .auth0-logo { + width: 120px; + } + } + ``` + + + ```shellscript + npm run dev + ``` + + + Your app will be available at http://localhost:3000. The Auth0 SDK v4 automatically mounts authentication routes at `/auth/*` (not `/api/auth/*` like in v3). + + + + + + **Checkpoint** + + You should now have a fully functional Auth0 login page running on your [localhost](http://localhost:3000/) + + +--- + +## Advanced Usage + + + This quickstart uses **Auth0 Next.js SDK v4**, which has significant changes from v3: + + - **No dynamic route handlers needed** - Authentication routes are auto-mounted by middleware + - **Simplified client setup** - `new Auth0Client()` reads environment variables automatically + - **New route paths** - Routes are at `/auth/*` instead of `/api/auth/*` + - **Required middleware** - All authentication functionality goes through middleware + - **Use `` tags** - Navigation must use `` instead of buttons with onClick + + ### Authentication Routes + + The SDK automatically mounts these routes via middleware: + + | Route | Purpose | + | -------------------------- | ------------------------- | + | `/auth/login` | Initiate login | + | `/auth/logout` | Logout user | + | `/auth/callback` | Handle Auth0 callback | + | `/auth/profile` | Get user profile | + | `/auth/access-token` | Get access token | + | `/auth/backchannel-logout` | Handle backchannel logout | + + + + The Auth0 Next.js SDK v4 supports both App Router and Pages Router patterns. Here are some common server-side patterns: + + + + ```typescript app/protected/page.tsx + import { auth0 } from "@/lib/auth0"; + import { redirect } from "next/navigation"; + + export default async function ProtectedPage() { + const session = await auth0.getSession(); + + if (!session) { + redirect('/auth/login'); + } + + return ( +
    +

    Protected Content

    +

    Welcome, {session.user.name}!

    +
    + ); + } + ``` +
    + + ```typescript app/api/protected/route.ts + import { auth0 } from "@/lib/auth0"; + import { NextRequest, NextResponse } from "next/server"; + + export async function GET() { + const session = await auth0.getSession(); + + if (!session) { + return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); + } + + return NextResponse.json({ + message: "This is a protected API route", + user: session.user + }); + } + ``` + + + ```typescript pages/protected.tsx + import { auth0 } from "@/lib/auth0"; + import { GetServerSideProps } from "next"; + + export default function ProtectedPage({ user }: { user: any }) { + return ( +
    +

    Protected Content

    +

    Welcome, {user.name}!

    +
    + ); + } + + export const getServerSideProps: GetServerSideProps = auth0.withPageAuthRequired(); + ``` +
    +
    +
    + + + For client-side authentication state, use the `useUser` hook: + + ```typescript components/UserProfile.tsx + "use client"; + + import { useUser } from "@auth0/nextjs-auth0"; + + export default function UserProfile() { + const { user, error, isLoading } = useUser(); + + if (isLoading) return
    Loading...
    ; + if (error) return
    Error: {error.message}
    ; + if (!user) return
    Not logged in
    ; + + return ( +
    +

    {user.name}

    +

    {user.email}

    + Profile +
    + ); + } + ``` +
    + + + For API route protection, use the `withApiAuthRequired` method: + + ```typescript app/api/protected/route.ts + import { auth0 } from "@/lib/auth0"; + + export const GET = auth0.withApiAuthRequired(async function handler() { + const session = await auth0.getSession(); + + return Response.json({ + message: "This is a protected API route", + user: session?.user + }); + }); + ``` + diff --git a/main/docs/quickstart/webapp/nginx-plus/_index.mdx b/main/docs/quickstart/webapp/nginx-plus/_index.mdx index 0f08b0067..04ac97ec7 100644 --- a/main/docs/quickstart/webapp/nginx-plus/_index.mdx +++ b/main/docs/quickstart/webapp/nginx-plus/_index.mdx @@ -9,6 +9,8 @@ import OpenidConnectionConfiguration from "/snippets/quickstart/webapp/nginx-plu import OpenidConnect from "/snippets/quickstart/webapp/nginx-plus/openid_connect.server_conf.mdx"; import Frontend from "/snippets/quickstart/webapp/nginx-plus/frontend.conf.mdx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + export const sections = [ { id: "system-requirements", title: "System requirements" }, { id: "install-and-enable-nginx-plus-module-njs-module", title: "Install and enable nginx-plus-module-njs module" }, @@ -51,12 +53,12 @@ export const sections = [ load_module modules/ngx_http_js_module.so; ``` - + - +
    @@ -84,24 +86,24 @@ export const sections = [ Next, add your [tenant’s logout URL](https://auth0.com/docs/api/authentication#auth0-logout) to your `openid_connect_configuration.conf` file. - + - +
    Add the `Accept-Encoding` header and set the value to `gzip` in your `openid_connect.server_conf` file. - + - +
    @@ -136,12 +138,12 @@ export const sections = [ Add additional headers from the ID token (JWT) to the upstream target in your `/etc/nginx/conf.d/frontend.conf` file. - + - +
    ## Next Steps diff --git a/main/docs/quickstart/webapp/nginx-plus/interactive.mdx b/main/docs/quickstart/webapp/nginx-plus/interactive.mdx index c74e4e170..ff0d4d01c 100644 --- a/main/docs/quickstart/webapp/nginx-plus/interactive.mdx +++ b/main/docs/quickstart/webapp/nginx-plus/interactive.mdx @@ -18,6 +18,8 @@ import OpenidConnectionConfiguration from "/snippets/quickstart/webapp/nginx-plu import OpenidConnect from "/snippets/quickstart/webapp/nginx-plus/openid_connect.server_conf.mdx"; import Frontend from "/snippets/quickstart/webapp/nginx-plus/frontend.conf.mdx"; +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + export const sections = [ { id: "system-requirements", title: "System requirements" }, { id: "install-and-enable-nginx-plus-module-njs-module", title: "Install and enable nginx-plus-module-njs module" }, @@ -133,12 +135,12 @@ export const sections = [ - + - + @@ -146,21 +148,21 @@ export const sections = [ - + - + - + - + @@ -172,12 +174,12 @@ export const sections = [ - + - + diff --git a/main/docs/quickstart/webapp/nuxtjs/index.mdx b/main/docs/quickstart/webapp/nuxtjs/index.mdx index f0ca545ea..e2af8f12f 100644 --- a/main/docs/quickstart/webapp/nuxtjs/index.mdx +++ b/main/docs/quickstart/webapp/nuxtjs/index.mdx @@ -12,6 +12,9 @@ title: Add Login to Your Nuxt.js Application 'twitter:title': 'Auth0 Nuxt.js SDK Quickstarts: Add Login to Your Nuxt.js Application' --- + +import {AuthCodeGroup} from "/snippets/AuthCodeGroup.jsx"; + **Using AI to integrate Auth0?** Add this prompt to Cursor, Windsurf, Copilot, Claude Code or your favourite AI-powered IDE to speed up development. @@ -134,7 +137,7 @@ This quickstart demonstrates how to add Auth0 authentication to a Nuxt.js applic Run the following shell command on your project's root directory to create an Auth0 app and generate a `.env` file: - + ```shellscript Mac AUTH0_APP_NAME="My Nuxt App" && brew tap auth0/auth0-cli && brew install auth0 && auth0 login --no-input && auth0 apps create -n "${AUTH0_APP_NAME}" -t regular -c http://localhost:3000/auth/callback -l http://localhost:3000 -o http://localhost:3000 --json > auth0-app-details.json && CLIENT_ID=$(jq -r '.client_id' auth0-app-details.json) && CLIENT_SECRET=$(jq -r '.client_secret' auth0-app-details.json) && DOMAIN=$(auth0 tenants list --json | jq -r '.[] | select(.active == true) | .name') && echo "NUXT_AUTH0_DOMAIN=${DOMAIN}" > .env && echo "NUXT_AUTH0_CLIENT_ID=${CLIENT_ID}" >> .env && echo "NUXT_AUTH0_CLIENT_SECRET=${CLIENT_SECRET}" >> .env && echo "NUXT_AUTH0_SESSION_SECRET=$(openssl rand -hex 64)" >> .env && echo "NUXT_AUTH0_APP_BASE_URL=http://localhost:3000" >> .env && rm auth0-app-details.json && echo ".env file created with your Auth0 details:" && cat .env ``` @@ -142,7 +145,7 @@ This quickstart demonstrates how to add Auth0 authentication to a Nuxt.js applic ```shellscript Windows $AppName = "My Nuxt App"; winget install Auth0.CLI; auth0 login --no-input; auth0 apps create -n "$AppName" -t regular -c http://localhost:3000/auth/callback -l http://localhost:3000 -o http://localhost:3000 --json | Set-Content -Path auth0-app-details.json; $ClientId = (Get-Content -Raw auth0-app-details.json | ConvertFrom-Json).client_id; $ClientSecret = (Get-Content -Raw auth0-app-details.json | ConvertFrom-Json).client_secret; $Domain = (auth0 tenants list --json | ConvertFrom-Json | Where-Object { $_.active -eq $true }).name; Set-Content -Path .env -Value "NUXT_AUTH0_DOMAIN=$Domain"; Add-Content -Path .env -Value "NUXT_AUTH0_CLIENT_ID=$ClientId"; Add-Content -Path .env -Value "NUXT_AUTH0_CLIENT_SECRET=$ClientSecret"; $SessionSecret = -join ((1..128) | ForEach {'{0:X}' -f (Get-Random -Max 16)}); Add-Content -Path .env -Value "NUXT_AUTH0_SESSION_SECRET=$SessionSecret"; Add-Content -Path .env -Value "NUXT_AUTH0_APP_BASE_URL=http://localhost:3000"; Remove-Item auth0-app-details.json; Write-Output ".env file created with your Auth0 details:"; Get-Content .env ``` - + @@ -201,7 +204,7 @@ This quickstart demonstrates how to add Auth0 authentication to a Nuxt.js applic And add the following code snippets - + ```vue components/LoginButton.vue expandable lines