简体   繁体   English

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

[英]Create Client programmatically in Keycloak

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

One way to do it is via the api :一种方法是通过 api :

  • Get token for an account with the rights to add client to the realm获取有权将客户端添加到领域的帐户的令牌

     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>
  • Add a new client (the request body comes from an export of an existing client)添加新客户端(请求正文来自现有客户端的导出)

     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", "[...]" }

The response status should be a 201 with an header location to the new client.响应状态应该是201 ,带有新客户端的标头位置。

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

I did it like this,我是这样做的,

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(); KeycloakInstance.getInstance(); returns Keycloak Object.返回 Keycloak 对象。

Using curl使用卷曲

#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

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

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