2017-04-05 90 views
2

我想以編程方式創建keycloak客戶端角色並將其分配給動態創建的用戶。下面是我創建的用戶如何以編程方式創建keycloak客戶端角色並將其分配給用戶

UserRepresentation user = new UserRepresentation(); 
user.setEmail("[email protected]"); 
user.setUsername("xxxx"); 
user.setFirstName("xxx"); 
user.setLastName("m"); 
user.setEnabled(true); 
Response response = kc.realm("YYYYY").users().create(user); 
+0

什麼是真正的問題嗎? –

回答

3

下面的代碼到你的要求的解決方案(不是很漂亮,但它的工作原理):

// Get keycloak client 
Keycloak kc = Keycloak.getInstance("http://localhost:8080/auth", 
       "master", "admin", "admin", "admin-cli"); 

// Create the role 
RoleRepresentation clientRoleRepresentation = new RoleRepresentation(); 
clientRoleRepresentation.setName("client_role"); 
clientRoleRepresentation.setClientRole(true); 
kc.realm("RealmID").clients().findByClientId("ClientID").forEach(clientRepresentation -> 
    kc.realm("RealmID").clients().get(clientRepresentation.getId()).roles().create(clientRoleRepresentation) 
); 

// Create the user 
UserRepresentation user = new UserRepresentation(); 
user.setUsername("test"); 
user.setEnabled(true); 
Response response = kc.realm("RealmID").users().create(user); 
String userId = getCreatedId(response); 

// Assign role to the user 
kc.realm("RealmID").clients().findByClientId("ClientID").forEach(clientRepresentation -> { 
    RoleRepresentation savedRoleRepresentation = kc.realm("RealmID").clients() 
      .get(clientRepresentation.getId()).roles().get("client_role").toRepresentation(); 
    kc.realm("RealmID").users().get(userId).roles().clientLevel(clientRepresentation.getId()) 
      .add(asList(savedRoleRepresentation)); 
}); 

// Update credentials to make sure, that the user can log in 
UserResource userResource = kc.realm("RealmID").users().get(userId); 
userResource.resetPassword(credential); 

隨着help方法:

private String getCreatedId(Response response) { 
    URI location = response.getLocation(); 
    if (!response.getStatusInfo().equals(Response.Status.CREATED)) { 
     Response.StatusType statusInfo = response.getStatusInfo(); 
     throw new WebApplicationException("Create method returned status " + 
       statusInfo.getReasonPhrase() + " (Code: " + statusInfo.getStatusCode() + "); expected status: Created (201)", response); 
    } 
    if (location == null) { 
     return null; 
    } 
    String path = location.getPath(); 
    return path.substring(path.lastIndexOf('/') + 1); 
} 
+0

它實際上工作。但在我的2個角度的應用程序,受限制的客戶端角色可以登錄。 – boycod3

+0

我想這是因爲你沒有在角度的應用程序中正確配置這個客戶端角色。查看[此鏈接](https://keycloak.gitbooks.io/documentation/securing_apps/topics/oidc/javascript-adapter.html)瞭解更多信息。 –

+0

我已經正確配置檢查這個問題http://stackoverflow.com/questions/43226287/keycloak-per-app-role-mapping – boycod3

相關問題