6

如何使用 java 应用程序在 keycloak 中以编程方式创建客户端?

4

3 回答 3

6

一种方法是通过 api :

  • 获取有权将客户端添加到领域的帐户的令牌

      POST https://<keycloak-url>/auth/realms/master/protocol/openid-connect/token
      Host: <keycloak-url>
      Content-Type: application/x-www-form-urlencoded
      Cache-Control: no-cache
    
      client_id=admin-cli&grant_type=password&username=<user>&password=<password>
    
  • 添加新客户端(请求正文来自现有客户端的导出)

      POST https://keycloak-url/auth/admin/realms/<realm-name>/clients
      Host: <keycloak-url>
      Content-Type: application/json
      Cache-Control: no-cache
      Authorization: Bearer <token>
    
      {
           "clientId": "test-add",
           "[...]"
       }
    

响应状态应该是201带有新客户端的标头位置。

文档可以在这里找到:https ://www.keycloak.org/docs-api/14.0/rest-api/index.html#_clients_resource

于 2018-03-29T11:12:58.333 回答
2

我是这样做的,

public boolean createClient(String clientId, String realmName) throws IOException {
    try {
        Keycloak keycloakInstanceDefault = KeycloakInstance.getInstance();
        RealmResource createdRealmResource = keycloakInstanceDefault.realms().realm(realmName);
        ClientRepresentation clientRepresentation = new ClientRepresentation();
        clientRepresentation.setClientId(clientId);
        clientRepresentation.setProtocol("openid-connect");
        clientRepresentation.setSecret(clientId);
        createdRealmResource.clients().create(clientRepresentation);

    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }

    return true;
}

KeycloakInstance.getInstance(); 返回 Keycloak 对象。

于 2018-04-12T07:38:36.050 回答
1

使用卷曲

#get token
RESULT=`curl --data "username=<your_admin_user>&password=<your_passwod>&grant_type=password&client_id=admin-cli" http://localhost:8090/auth/realms/master/protocol/openid-connect/token
TOKEN=`echo $RESULT | sed 's/.*access_token":"//g' | sed 's/".*//g'`
#create user
curl -X POST -d '{ "clientId": "myclient" }' -H "Content-Type:application/json" -H "Authorization: bearer ${TOKEN}" http://localhost:8090/auth/realms/master/clients-registrations/default
于 2019-11-21T06:11:17.097 回答