APIにロールベースのアクセス制御(RBAC)を有効にする

Auth0 DashboardまたはManagement使用して、APIにロールベースのアクセス制御(RBAC)を有効化することができます。これにより、APIの認可コア機能セットが有効になります。

RBACを有効にすると、アクセストークンに権限が含まれているかにかかわらず、要求された権限とユーザーに割り当てられた権限の共通部分がアクセストークンのscopeクレームに含まれます。RBACを無効にすると、アプリケーションがAPIに定義された任意の権限を要求できるようになり、scopeクレームには要求されたすべての権限が含まれます。

Dashboard

  1. [Dashboard]>[Applications (アプリケーション)]>[API]に移動し、表示するAPI名をクリックします。

    Dashboard - アプリケーション - APIリスト

  2. [RBAC Settings(RBACの設定)]までスクロールして、[Enable RBAC(RBACを有効にする)]トグルを有効にします。

    Auth0 Dashboard - APIの設定 - RBACトグル

  3. ユーザーに割り当てられたすべての権限をアクセストークンのpermissionsクレームに含めるには、[Add Permissions in the Access Token(アクセストークンに権限を追加する)]トグルを有効にして、[Save(保存)]をクリックします。アクセストークンに権限を含めると、最小限の呼び出しで権限を取得できますが、トークンのサイズは大きくなります。[Add Permissions in the Access Token(アクセストークンに権限を追加する)]トグルを有効にすると、Auth0はAPIに設定されたアクセストークンプロファイルを基に、トークンのダイアレクトも更新します。

    • トークンのダイアレクトがaccess_tokenの場合、Auth0はこれをaccess_token_authzに更新します。これは、permissionsクレームを含むaccess_tokenプロファイルと同等です。

    • トークンのダイアレクトがrfc9068_profileの場合、Auth0はこれをrfc9068_profile_authzに更新します。これは、permissionsクレームを含むrfc9068_profileと同等です。

    使用可能なトークンのダイアレクトについては、「トークンのダイアレクトオプション」をお読みください。

Mangement API

Management APIを使用してRBACを有効にするには、リソースサーバー更新エンドポイントにPATCH要求を行います。PATCH要求で、enforce_policiestrueに設定します。


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" }'

Was this helpful?

/
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);

Was this helpful?

/
package main

import (
	"fmt"
	"strings"
	"net/http"
	"io/ioutil"
)

func main() {

	url := "https://{yourDomain}/api/v2/resource-servers/API_ID"

	payload := strings.NewReader("{ \"enforce_policies\": \"true\", \"token_dialect\": \"TOKEN_DIALECT\" }")

	req, _ := http.NewRequest("PATCH", url, payload)

	req.Header.Add("content-type", "application/json")
	req.Header.Add("authorization", "Bearer MGMT_API_ACCESS_TOKEN")
	req.Header.Add("cache-control", "no-cache")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := ioutil.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))

}

Was this helpful?

/
HttpResponse<String> 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();

Was this helpful?

/
var axios = require("axios").default;

var options = {
  method: 'PATCH',
  url: 'https://{yourDomain}/api/v2/resource-servers/API_ID',
  headers: {
    'content-type': 'application/json',
    authorization: 'Bearer MGMT_API_ACCESS_TOKEN',
    'cache-control': 'no-cache'
  },
  data: {enforce_policies: 'true', token_dialect: 'TOKEN_DIALECT'}
};

axios.request(options).then(function (response) {
  console.log(response.data);
}).catch(function (error) {
  console.error(error);
});

Was this helpful?

/
#import <Foundation/Foundation.h>

NSDictionary *headers = @{ @"content-type": @"application/json",
                           @"authorization": @"Bearer MGMT_API_ACCESS_TOKEN",
                           @"cache-control": @"no-cache" };
NSDictionary *parameters = @{ @"enforce_policies": @"true",
                              @"token_dialect": @"TOKEN_DIALECT" };

NSData *postData = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:nil];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://{yourDomain}/api/v2/resource-servers/API_ID"]
                                                       cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                   timeoutInterval:10.0];
[request setHTTPMethod:@"PATCH"];
[request setAllHTTPHeaderFields:headers];
[request setHTTPBody:postData];

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];

