在Keycloak中以编程方式创建客户端

时间:2018-03-29 09:06:35

标签: java keycloak keycloak-services

我想使用java应用程序在keycloak中以编程方式创建客户端。 有没有办法做到这一点?请回复。提前致谢

3 个答案:

答案 0 :(得分:2)

一种方法是通过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,其中包含新客户端的标头位置。

可以在此处找到文档:http://www.keycloak.org/docs-api/3.4/rest-api/index.html#_clients_resource

答案 1 :(得分:0)

我是这样做的,

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对象。

答案 2 :(得分:0)

使用卷曲

#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