2017-04-05 11 views
2

プログラムでキークローキングクライアントロールを作成し、動的に作成したユーザーに割り当てる必要があります。以下は、ユーザーここプログラムでキークローキングクライアントロールを作成してユーザーに割り当てる方法

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); 

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

関連する問題