【问题标题】:Create Client programmatically in Keycloak在 Keycloak 中以编程方式创建客户端
【发布时间】:2018-09-08 04:07:44
【问题描述】:

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

【问题讨论】:

    标签: java keycloak keycloak-services


    【解决方案1】:

    一种方法是通过 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

    【讨论】:

    【解决方案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 对象。

    【讨论】:

      【解决方案3】:

      使用卷曲

      #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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-12-11
        • 2017-08-30
        • 2019-01-02
        • 1970-01-01
        • 2017-03-30
        • 2011-02-15
        • 1970-01-01
        相关资源
        最近更新 更多