/** * Update the top-level information of the realm * * <p>Any user, roles or client information in the representation will be ignored. This will only * update top-level attributes of the realm. * * @param rep * @return */ @PUT @Consumes(MediaType.APPLICATION_JSON) public Response updateRealm(final RealmRepresentation rep) { auth.requireManage(); logger.debug("updating realm: " + realm.getName()); if (Config.getAdminRealm().equals(realm.getName()) && (rep.getRealm() != null && !rep.getRealm().equals(Config.getAdminRealm()))) { return ErrorResponse.error("Can't rename master realm", Status.BAD_REQUEST); } try { if (!Constants.GENERATE.equals(rep.getPublicKey()) && (rep.getPrivateKey() != null && rep.getPublicKey() != null)) { try { KeyPairVerifier.verify(rep.getPrivateKey(), rep.getPublicKey()); } catch (VerificationException e) { return ErrorResponse.error(e.getMessage(), Status.BAD_REQUEST); } } if (!Constants.GENERATE.equals(rep.getPublicKey()) && (rep.getCertificate() != null)) { try { X509Certificate cert = PemUtils.decodeCertificate(rep.getCertificate()); if (cert == null) { return ErrorResponse.error("Failed to decode certificate", Status.BAD_REQUEST); } } catch (Exception e) { return ErrorResponse.error("Failed to decode certificate", Status.BAD_REQUEST); } } RepresentationToModel.updateRealm(rep, realm, session); // Refresh periodic sync tasks for configured federationProviders List<UserStorageProviderModel> federationProviders = realm.getUserStorageProviders(); UserStorageSyncManager usersSyncManager = new UserStorageSyncManager(); for (final UserStorageProviderModel fedProvider : federationProviders) { usersSyncManager.notifyToRefreshPeriodicSync(session, realm, fedProvider, false); } adminEvent .operation(OperationType.UPDATE) .representation(StripSecretsUtils.strip(rep)) .success(); return Response.noContent().build(); } catch (PatternSyntaxException e) { return ErrorResponse.error( "Specified regex pattern(s) is invalid.", Response.Status.BAD_REQUEST); } catch (ModelDuplicateException e) { return ErrorResponse.exists("Realm with same name exists"); } catch (Exception e) { logger.error(e.getMessage(), e); return ErrorResponse.error("Failed to update realm", Response.Status.INTERNAL_SERVER_ERROR); } }
@Before public void setupAdminEvents() { RealmRepresentation realm = testRealmResource().toRepresentation(); if (realm.getEventsListeners() == null || !realm.getEventsListeners().contains(EventsListenerProviderFactory.PROVIDER_ID)) { realm = RealmBuilder.edit(testRealmResource().toRepresentation()).testEventListener().build(); testRealmResource().update(realm); } }
protected void addRealmRep( List<RealmRepresentation> reps, RealmModel realm, ClientModel realmManagementClient) { if (auth.hasAppRole(realmManagementClient, AdminRoles.VIEW_REALM)) { reps.add(ModelToRepresentation.toRepresentation(realm, false)); } else if (auth.hasOneOfAppRole(realmManagementClient, AdminRoles.ALL_REALM_ROLES)) { RealmRepresentation rep = new RealmRepresentation(); rep.setRealm(realm.getName()); reps.add(rep); } }
@Test public void install2() throws Exception { RealmManager manager = realmManager; RealmRepresentation rep = AbstractModelTest.loadJson("model/testrealm-demo.json"); rep.setId("demo"); RealmModel realm = manager.importRealm(rep); Assert.assertEquals(600, realm.getAccessCodeLifespanUserAction()); verifyRequiredCredentials(realm.getRequiredCredentials(), "password"); }
@Test public void install2() throws Exception { RealmManager manager = realmManager; RealmRepresentation rep = AbstractModelTest.loadJson("testrealm-demo.json"); RealmModel realm = manager.createRealm("demo", rep.getRealm()); manager.importRealm(rep, realm); Assert.assertFalse(realm.isUpdateProfileOnInitialSocialLogin()); Assert.assertEquals(600, realm.getAccessCodeLifespanUserAction()); verifyRequiredCredentials(realm.getRequiredCredentials(), "password"); }
public void importRealm(RealmRepresentation realm) { log.debug("importing realm: " + realm.getRealm()); try { // TODO - figure out a way how to do this without try-catch RealmResource realmResource = adminClient.realms().realm(realm.getRealm()); RealmRepresentation rRep = realmResource.toRepresentation(); log.debug("realm already exists on server, re-importing"); realmResource.remove(); } catch (NotFoundException nfe) { // expected when realm does not exist } adminClient.realms().create(realm); }
public static void addRequiredActionForRealm(RealmRepresentation testRealm, String providerId) { List<RequiredActionProviderRepresentation> requiredActions = testRealm.getRequiredActions(); if (requiredActions == null) requiredActions = new LinkedList(); RequiredActionProviderRepresentation action = new RequiredActionProviderRepresentation(); action.setAlias(providerId); action.setProviderId(providerId); action.setEnabled(true); action.setDefaultAction(true); requiredActions.add(action); testRealm.setRequiredActions(requiredActions); }
@POST @Consumes("application/json") public Response importRealm(@Context final UriInfo uriInfo, final RealmRepresentation rep) { logger.debug("importRealm: {0}", rep.getRealm()); RealmManager realmManager = new RealmManager(session); if (realmManager.getRealm(rep.getRealm()) != null) { return Flows.errors().exists("Realm " + rep.getRealm() + " already exists"); } RealmModel realm = realmManager.importRealm(rep, admin); URI location = realmUrl(uriInfo).build(realm.getId()); logger.debug("imported realm success, sending back: {0}", location.toString()); return Response.created(location).build(); }
@GET @NoCache @Produces("application/json") public RealmRepresentation getRealm() { if (auth.hasView()) { return ModelToRepresentation.toRepresentation(realm); } else { auth.requireAny(); RealmRepresentation rep = new RealmRepresentation(); rep.setRealm(realm.getName()); return rep; } }
/** * Import a realm * * <p>Imports a realm from a full representation of that realm. Realm name must be unique. * * @param uriInfo * @param rep JSON representation of the realm * @return */ @POST @Consumes(MediaType.APPLICATION_JSON) public Response importRealm(@Context final UriInfo uriInfo, final RealmRepresentation rep) { RealmManager realmManager = new RealmManager(session); realmManager.setContextPath(keycloak.getContextPath()); if (!auth.getRealm().equals(realmManager.getKeycloakAdminstrationRealm())) { throw new ForbiddenException(); } if (!auth.hasRealmRole(AdminRoles.CREATE_REALM)) { throw new ForbiddenException(); } logger.debugv("importRealm: {0}", rep.getRealm()); try { RealmModel realm = realmManager.importRealm(rep); grantPermissionsToRealmCreator(realm); URI location = AdminRoot.realmsUrl(uriInfo).path(realm.getName()).build(); logger.debugv("imported realm success, sending back: {0}", location.toString()); return Response.created(location).build(); } catch (ModelDuplicateException e) { return ErrorResponse.exists("Realm with same name exists"); } }
// KEYCLOAK-3823: Test that sending notBefore policy invalidates JWKPublicKeyLocator cache @Test public void testPublicKeyCacheInvalidatedWhenPushedNotBefore() { driver.manage().timeouts().pageLoadTimeout(1000, TimeUnit.SECONDS); // increase accessTokenLifespan to 1200 RealmRepresentation demoRealm = adminClient.realm(DEMO).toRepresentation(); demoRealm.setAccessTokenLifespan(1200); adminClient.realm(DEMO).update(demoRealm); // authenticate in tokenMinTTL app loginToTokenMinTtlApp(); String accessTokenString = tokenMinTTLPage.getAccessTokenString(); // Generate new realm public key String oldActiveKeyProviderId = getActiveKeyProvider(); generateNewRealmKey(); // Send REST request to customer-db app. It should be successfully authenticated even that token // is signed by the old key int status = invokeRESTEndpoint(accessTokenString); Assert.assertEquals(200, status); // Remove the old realm key now adminClient.realm(DEMO).components().component(oldActiveKeyProviderId).remove(); // Set some offset to ensure pushing notBefore will pass setAdapterAndServerTimeOffset( 130, customerDb.toString() + "/unsecured/foo", tokenMinTTLPage.toString() + "/unsecured/foo"); // Send notBefore policy from the realm demoRealm.setNotBefore(Time.currentTime() - 1); adminClient.realm(DEMO).update(demoRealm); GlobalRequestResult result = adminClient.realm(DEMO).pushRevocation(); Assert.assertTrue(result.getSuccessRequests().contains(customerDb.toString())); // Send REST request. New request to the publicKey cache should be sent, and key is no longer // returned as token contains the old kid status = invokeRESTEndpoint(accessTokenString); Assert.assertEquals(401, status); // Revert public keys change and time offset resetKeycloakDeploymentForAdapter(customerDb.toString() + "/unsecured/foo"); resetKeycloakDeploymentForAdapter(tokenMinTTLPage.toString() + "/unsecured/foo"); }
public static UserRepresentation findUserInRealmRep( RealmRepresentation testRealm, String username) { for (UserRepresentation rep : testRealm.getUsers()) { if (rep.getUsername().equals(username)) return rep; } return null; }
@Test public void install() throws Exception { RealmRepresentation rep = AbstractModelTest.loadJson("testrealm.json"); RealmModel realm = realmManager.createRealm("demo", rep.getRealm()); realmManager.importRealm(rep, realm); // Commit after import commit(); realm = realmManager.getRealm("demo"); assertDataImportedInRealm(realm); commit(); realm = realmManager.getRealm("demo"); realmManager.removeRealm(realm); }
@Before public void before() throws MalformedURLException { RealmRepresentation testRealm = testRealm().toRepresentation(); testRealm.setOtpPolicyType(UserCredentialModel.HOTP); testRealm.setOtpPolicyLookAheadWindow(2); testRealm().update(testRealm); policy = new OTPPolicy(); policy.setAlgorithm(testRealm.getOtpPolicyAlgorithm()); policy.setDigits(testRealm.getOtpPolicyDigits()); policy.setInitialCounter(testRealm.getOtpPolicyInitialCounter()); policy.setLookAheadWindow(testRealm.getOtpPolicyLookAheadWindow()); policy.setPeriod(testRealm.getOtpPolicyLookAheadWindow()); policy.setType(testRealm.getOtpPolicyType()); otp = new HmacOTP(policy.getDigits(), policy.getAlgorithm(), policy.getLookAheadWindow()); }
/** * Update the top-level information of the realm * * <p>Any user, roles or client information in the representation will be ignored. This will only * update top-level attributes of the realm. * * @param rep * @return */ @PUT @Consumes(MediaType.APPLICATION_JSON) public Response updateRealm(final RealmRepresentation rep) { auth.requireManage(); logger.debug("updating realm: " + realm.getName()); try { RepresentationToModel.updateRealm(rep, realm); if (rep.isRealmCacheEnabled() != null && session.realms() instanceof CacheRealmProvider) { CacheRealmProvider cacheRealmProvider = (CacheRealmProvider) session.realms(); cacheRealmProvider.setEnabled(rep.isRealmCacheEnabled()); } if (rep.isUserCacheEnabled() != null && session.userStorage() instanceof CacheUserProvider) { CacheUserProvider cache = (CacheUserProvider) session.userStorage(); cache.setEnabled(rep.isUserCacheEnabled()); } // Refresh periodic sync tasks for configured federationProviders List<UserFederationProviderModel> federationProviders = realm.getUserFederationProviders(); UsersSyncManager usersSyncManager = new UsersSyncManager(); for (final UserFederationProviderModel fedProvider : federationProviders) { usersSyncManager.refreshPeriodicSyncForProvider( session.getKeycloakSessionFactory(), session.getProvider(TimerProvider.class), fedProvider, realm.getId()); } adminEvent.operation(OperationType.UPDATE).representation(rep).success(); return Response.noContent().build(); } catch (PatternSyntaxException e) { return ErrorResponse.error( "Specified regex pattern(s) is invalid.", Response.Status.BAD_REQUEST); } catch (ModelDuplicateException e) { throw e; } catch (Exception e) { logger.error(e); return ErrorResponse.error( "Failed to update " + rep.getRealm() + " Realm.", Response.Status.INTERNAL_SERVER_ERROR); } }
@PUT @Consumes("application/json") public Response updateRealm(final RealmRepresentation rep) { auth.requireManage(); logger.debug("updating realm: " + realm.getName()); try { new RealmManager(session).updateRealm(rep, realm); return Response.noContent().build(); } catch (ModelDuplicateException e) { return Flows.errors().exists("Realm " + rep.getRealm() + " already exists"); } }
// KEYCLOAK-3824: Test for public-key-cache-ttl @Test public void testPublicKeyCacheTtl() { // increase accessTokenLifespan to 1200 RealmRepresentation demoRealm = adminClient.realm(DEMO).toRepresentation(); demoRealm.setAccessTokenLifespan(1200); adminClient.realm(DEMO).update(demoRealm); // authenticate in tokenMinTTL app loginToTokenMinTtlApp(); String accessTokenString = tokenMinTTLPage.getAccessTokenString(); // Send REST request to customer-db app. I should be successfully authenticated int status = invokeRESTEndpoint(accessTokenString); Assert.assertEquals(200, status); // Re-generate realm public key and remove the old key String oldActiveKeyProviderId = getActiveKeyProvider(); generateNewRealmKey(); adminClient.realm(DEMO).components().component(oldActiveKeyProviderId).remove(); // Send REST request to the customer-db app. Should be still succcessfully authenticated as the // JWKPublicKeyLocator cache is still valid status = invokeRESTEndpoint(accessTokenString); Assert.assertEquals(200, status); // TimeOffset to 900 on the REST app side. Token is still valid (1200) but JWKPublicKeyLocator // should try to download new key (public-key-cache-ttl=600) setAdapterAndServerTimeOffset(900, customerDb.toString() + "/unsecured/foo"); // Send REST request. New request to the publicKey cache should be sent, and key is no longer // returned as token contains the old kid status = invokeRESTEndpoint(accessTokenString); Assert.assertEquals(401, status); // Revert public keys change and time offset resetKeycloakDeploymentForAdapter(customerDb.toString() + "/unsecured/foo"); resetKeycloakDeploymentForAdapter(tokenMinTTLPage.toString() + "/unsecured/foo"); }
/** * Get the top-level representation of the realm * * <p>It will not include nested information like User and Client representations. * * @return */ @GET @NoCache @Produces(MediaType.APPLICATION_JSON) public RealmRepresentation getRealm() { if (auth.hasView()) { RealmRepresentation rep = ModelToRepresentation.toRepresentation(realm, false); if (session.realms() instanceof CacheRealmProvider) { CacheRealmProvider cacheRealmProvider = (CacheRealmProvider) session.realms(); rep.setRealmCacheEnabled(cacheRealmProvider.isEnabled()); } if (session.userStorage() instanceof CacheUserProvider) { CacheUserProvider cache = (CacheUserProvider) session.userStorage(); rep.setUserCacheEnabled(cache.isEnabled()); } return rep; } else { auth.requireAny(); RealmRepresentation rep = new RealmRepresentation(); rep.setRealm(realm.getName()); return rep; } }
@Override public void addTestRealms(List<RealmRepresentation> testRealms) { RealmRepresentation rep = new RealmRepresentation(); rep.setEnabled(true); rep.setRealm(REALM_NAME); rep.setUsers(new LinkedList<UserRepresentation>()); LinkedList<CredentialRepresentation> credentials = new LinkedList<>(); CredentialRepresentation password = new CredentialRepresentation(); password.setType(CredentialRepresentation.PASSWORD); password.setValue("password"); credentials.add(password); UserRepresentation user = new UserRepresentation(); user.setEnabled(true); user.setUsername("manage-clients"); user.setCredentials(credentials); user.setClientRoles( Collections.singletonMap( Constants.REALM_MANAGEMENT_CLIENT_ID, Collections.singletonList(AdminRoles.MANAGE_CLIENTS))); rep.getUsers().add(user); UserRepresentation user2 = new UserRepresentation(); user2.setEnabled(true); user2.setUsername("create-clients"); user2.setCredentials(credentials); user2.setClientRoles( Collections.singletonMap( Constants.REALM_MANAGEMENT_CLIENT_ID, Collections.singletonList(AdminRoles.CREATE_CLIENT))); rep.getUsers().add(user2); UserRepresentation user3 = new UserRepresentation(); user3.setEnabled(true); user3.setUsername("no-access"); user3.setCredentials(credentials); rep.getUsers().add(user3); testRealms.add(rep); }
/** * Get the top-level representation of the realm * * <p>It will not include nested information like User and Client representations. * * @return */ @GET @NoCache @Produces(MediaType.APPLICATION_JSON) public RealmRepresentation getRealm() { if (auth.hasView()) { return ModelToRepresentation.toRepresentation(realm, false); } else { auth.requireAny(); RealmRepresentation rep = new RealmRepresentation(); rep.setRealm(realm.getName()); if (auth.init(Resource.IDENTITY_PROVIDER).hasView()) { RealmRepresentation r = ModelToRepresentation.toRepresentation(realm, false); rep.setIdentityProviders(r.getIdentityProviders()); rep.setIdentityProviderMappers(r.getIdentityProviderMappers()); } return rep; } }
@Test public void addUserTest() throws Throwable { AddUser.main(new String[] {"-u", "addusertest-admin", "-p", "password"}); assertEquals(1, dir.listFiles().length); List<RealmRepresentation> realms = JsonSerialization.readValue( new FileInputStream(new File(dir, "keycloak-add-user.json")), new TypeReference<List<RealmRepresentation>>() {}); assertEquals(1, realms.size()); assertEquals(1, realms.get(0).getUsers().size()); UserRepresentation user = realms.get(0).getUsers().get(0); assertEquals(new Integer(100000), user.getCredentials().get(0).getHashIterations()); assertNull(user.getCredentials().get(0).getValue()); CredentialRepresentation credentials = user.getCredentials().get(0); assertEquals(Pbkdf2PasswordHashProvider.ID, credentials.getAlgorithm()); assertEquals(new Integer(100000), credentials.getHashIterations()); KeycloakServer server = new KeycloakServer(); try { server.start(); Keycloak keycloak = Keycloak.getInstance( "http://localhost:8081/auth", "master", "addusertest-admin", "password", Constants.ADMIN_CLI_CLIENT_ID); keycloak.realms().findAll(); RealmRepresentation testRealm = new RealmRepresentation(); testRealm.setEnabled(true); testRealm.setId("test"); testRealm.setRealm("test"); keycloak.realms().create(testRealm); RealmResource realm = keycloak.realm("master"); List<UserRepresentation> users = realm.users().search("addusertest-admin", null, null, null, null, null); assertEquals(1, users.size()); UserRepresentation created = users.get(0); assertNotNull(created.getCreatedTimestamp()); UserResource userResource = realm.users().get(created.getId()); List<RoleRepresentation> realmRoles = userResource.roles().realmLevel().listAll(); assertRoles(realmRoles, "admin", "offline_access"); List<ClientRepresentation> clients = realm.clients().findAll(); String accountId = null; for (ClientRepresentation c : clients) { if (c.getClientId().equals("account")) { accountId = c.getId(); } } List<RoleRepresentation> accountRoles = userResource.roles().clientLevel(accountId).listAll(); assertRoles(accountRoles, "view-profile", "manage-account"); keycloak.close(); assertEquals(0, dir.listFiles().length); } finally { server.stop(); } }
public void removeRealm(RealmRepresentation realm) { removeRealm(realm.getRealm()); }
private void switchEditUsernameAllowedOn() { RealmRepresentation rep = realm.toRepresentation(); rep.setEditUsernameAllowed(true); realm.update(rep); }
public void install(RealmManager manager) { RealmRepresentation rep = loadJson("META-INF/testrealm.json"); RealmModel realm = manager.createRealm("demo", rep.getRealm()); manager.importRealm(rep, realm); }