简体   繁体   English

如何通过 REST 将客户端授权设置导入 Keycloak REALM?

[英]How to import client authorization settings into Keycloak REALM through REST?

I am trying to import a client and its authorization settings into my current Realm "TestRealm" using the REST API of the Keycloak version 15 via my Python script.我正在尝试通过我的 Python 脚本使用 Keycloak 版本 15 的 REST API 将客户端及其授权设置导入我当前的领域“TestRealm”。 My client representation is a JSON dump of another Keycloak REALM of mine, so I know that the values and structure is correct.我的客户端表示是我的另一个 Keycloak REALM 的 JSON 转储,所以我知道值和结构是正确的。
Here is a snippet of my code, how I try to import the client and its authorization settings:这是我的代码片段,我如何尝试导入客户端及其授权设置:

class KeycloakClient:
  def __init__(self, base_url, admin_username, admin_password, verify=True):
    self.keycloak_base = base_url
    self.admin_username = admin_username
    self.admin_password = admin_password
    self.current_access_token = None
    self.verify = verify

  @property
  def token(self):
    if not self.current_access_token or self.is_token_expired():
      # implemented elsewhere
      self.refresh_access_token()
    return self.current_access_token

  def post(self, path, data):
    headers = {
      'Authorization': 'Bearer ' + self.token,
      'content-type': 'application/json;charset=UTF-8'
    }
    return requests.post(f"{self.keycloak_base}/{path}", data=data, headers=headers, verify=self.verify)

  def create_client(self, realmName, clientData):
    return self.post(f"admin/realms/{realmName}/clients", data=clientData)
    
keycloak_client = KeycloakClient("127.0.0.1:8080", "admin", "pass!")

client_file = open("single_client.json", "r")
new_client = client_file.read()

keycloak_client.create_client("TestRealm", new_client)

The client representation inside "single_client.json" looks like this: “single_client.json”中的客户端表示如下所示:

{
"id" : "586fcea1-9049-47a0-af14-9e09d660a728",
"clientId" : "Test-Client",
"name" : "Test-Client-New",
"surrogateAuthRequired" : false,
"enabled" : true,
"alwaysDisplayInConsole" : false,
"clientAuthenticatorType" : "client-secret",
"secret" : "5123feeb-8754-49bf-b98a-2d5411bb53b",
"authorizationSettings" : {
  "allowRemoteResourceManagement" : true,
  "policyEnforcementMode" : "ENFORCING",
  "resources" : [ {
    "name" : "Dialog.Systeminformation.OS",
    "ownerManagedAccess" : false,
    "displayName" : "System Information OS",
    "attributes" : {
      "Description" : [ "View all OS" ]
    },
    "_id" : "0afa876b-7f22-4ecd-8393-4101dc6dc89e",
    "uris" : [ ],
    "scopes" : [ {
      "name" : "visible"
    } ]
  }, {
    "name" : "View.Data.ViewerClasses",
    "ownerManagedAccess" : false,
    "displayName" : "Data ViewerClasses",
    "attributes" : {
      "Description" : [ "View/edit viwer class data" ]
    },
    "_id" : "0d08ea97-4a61-4b9f-9b97-3bc1c87fe5e4",
    "uris" : [ ],
    "scopes" : [ {
      "name" : "visible"
    }, {
      "name" : "editable"
    } ]
  } ]
}

After executing this script I can see the fully imported client inside the Keycloak UI, with the exception of the authorization settings.执行此脚本后,我可以在 Keycloak UI 中看到完全导入的客户端,但授权设置除外。

NOTE: The same problem occurs when I try to update an existing clint using the PUT endpoint for clients.注意:当我尝试使用客户端的 PUT 端点更新现有 clint 时,会出现同样的问题。 I have tried this with different clients but always end up without the authorization settings being imported or updated.我已经用不同的客户端尝试过这个,但总是没有导入或更新授权设置。

Am I using the API in a wrong way or is this behavior intended?我是否以错误的方式使用 API,或者这种行为是有意的? What other ways exist to import client authorization settings separately from the REALM.还有哪些其他方法可以将客户端授权设置与 REALM 分开导入。 IF there maybe is a better way to update my realm or if I missed out on an endpoint I would be happy for recommendations.如果可能有更好的方法来更新我的领域,或者如果我错过了某个端点,我会很高兴获得建议。

NOTE 2: The overall goal of the intended import is to update a REALM, but keep user/group/parts of the authorization settings.注意 2:预期导入的总体目标是更新 REALM,但保留用户/组/部分授权设置。

You missed one item in yours client.json file.您错过了 client.json 文件中的一项。

you needs to add "serviceAccountsEnabled": true,您需要添加“serviceAccountsEnabled”:true,

This JSON works at Keycloak v18.0.0此 JSON 适用于 Keycloak v18.0.0

{
    "id": "586fcea1-9049-47a0-af14-9e09d660a728",
    "clientId": "Test-Client",
    "name": "Test-Client-New",
    "surrogateAuthRequired": false,
    "enabled": true,
    "alwaysDisplayInConsole": false,
    "clientAuthenticatorType": "client-secret",
    "secret": "5123feeb-8754-49bf-b98a-2d5411bb53b",
    "redirectUris": [],
    "webOrigins": [],
    "notBefore": 0,
    "bearerOnly": false,
    "consentRequired": false,
    "standardFlowEnabled": true,
    "implicitFlowEnabled": false,
    "directAccessGrantsEnabled": false,
    "serviceAccountsEnabled": true,
    "publicClient": false,
    "frontchannelLogout": false,
    "protocol": "openid-connect",
    "attributes": {},
    "authenticationFlowBindingOverrides": {},
    "fullScopeAllowed": true,
    "nodeReRegistrationTimeout": -1,
    "authorizationSettings": {
        "allowRemoteResourceManagement": true,
        "policyEnforcementMode": "ENFORCING",
        "resources": [
            {
                "name": "Dialog.Systeminformation.OS",
                "ownerManagedAccess": false,
                "displayName": "System Information OS",
                "attributes": {},
                "uris": [],
                "scopes": [
                    {
                        "name": "visible"
                    }
                ]
            },
            {
                "name": "View.Data.ViewerClasses",
                "ownerManagedAccess": false,
                "displayName": "Data ViewerClasses",
                "attributes": {},
                "uris": [],
                "scopes": [
                    {
                        "name": "visible"
                    },
                    {
                        "name": "editable"
                    }
                ]
            }
        ],
        "scopes": [
            {
                "name": "visible"
            },
            {
                "name": "editable"
            }
        ],
        "decisionStrategy": "UNANIMOUS"
    }
}

This posted screen capture in Postmen after add client POST call.添加客户端 POST 调用后,此在 Postmen 中发布了屏幕截图。 在此处输入图像描述

This is Added Client screen in Keycloak after call API.这是调用 API 后在 Keycloak 中添加的客户端屏幕。 Keycloak returned 201 Created status without error. Keycloak 返回 201 Created 状态,没有错误。 You can see added new resources with scopes in client's Authorization tab.您可以在客户端的“授权”选项卡中看到添加的具有范围的新资源。 在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM