![](/img/trans.png)
[英]Create keycloak client and assign role from other client programmatically
[英]Create Client programmatically in Keycloak
如何使用 java 應用程序在 keycloak 中以編程方式創建客戶端?
一種方法是通過 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
我是這樣做的,
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 對象。
#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.