Was this helpful?

/
$curl = curl_init();

curl_setopt_array($curl, [
  CURLOPT_URL => "https://{yourDomain}/api/v2/resource-servers/API_ID",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "PATCH",
  CURLOPT_POSTFIELDS => "{ \"enforce_policies\": \"true\", \"token_dialect\": \"TOKEN_DIALECT\" }",
  CURLOPT_HTTPHEADER => [
    "authorization: Bearer MGMT_API_ACCESS_TOKEN",
    "cache-control: no-cache",
    "content-type: application/json"
  ],
]);

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}

Was this helpful?

/
import http.client

conn = http.client.HTTPSConnection("")

payload = "{ \"enforce_policies\": \"true\", \"token_dialect\": \"TOKEN_DIALECT\" }"

headers = {
    'content-type': "application/json",
    'authorization': "Bearer MGMT_API_ACCESS_TOKEN",
    'cache-control': "no-cache"
    }

conn.request("PATCH", "/{yourDomain}/api/v2/resource-servers/API_ID", payload, headers)

res = conn.getresponse()
data = res.read()

print(data.decode("utf-8"))

Was this helpful?

/
require 'uri'
require 'net/http'
require 'openssl'

url = URI("https://{yourDomain}/api/v2/resource-servers/API_ID")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE

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\" }"

response = http.request(request)
puts response.read_body

Was this helpful?

/
import Foundation

let headers = [
  "content-type": "application/json",
  "authorization": "Bearer MGMT_API_ACCESS_TOKEN",
  "cache-control": "no-cache"
]
let parameters = [
  "enforce_policies": "true",
  "token_dialect": "TOKEN_DIALECT"
] as [String : Any]

let postData = JSONSerialization.data(withJSONObject: parameters, options: [])

let request = NSMutableURLRequest(url: NSURL(string: "https://{yourDomain}/api/v2/resource-servers/API_ID")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "PATCH"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data

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()

Was this helpful?

/

以下の表が示すように、API_IDMGMT_API_ACCESS_TOKENTOKEN_DIALECTをそれぞれの値に置き換えます。

パラメーター 説明
API_ID RBACを有効にしたいAPIのID。
MGMT_API_ACCESS_TOKEN スコープupdate:resource_serversを持つManagement APIのアクセストークン
TOKEN_DIALECT 指定されたAPIのアクセストークンのダイアレクト。詳しくは、「トークンのダイアレクトオプション」をご覧ください。

トークンのダイアレクトオプション

Auth0は以下のトークンダイアレクトに対応しています。

説明
access_token デフォルトのAuth0トークンプロファイルはJSON Web Token(JWT)形式のアクセストークンを生成します。アクセストークンのscopeクレームには、要求された権限とユーザーに割り当てられた権限の共通部分が含まれます。permissionsクレームは渡されません。詳細については、「アクセストークンのプロファイル」をお読みください。
access_token_authz permissionsクレームのあるデフォルトのAuth0トークンプロファイル(access_token)です。アクセストークンのscopeクレームには、要求された権限とユーザーに割り当てられた権限の共通部分が含まれます。アクセストークンのpermissionsクレームには、ユーザーに割り当てられたすべての許可が含まれます。アクセストークンに許可を含めると、最小限の呼び出しで許可を取得できますが、トークンサイズは大きくなります。
rfc9068_profile IETF JWT Profile for OAuth 2.0 Access Tokens(RFC 9068)に準拠したJWT形式のアクセストークンを生成します。アクセストークンのscopeクレームには、要求された権限とユーザーに割り当てられた権限の共通部分が含まれます。permissionsクレームは渡されません。詳細については、「アクセストークンのプロファイル」をお読みください。
rfc9068_profile_authz permissionsのあるRFC 9068トークンプロファイル(rfc9068_profile)。アクセストークンのscopeクレームには、要求された権限とユーザーに割り当てられた権限の共通部分が含まれます。アクセストークンのpermissionsクレームには、ユーザーに割り当てられたすべての許可が含まれます。アクセストークンに許可を含めると、最小限の呼び出しで許可を取得できますが、トークンサイズは大きくなります。

もっと詳しく