org.keycloak.representations.idm.RoleRepresentation Java Examples
The following examples show how to use
org.keycloak.representations.idm.RoleRepresentation.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: KeycloakDevModeRealmResourceManager.java From quarkus with Apache License 2.0 | 8 votes |
private static RealmRepresentation createRealm(String name) { RealmRepresentation realm = new RealmRepresentation(); realm.setRealm(name); realm.setEnabled(true); realm.setUsers(new ArrayList<>()); realm.setClients(new ArrayList<>()); realm.setSsoSessionMaxLifespan(2); // sec realm.setAccessTokenLifespan(3); // 3 seconds RolesRepresentation roles = new RolesRepresentation(); List<RoleRepresentation> realmRoles = new ArrayList<>(); roles.setRealm(realmRoles); realm.setRoles(roles); realm.getRoles().getRealm().add(new RoleRepresentation("user", null, false)); return realm; }
Example #2
Source File: ImportRolesIT.java From keycloak-config-cli with Apache License 2.0 | 6 votes |
@Test @Order(24) void shouldRemoveRealmCompositeFromClientRole() { doImport("24_update_realm__remove_realm_role_composite_from_client_role.json"); RealmRepresentation createdRealm = keycloakProvider.get().realm(REALM_NAME).toRepresentation(); assertThat(createdRealm.getRealm(), is(REALM_NAME)); assertThat(createdRealm.isEnabled(), is(true)); RoleRepresentation realmRole = keycloakRepository.getClientRole( REALM_NAME, "moped-client", "my_composite_moped_client_role" ); assertThat(realmRole.getName(), is("my_composite_moped_client_role")); assertThat(realmRole.isComposite(), is(true)); assertThat(realmRole.getClientRole(), is(true)); assertThat(realmRole.getDescription(), is("My composite moped-client role")); RoleRepresentation.Composites composites = realmRole.getComposites(); assertThat(composites, notNullValue()); assertThat(composites.getRealm(), contains("my_other_realm_role")); assertThat(composites.getClient(), is(nullValue())); }
Example #3
Source File: SAMLClientRegistrationTest.java From keycloak with Apache License 2.0 | 6 votes |
@Test public void testSAMLEndpointCreateWithOIDCClient() throws Exception { ClientsResource clientsResource = adminClient.realm(TEST).clients(); ClientRepresentation oidcClient = clientsResource.findByClientId("oidc-client").get(0); String oidcClientServiceId = clientsResource.get(oidcClient.getId()).getServiceAccountUser().getId(); String realmManagementId = clientsResource.findByClientId("realm-management").get(0).getId(); RoleRepresentation role = clientsResource.get(realmManagementId).roles().get("create-client").toRepresentation(); adminClient.realm(TEST).users().get(oidcClientServiceId).roles().clientLevel(realmManagementId).add(Arrays.asList(role)); String accessToken = oauth.clientId("oidc-client").doClientCredentialsGrantAccessTokenRequest("secret").getAccessToken(); reg.auth(Auth.token(accessToken)); String entityDescriptor = IOUtils.toString(getClass().getResourceAsStream("/clientreg-test/saml-entity-descriptor.xml")); assertCreateFail(entityDescriptor, 400, Errors.INVALID_CLIENT); }
Example #4
Source File: ClientRoleMappingsResource.java From keycloak with Apache License 2.0 | 6 votes |
/** * Get effective client-level role mappings * * This recurses any composite roles * * @return */ @Path("composite") @GET @Produces(MediaType.APPLICATION_JSON) @NoCache public List<RoleRepresentation> getCompositeClientRoleMappings() { viewPermission.require(); Set<RoleModel> roles = client.getRoles(); List<RoleRepresentation> mapRep = new ArrayList<RoleRepresentation>(); for (RoleModel roleModel : roles) { if (user.hasRole(roleModel)) mapRep.add(ModelToRepresentation.toBriefRepresentation(roleModel)); } return mapRep; }
Example #5
Source File: RoleByIdResource.java From keycloak with Apache License 2.0 | 6 votes |
/** * Get client-level roles for the client that are in the role's composite * * @param id * @param client * @return */ @Path("{role-id}/composites/clients/{client}") @GET @NoCache @Produces(MediaType.APPLICATION_JSON) public Set<RoleRepresentation> getClientRoleComposites(final @PathParam("role-id") String id, final @PathParam("client") String client) { RoleModel role = getRoleModel(id); auth.roles().requireView(role); ClientModel clientModel = realm.getClientById(client); if (clientModel == null) { throw new NotFoundException("Could not find client"); } return getClientRoleComposites(clientModel, role); }
Example #6
Source File: OfflineTokenTest.java From keycloak with Apache License 2.0 | 6 votes |
@Test public void offlineTokenAllowedWithCompositeRole() throws Exception { RealmResource appRealm = adminClient.realm("test"); UserResource testUser = findUserByUsernameId(appRealm, "test-user@localhost"); RoleRepresentation offlineAccess = findRealmRoleByName(adminClient.realm("test"), Constants.OFFLINE_ACCESS_ROLE).toRepresentation(); // Grant offline_access role indirectly through composite role appRealm.roles().create(RoleBuilder.create().name("composite").build()); RoleResource roleResource = appRealm.roles().get("composite"); roleResource.addComposites(Collections.singletonList(offlineAccess)); testUser.roles().realmLevel().remove(Collections.singletonList(offlineAccess)); testUser.roles().realmLevel().add(Collections.singletonList(roleResource.toRepresentation())); // Integration test offlineTokenDirectGrantFlow(); // Revert changes testUser.roles().realmLevel().remove(Collections.singletonList(appRealm.roles().get("composite").toRepresentation())); appRealm.roles().get("composite").remove(); testUser.roles().realmLevel().add(Collections.singletonList(offlineAccess)); }
Example #7
Source File: ImpersonationTest.java From keycloak with Apache License 2.0 | 6 votes |
@Test public void testImpersonateByMasterImpersonator() { String userId; try (Response response = adminClient.realm("master").users().create(UserBuilder.create().username("master-impersonator").build())) { userId = ApiUtil.getCreatedId(response); } UserResource user = adminClient.realm("master").users().get(userId); user.resetPassword(CredentialBuilder.create().password("password").build()); ClientResource testRealmClient = ApiUtil.findClientResourceByClientId(adminClient.realm("master"), "test-realm"); List<RoleRepresentation> roles = new LinkedList<>(); roles.add(ApiUtil.findClientRoleByName(testRealmClient, AdminRoles.VIEW_USERS).toRepresentation()); roles.add(ApiUtil.findClientRoleByName(testRealmClient, ImpersonationConstants.IMPERSONATION_ROLE).toRepresentation()); user.roles().clientLevel(testRealmClient.toRepresentation().getId()).add(roles); testSuccessfulImpersonation("master-impersonator", Config.getAdminRealm()); adminClient.realm("master").users().get(userId).remove(); }
Example #8
Source File: ClientRolesTest.java From keycloak with Apache License 2.0 | 6 votes |
@Test public void getRolesWithFullRepresentation() { for(int i = 0; i<5; i++) { String roleName = "attributesrole"+i; RoleRepresentation role = makeRole(roleName); Map<String, List<String>> attributes = new HashMap<String, List<String>>(); attributes.put("attribute1", Arrays.asList("value1","value2")); role.setAttributes(attributes); rolesRsc.create(role); assertAdminEvents.assertEvent(getRealmId(), OperationType.CREATE, AdminEventPaths.clientRoleResourcePath(clientDbId,roleName), role, ResourceType.CLIENT_ROLE); // we have to update the role to set the attributes because // the add role endpoint only care about name and description RoleResource roleToUpdate = rolesRsc.get(roleName); role.setId(roleToUpdate.toRepresentation().getId()); roleToUpdate.update(role); assertAdminEvents.assertEvent(getRealmId(), OperationType.UPDATE, AdminEventPaths.clientRoleResourcePath(clientDbId,roleName), role, ResourceType.CLIENT_ROLE); } List<RoleRepresentation> roles = rolesRsc.list(false); assertTrue(roles.get(0).getAttributes().containsKey("attribute1")); }
Example #9
Source File: RoleRepository.java From keycloak-config-cli with Apache License 2.0 | 6 votes |
public List<RoleRepresentation> searchRealmRoles(String realmName, List<String> roleNames) { List<RoleRepresentation> roles = new ArrayList<>(); RealmResource realm = realmRepository.loadRealm(realmName); for (String roleName : roleNames) { try { RoleRepresentation role = realm.roles().get(roleName).toRepresentation(); roles.add(role); } catch (NotFoundException e) { throw new ImportProcessingException("Could not find role '" + roleName + "' in realm '" + realmName + "'!"); } } return roles; }
Example #10
Source File: PermissionsTest.java From keycloak with Apache License 2.0 | 6 votes |
private void createTestUsers() { RealmResource master = adminClient.realm("master"); Response response = master.users().create(UserBuilder.create().username("permissions-test-master-none").build()); String userId = ApiUtil.getCreatedId(response); response.close(); master.users().get(userId).resetPassword(CredentialBuilder.create().password("password").build()); for (String role : AdminRoles.ALL_REALM_ROLES) { response = master.users().create(UserBuilder.create().username("permissions-test-master-" + role).build()); userId = ApiUtil.getCreatedId(response); response.close(); master.users().get(userId).resetPassword(CredentialBuilder.create().password("password").build()); String clientId = master.clients().findByClientId(REALM_NAME + "-realm").get(0).getId(); RoleRepresentation roleRep = master.clients().get(clientId).roles().get(role).toRepresentation(); master.users().get(userId).roles().clientLevel(clientId).add(Collections.singletonList(roleRep)); } }
Example #11
Source File: RealmRolesPartialImport.java From keycloak with Apache License 2.0 | 5 votes |
@Override public String getModelId(RealmModel realm, KeycloakSession session, RoleRepresentation roleRep) { for (RoleModel role : realm.getRoles()) { if (getName(roleRep).equals(role.getName())) return role.getId(); } return null; }
Example #12
Source File: RoleImportService.java From keycloak-config-cli with Apache License 2.0 | 5 votes |
private void createOrUpdateClientRoles(String realm, RolesRepresentation roles) { Map<String, List<RoleRepresentation>> clientRolesPerClient = roles.getClient(); if (clientRolesPerClient == null) return; for (Map.Entry<String, List<RoleRepresentation>> clientRoles : clientRolesPerClient.entrySet()) { createOrUpdateClientRoles(realm, clientRoles); } }
Example #13
Source File: RolesPartialImport.java From keycloak with Apache License 2.0 | 5 votes |
private void setUniqueIds(Map<String, List<RoleRepresentation>> clientRoles) { for (String clientId : clientRoles.keySet()) { for (RoleRepresentation clientRole : clientRoles.get(clientId)) { clientRole.setId(KeycloakModelUtils.generateId()); } } }
Example #14
Source File: ImportRolesIT.java From keycloak-config-cli with Apache License 2.0 | 5 votes |
@Test @Order(26) void shouldRemoveClientCompositesFromClientRole() { doImport("26_update_realm__remove_client_role_composites_from_client_role.json"); RealmRepresentation createdRealm = keycloakProvider.get().realm(REALM_NAME).toRepresentation(); assertThat(createdRealm.getRealm(), is(REALM_NAME)); assertThat(createdRealm.isEnabled(), is(true)); RoleRepresentation realmRole = keycloakRepository.getClientRole( REALM_NAME, "moped-client", "my_other_composite_moped_client_role" ); assertThat(realmRole.getName(), is("my_other_composite_moped_client_role")); assertThat(realmRole.isComposite(), is(true)); assertThat(realmRole.getClientRole(), is(true)); assertThat(realmRole.getDescription(), is("My other composite moped-client role")); RoleRepresentation.Composites composites = realmRole.getComposites(); assertThat(composites, notNullValue()); assertThat(composites.getRealm(), is(nullValue())); assertThat(composites.getClient(), aMapWithSize(1)); assertThat(composites.getClient(), hasEntry(is("second-moped-client"), containsInAnyOrder("my_other_second_client_role"))); }
Example #15
Source File: RealmRolesTest.java From keycloak with Apache License 2.0 | 5 votes |
public void addRole(RoleRepresentation roleRep) { assertCurrentUrlEquals(realmRolesPage); realmRolesPage.table().addRole(); assertCurrentUrlEquals(createRolePage); createRolePage.form().setBasicAttributes(roleRep); createRolePage.form().save(); assertAlertSuccess(); createRolePage.form().setCompositeRoles(roleRep); // TODO add verification of notification message when KEYCLOAK-1497 gets resolved }
Example #16
Source File: KeycloakRepository.java From keycloak-config-cli with Apache License 2.0 | 5 votes |
public boolean isClientRoleExisting(String realm, String clientId, String role) { ClientRepresentation client = getClient(realm, clientId); List<RoleRepresentation> clientRoles = keycloakProvider.get() .realm(realm) .clients().get(client.getId()) .roles() .list(); long count = clientRoles.stream() .filter(r -> Objects.equals(r.getName(), role)) .count(); return count > 0; }
Example #17
Source File: RolesBuilder.java From keycloak with Apache License 2.0 | 5 votes |
public RolesBuilder clientRole(String client, RoleRepresentation role) { if (rep.getClient() == null) { rep.setClient(new HashMap<String, List<RoleRepresentation>>()); } List<RoleRepresentation> clientList = rep.getClient().get(client); if (clientList == null) { rep.getClient().put(client, new LinkedList<RoleRepresentation>()); } rep.getClient().get(client).add(role); return this; }
Example #18
Source File: ApiUtil.java From keycloak with Apache License 2.0 | 5 votes |
public static void assignClientRoles(RealmResource realm, String userId, String clientName, String... roles) { String realmName = realm.toRepresentation().getRealm(); String clientId = ""; for (ClientRepresentation clientRepresentation : realm.clients().findAll()) { if (clientRepresentation.getClientId().equals(clientName)) { clientId = clientRepresentation.getId(); } } if (!clientId.isEmpty()) { ClientResource clientResource = realm.clients().get(clientId); List<RoleRepresentation> roleRepresentations = new ArrayList<>(); for (String roleName : roles) { RoleRepresentation role = clientResource.roles().get(roleName).toRepresentation(); roleRepresentations.add(role); } UserResource userResource = realm.users().get(userId); log.info("assigning role: " + Arrays.toString(roles) + " to user: \"" + userResource.toRepresentation().getUsername() + "\" of client: \"" + clientName + "\" in realm: \"" + realmName + "\""); userResource.roles().clientLevel(clientId).add(roleRepresentations); } else { log.warn("client with name " + clientName + " doesn't exist in realm " + realmName); } }
Example #19
Source File: UserStorageConsentTest.java From keycloak with Apache License 2.0 | 5 votes |
/** * KEYCLOAK-5273 * * @throws Exception */ @Test public void testLogin() throws Exception { testingClient.server().run(UserStorageConsentTest::setupConsent); UserRepresentation memuser = new UserRepresentation(); memuser.setUsername("memuser"); String uid = ApiUtil.createUserAndResetPasswordWithAdminClient(testRealmResource(), memuser, "password"); System.out.println("uid: " + uid); Assert.assertTrue(uid.startsWith("f:")); // make sure its federated RoleRepresentation roleRep = adminClient.realm("demo").roles().get("user").toRepresentation(); List<RoleRepresentation> roleList = new ArrayList<>(); roleList.add(roleRep); adminClient.realm("demo").users().get(uid).roles().realmLevel().add(roleList); productPortal.navigateTo(); assertCurrentUrlStartsWithLoginUrlOf(testRealmPage); testRealmLoginPage.form().login("memuser", "password"); Assert.assertTrue(consentPage.isCurrent()); consentPage.confirm(); assertCurrentUrlEquals(productPortal.toString()); Assert.assertTrue(driver.getPageSource().contains("iPhone")); String logoutUri = OIDCLoginProtocolService.logoutUrl(authServerPage.createUriBuilder()) .queryParam(OAuth2Constants.REDIRECT_URI, productPortal.toString()) .build("demo").toString(); driver.navigate().to(logoutUri); assertCurrentUrlStartsWithLoginUrlOf(testRealmPage); productPortal.navigateTo(); assertCurrentUrlStartsWithLoginUrlOf(testRealmPage); testRealmLoginPage.form().login("memuser", "password"); assertCurrentUrlEquals(productPortal.toString()); Assert.assertTrue(driver.getPageSource().contains("iPhone")); adminClient.realm("demo").users().delete(uid).close(); }
Example #20
Source File: ClientRolesPartialImport.java From keycloak with Apache License 2.0 | 5 votes |
public void prepare(PartialImportRepresentation partialImportRep, RealmModel realm, KeycloakSession session) throws ErrorResponseException { Map<String, List<RoleRepresentation>> repList = getRepList(partialImportRep); if (repList == null || repList.isEmpty()) return; for (String clientId : repList.keySet()) { if (!clientExists(partialImportRep, realm, clientId)) { throw noClientFound(clientId); } toOverwrite.put(clientId, new HashSet<>()); toSkip.put(clientId, new HashSet<>()); for (RoleRepresentation roleRep : repList.get(clientId)) { if (exists(realm, session, clientId, roleRep)) { switch (partialImportRep.getPolicy()) { case SKIP: toSkip.get(clientId).add(roleRep); break; case OVERWRITE: toOverwrite.get(clientId).add(roleRep); break; default: throw exists(existsMessage(clientId, roleRep)); } } } } }
Example #21
Source File: RoleContainerResource.java From keycloak with Apache License 2.0 | 5 votes |
/** * Create a new role for the realm or client * * @param rep * @return */ @POST @Consumes(MediaType.APPLICATION_JSON) public Response createRole(final RoleRepresentation rep) { auth.roles().requireManage(roleContainer); if (rep.getName() == null) { throw new BadRequestException(); } try { RoleModel role = roleContainer.addRole(rep.getName()); role.setDescription(rep.getDescription()); rep.setId(role.getId()); if (role.isClientRole()) { adminEvent.resource(ResourceType.CLIENT_ROLE); } else { adminEvent.resource(ResourceType.REALM_ROLE); } adminEvent.operation(OperationType.CREATE).resourcePath(uriInfo, role.getName()).representation(rep).success(); return Response.created(uriInfo.getAbsolutePathBuilder().path(role.getName()).build()).build(); } catch (ModelDuplicateException e) { return ErrorResponse.exists("Role with name " + rep.getName() + " already exists"); } }
Example #22
Source File: RoleCompositeRepository.java From keycloak-config-cli with Apache License 2.0 | 5 votes |
private MultivaluedHashMap<String, RoleRepresentation> findClientComposites(String realm, Supplier<RoleResource> roleSupplier) { MultivaluedHashMap<String, RoleRepresentation> clientComposites = new MultivaluedHashMap<>(); List<ClientRepresentation> clients = clientRepository.getClients(realm); for (ClientRepresentation client : clients) { Set<RoleRepresentation> clientRoleComposites = findClientComposites(realm, client.getClientId(), roleSupplier); clientComposites.addAll(client.getClientId(), new ArrayList<>(clientRoleComposites)); } return clientComposites; }
Example #23
Source File: RoleResource.java From keycloak with Apache License 2.0 | 5 votes |
protected Set<RoleRepresentation> getRealmRoleComposites(RoleModel role) { if (!role.isComposite() || role.getComposites().size() == 0) return Collections.emptySet(); Set<RoleRepresentation> composites = new HashSet<RoleRepresentation>(role.getComposites().size()); for (RoleModel composite : role.getComposites()) { if (composite.getContainer() instanceof RealmModel) composites.add(ModelToRepresentation.toBriefRepresentation(composite)); } return composites; }
Example #24
Source File: RoleRepository.java From keycloak-config-cli with Apache License 2.0 | 5 votes |
public void removeClientRolesForUser(String realm, String username, String clientId, List<RoleRepresentation> clientRoles) { ClientRepresentation client = clientRepository.getClientByClientId(realm, clientId); UserResource userResource = userRepository.getUserResource(realm, username); RoleScopeResource userClientRoles = userResource.roles() .clientLevel(client.getId()); userClientRoles.remove(clientRoles); }
Example #25
Source File: ImportRolesIT.java From keycloak-config-cli with Apache License 2.0 | 5 votes |
@Test @Order(17) void shouldAddClientRoleWithClientRoleComposite() { doImport("17_update_realm__add_client_role_with_client_role_composite.json"); RealmRepresentation createdRealm = keycloakProvider.get().realm(REALM_NAME).toRepresentation(); assertThat(createdRealm.getRealm(), is(REALM_NAME)); assertThat(createdRealm.isEnabled(), is(true)); RoleRepresentation realmRole = keycloakRepository.getClientRole( REALM_NAME, "moped-client", "my_other_composite_moped_client_role" ); assertThat(realmRole.getName(), is("my_other_composite_moped_client_role")); assertThat(realmRole.isComposite(), is(true)); assertThat(realmRole.getClientRole(), is(true)); assertThat(realmRole.getDescription(), is("My other composite moped-client role")); RoleRepresentation.Composites composites = realmRole.getComposites(); assertThat(composites, notNullValue()); assertThat(composites.getRealm(), is(nullValue())); assertThat(composites.getClient(), aMapWithSize(1)); assertThat(composites.getClient(), hasEntry(is("moped-client"), containsInAnyOrder("my_client_role"))); }
Example #26
Source File: ExportImportUtil.java From keycloak with Apache License 2.0 | 5 votes |
private static Set<RoleRepresentation> allScopeMappings(ClientResource client) { Set<RoleRepresentation> allRoles = new HashSet<>(); List<RoleRepresentation> realmRoles = realmScopeMappings(client); if (realmRoles != null) allRoles.addAll(realmRoles); allRoles.addAll(clientScopeMappings(client)); return allRoles; }
Example #27
Source File: RealmsConfigurationLoader.java From keycloak with Apache License 2.0 | 5 votes |
@Override public void run() { List<RoleRepresentation> roles = admin().realms().realm(realm.getRealm()).roles().list(); for (RoleRepresentation r: roles) { realmRoleIdMap.put(r.getName(), r.getId()); } }
Example #28
Source File: ScopeMappedClientResource.java From keycloak with Apache License 2.0 | 5 votes |
/** * Get the roles associated with a client's scope * * Returns roles for the client. * * @return */ @GET @Produces(MediaType.APPLICATION_JSON) @NoCache public List<RoleRepresentation> getClientScopeMappings() { viewPermission.require(); Set<RoleModel> mappings = KeycloakModelUtils.getClientScopeMappings(scopedClient, scopeContainer); //scopedClient.getClientScopeMappings(client); List<RoleRepresentation> mapRep = new ArrayList<RoleRepresentation>(); for (RoleModel roleModel : mappings) { mapRep.add(ModelToRepresentation.toBriefRepresentation(roleModel)); } return mapRep; }
Example #29
Source File: RealmRepUtil.java From keycloak with Apache License 2.0 | 5 votes |
public static RoleRepresentation findRealmRole(RealmRepresentation realm, String roleName) { if (realm.getRoles() == null) return null; if (realm.getRoles().getRealm() == null) return null; for (RoleRepresentation role : realm.getRoles().getRealm()) { if (role.getName().equals(roleName)) return role; } return null; }
Example #30
Source File: ExportAuthorizationSettingsTest.java From keycloak with Apache License 2.0 | 5 votes |
@Test public void testRoleBasedPolicy() { ClientResource clientResource = getClientResource(); AuthorizationResource authorizationResource = clientResource.authorization(); ClientRepresentation account = testRealmResource().clients().findByClientId("account").get(0); RoleRepresentation role = testRealmResource().clients().get(account.getId()).roles().get("view-profile").toRepresentation(); PolicyRepresentation policy = new PolicyRepresentation(); policy.setName("role-based-policy"); policy.setType("role"); Map<String, String> config = new HashMap<>(); config.put("roles", "[{\"id\":\"" + role.getId() +"\"}]"); policy.setConfig(config); Response create = authorizationResource.policies().create(policy); try { Assert.assertEquals(Status.CREATED, create.getStatusInfo()); } finally { create.close(); } //this call was messing up with DB, see KEYCLOAK-4340 authorizationResource.exportSettings(); //this call failed with NPE authorizationResource.exportSettings(); }