Java Code Examples for org.keycloak.representations.idm.UserRepresentation#setEnabled()
The following examples show how to use
org.keycloak.representations.idm.UserRepresentation#setEnabled() .
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: ConsentsTest.java From keycloak with Apache License 2.0 | 7 votes |
@Before public void createUser() { log.debug("creating user for realm " + providerRealmName()); UserRepresentation user = new UserRepresentation(); user.setUsername(getUserLogin()); user.setEmail(getUserEmail()); user.setFirstName(getUserFirstName()); user.setLastName(getUserLastName()); user.setEmailVerified(true); user.setEnabled(true); RealmResource realmResource = adminClient.realm(providerRealmName()); String userId = createUserWithAdminClient(realmResource, user); resetUserPassword(realmResource.users().get(userId), getUserPassword(), false); }
Example 2
Source File: KeycloakRealmResourceManager.java From quarkus with Apache License 2.0 | 7 votes |
private static UserRepresentation createUser(String username, String... realmRoles) { UserRepresentation user = new UserRepresentation(); user.setUsername(username); user.setEnabled(true); user.setCredentials(new ArrayList<>()); user.setRealmRoles(Arrays.asList(realmRoles)); CredentialRepresentation credential = new CredentialRepresentation(); credential.setType(CredentialRepresentation.PASSWORD); credential.setValue(username); credential.setTemporary(false); user.getCredentials().add(credential); return user; }
Example 3
Source File: KeyCloakServiceImpl.java From sunbird-lms-service with MIT License | 7 votes |
/** * This method will take userid and boolean status to update user status * * @param userId String * @param status boolean * @throws ProjectCommonException */ private void makeUserActiveOrInactive(String userId, boolean status) { try { String fedUserId = getFederatedUserId(userId); ProjectLogger.log( "KeyCloakServiceImpl:makeUserActiveOrInactive: fedration id formed: " + fedUserId, LoggerEnum.INFO.name()); validateUserId(fedUserId); Keycloak keycloak = KeyCloakConnectionProvider.getConnection(); UserResource resource = keycloak.realm(KeyCloakConnectionProvider.SSO_REALM).users().get(fedUserId); UserRepresentation ur = resource.toRepresentation(); ur.setEnabled(status); if (isNotNull(resource)) { resource.update(ur); } } catch (Exception e) { ProjectLogger.log( "KeyCloakServiceImpl:makeUserActiveOrInactive:error occurred while blocking user: " + e, LoggerEnum.ERROR.name()); ProjectUtil.createAndThrowInvalidUserDataException(); } }
Example 4
Source File: BruteForceTest.java From keycloak with Apache License 2.0 | 6 votes |
@Test public void testPermanentLockout() throws Exception { RealmRepresentation realm = testRealm().toRepresentation(); try { // arrange realm.setPermanentLockout(true); testRealm().update(realm); // act loginInvalidPassword(); loginInvalidPassword(); // assert expectPermanentlyDisabled(); assertFalse(adminClient.realm("test").users().search("test-user@localhost", 0, 1).get(0).isEnabled()); } finally { realm.setPermanentLockout(false); testRealm().update(realm); UserRepresentation user = adminClient.realm("test").users().search("test-user@localhost", 0, 1).get(0); user.setEnabled(true); updateUser(user); } }
Example 5
Source File: PersonalInfoTest.java From keycloak with Apache License 2.0 | 6 votes |
@Test public void testNameInToolbar() { assertEquals("test user", personalInfoPage.header().getToolbarLoggedInUser()); UserRepresentation user = new UserRepresentation(); user.setUsername("edewit"); user.setEnabled(true); setPasswordFor(user, "password"); try { ApiUtil.removeUserByUsername(testRealmResource(), testUser.getUsername()); personalInfoPage.navigateTo(); ApiUtil.createUserWithAdminClient(testRealmResource(), user); loginPage.form().login(user); assertEquals("edewit", personalInfoPage.header().getToolbarLoggedInUser()); } finally { ApiUtil.removeUserByUsername(testRealmResource(), user.getUsername()); } }
Example 6
Source File: TokenIntrospectionTest.java From keycloak with Apache License 2.0 | 6 votes |
@Test public void testIntrospectAccessTokenUserDisabled() throws Exception { oauth.doLogin("test-user@localhost", "password"); String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE); AccessTokenResponse accessTokenResponse = oauth.doAccessTokenRequest(code, "password"); EventRepresentation loginEvent = events.expectLogin().assertEvent(); UserRepresentation userRep = new UserRepresentation(); try { userRep.setEnabled(false); adminClient.realm(oauth.getRealm()).users().get(loginEvent.getUserId()).update(userRep); String tokenResponse = oauth.introspectAccessTokenWithClientCredential("confidential-cli", "secret1", accessTokenResponse.getAccessToken()); TokenMetadataRepresentation rep = JsonSerialization.readValue(tokenResponse, TokenMetadataRepresentation.class); assertFalse(rep.isActive()); assertNull(rep.getUserName()); assertNull(rep.getClientId()); assertNull(rep.getSubject()); } finally { userRep.setEnabled(true); adminClient.realm(oauth.getRealm()).users().get(loginEvent.getUserId()).update(userRep); } }
Example 7
Source File: HoKTest.java From keycloak with Apache License 2.0 | 6 votes |
private void configTestRealmForTokenIntrospection(RealmRepresentation testRealm) { ClientRepresentation confApp = KeycloakModelUtils.createClient(testRealm, "confidential-cli"); confApp.setSecret("secret1"); confApp.setServiceAccountsEnabled(Boolean.TRUE); ClientRepresentation pubApp = KeycloakModelUtils.createClient(testRealm, "public-cli"); pubApp.setPublicClient(Boolean.TRUE); UserRepresentation user = new UserRepresentation(); user.setUsername("no-permissions"); CredentialRepresentation credential = new CredentialRepresentation(); credential.setType("password"); credential.setValue("password"); List<CredentialRepresentation> creds = new ArrayList<>(); creds.add(credential); user.setCredentials(creds); user.setEnabled(Boolean.TRUE); List<String> realmRoles = new ArrayList<>(); realmRoles.add("user"); user.setRealmRoles(realmRoles); testRealm.getUsers().add(user); }
Example 8
Source File: UsersInRoleTest.java From keycloak with Apache License 2.0 | 6 votes |
@Before public void beforeUsersInRoleTestClass() { // create a role via admin client testRoleRep = new RoleRepresentation("test-role", "", false); testRealmResource().roles().create(testRoleRep); emptyTestRoleRep = new RoleRepresentation("empty-test-role", "", false); testRealmResource().roles().create(emptyTestRoleRep); newUser = new UserRepresentation(); newUser.setUsername("test_user"); newUser.setEnabled(true); newUser.setId(createUserWithAdminClient(testRealmResource(), newUser)); assignRealmRoles(testRealmResource(), newUser.getId(), testRoleRep.getName()); userPage.setId(newUser.getId()); }
Example 9
Source File: AbstractAdvancedBrokerTest.java From keycloak with Apache License 2.0 | 6 votes |
/** * Refers to in old test suite: org.keycloak.testsuite.broker.AbstractKeycloakIdentityProviderTest.testDisabledUser */ @Test public void testDisabledUser() { loginUser(); logoutFromRealm(getProviderRoot(), bc.providerRealmName()); logoutFromRealm(getConsumerRoot(), bc.consumerRealmName()); RealmResource realm = adminClient.realm(bc.consumerRealmName()); UserRepresentation userRep = realm.users().search(bc.getUserLogin()).get(0); UserResource user = realm.users().get(userRep.getId()); userRep.setEnabled(false); user.update(userRep); logInWithBroker(bc); errorPage.assertCurrent(); assertEquals("Account is disabled, contact your administrator.", errorPage.getError()); }
Example 10
Source File: BackwardsCompatibilityUserStorageTest.java From keycloak with Apache License 2.0 | 6 votes |
private String addUserAndResetPassword(String username, String password) { // Save user and assert he is saved in the new storage UserRepresentation user = new UserRepresentation(); user.setEnabled(true); user.setUsername(username); Response response = testRealmResource().users().create(user); String userId = ApiUtil.getCreatedId(response); Assert.assertEquals(backwardsCompProviderId, new StorageId(userId).getProviderId()); // Update his password CredentialRepresentation passwordRep = new CredentialRepresentation(); passwordRep.setType(CredentialModel.PASSWORD); passwordRep.setValue(password); passwordRep.setTemporary(false); testRealmResource().users().get(userId).resetPassword(passwordRep); return userId; }
Example 11
Source File: AbstractX509AuthenticationTest.java From keycloak with Apache License 2.0 | 5 votes |
protected void setUserEnabled(String userName, boolean enabled) { UserRepresentation user = findUser(userName); Assert.assertNotNull(user); user.setEnabled(enabled); updateUser(user); }
Example 12
Source File: UserTest.java From keycloak with Apache License 2.0 | 5 votes |
public String createUser(String username, String email) { UserRepresentation user = new UserRepresentation(); user.setUsername(username); user.setEmail(email); user.setRequiredActions(Collections.emptyList()); user.setEnabled(true); return createUser(user); }
Example 13
Source File: UserTest.java From keycloak with Apache License 2.0 | 5 votes |
@Test public void searchByFirstNameNullForLastName() { UserRepresentation user = new UserRepresentation(); user.setUsername("user1"); user.setFirstName("Erik"); user.setRequiredActions(Collections.emptyList()); user.setEnabled(true); createUser(user); List<UserRepresentation> users = realm.users().search("Erik", 0, 50); assertEquals(1, users.size()); }
Example 14
Source File: UserTest.java From keycloak with Apache License 2.0 | 5 votes |
@Test public void searchByLastNameNullForFirstName() { UserRepresentation user = new UserRepresentation(); user.setUsername("user1"); user.setLastName("de Wit"); user.setRequiredActions(Collections.emptyList()); user.setEnabled(true); createUser(user); List<UserRepresentation> users = realm.users().search("wit", null, null); assertEquals(1, users.size()); }
Example 15
Source File: TokenIntrospectionTest.java From keycloak with Apache License 2.0 | 5 votes |
@Override public void configureTestRealm(RealmRepresentation testRealm) { ClientRepresentation confApp = KeycloakModelUtils.createClient(testRealm, "confidential-cli"); confApp.setSecret("secret1"); confApp.setServiceAccountsEnabled(Boolean.TRUE); ClientRepresentation pubApp = KeycloakModelUtils.createClient(testRealm, "public-cli"); pubApp.setPublicClient(Boolean.TRUE); ClientRepresentation samlApp = KeycloakModelUtils.createClient(testRealm, "saml-client"); samlApp.setSecret("secret2"); samlApp.setServiceAccountsEnabled(Boolean.TRUE); samlApp.setProtocol("saml"); UserRepresentation user = new UserRepresentation(); user.setUsername("no-permissions"); CredentialRepresentation credential = new CredentialRepresentation(); credential.setType("password"); credential.setValue("password"); List<CredentialRepresentation> creds = new ArrayList<>(); creds.add(credential); user.setCredentials(creds); user.setEnabled(Boolean.TRUE); List<String> realmRoles = new ArrayList<>(); realmRoles.add("user"); user.setRealmRoles(realmRoles); testRealm.getUsers().add(user); }
Example 16
Source File: ActionTokenCrossDCTest.java From keycloak with Apache License 2.0 | 4 votes |
@Test @InitialDcState(authServers = ServerSetup.ALL_NODES_IN_FIRST_DC_FIRST_NODE_IN_SECOND_DC) public void sendResetPasswordEmailSuccessWorksInCrossDc( @JmxInfinispanCacheStatistics(dc=DC.FIRST, dcNodeIndex=0, cacheName=InfinispanConnectionProvider.ACTION_TOKEN_CACHE) InfinispanStatistics cacheDc0Node0Statistics, @JmxInfinispanCacheStatistics(dc=DC.FIRST, dcNodeIndex=1, cacheName=InfinispanConnectionProvider.ACTION_TOKEN_CACHE) InfinispanStatistics cacheDc0Node1Statistics, @JmxInfinispanCacheStatistics(dc=DC.SECOND, dcNodeIndex=0, cacheName=InfinispanConnectionProvider.ACTION_TOKEN_CACHE) InfinispanStatistics cacheDc1Node0Statistics, @JmxInfinispanChannelStatistics() InfinispanStatistics channelStatisticsCrossDc) throws Exception { log.debug("--DC: START sendResetPasswordEmailSuccessWorksInCrossDc"); cacheDc0Node1Statistics.waitToBecomeAvailable(10, TimeUnit.SECONDS); Comparable originalNumberOfEntries = cacheDc0Node0Statistics.getSingleStatistics(Constants.STAT_CACHE_NUMBER_OF_ENTRIES_IN_MEMORY); UserRepresentation userRep = new UserRepresentation(); userRep.setEnabled(true); userRep.setUsername("user1"); userRep.setEmail("[email protected]"); String id = createUser(userRep); UserResource user = realm.users().get(id); List<String> actions = new LinkedList<>(); actions.add(UserModel.RequiredAction.UPDATE_PASSWORD.name()); user.executeActionsEmail(actions); Assert.assertEquals(1, greenMail.getReceivedMessages().length); MimeMessage message = greenMail.getReceivedMessages()[0]; String link = MailUtils.getPasswordResetEmailLink(message); assertSingleStatistics(cacheDc0Node0Statistics, Constants.STAT_CACHE_NUMBER_OF_ENTRIES_IN_MEMORY, () -> driver.navigate().to(link), Matchers::is ); proceedPage.assertCurrent(); proceedPage.clickProceedLink(); passwordUpdatePage.assertCurrent(); // Verify that there was at least one message sent via the channel - Even if we did the change on DC0, the message may be sent either from DC0 or DC1. Seems it depends on the actionTokens key ownership. // In case that it was sent from DC1, we will receive it in DC0. assertStatistics(channelStatisticsCrossDc, () -> { passwordUpdatePage.changePassword("new-pass", "new-pass"); }, (Map<String, Object> oldStats, Map<String, Object> newStats) -> { int oldSent = ((Number) oldStats.get(Constants.STAT_CHANNEL_SENT_MESSAGES)).intValue(); int newSent = ((Number) newStats.get(Constants.STAT_CHANNEL_SENT_MESSAGES)).intValue(); int oldReceived = ((Number) oldStats.get(Constants.STAT_CHANNEL_RECEIVED_MESSAGES)).intValue(); int newReceived = ((Number) newStats.get(Constants.STAT_CHANNEL_RECEIVED_MESSAGES)).intValue(); log.infof("oldSent: %d, newSent: %d, oldReceived: %d, newReceived: %d", oldSent, newSent, oldReceived, newReceived); Assert.assertTrue(newSent - oldSent > 0 || newReceived - oldReceived > 0); } ); assertThat(PageUtils.getPageTitle(driver), containsString("Your account has been updated.")); // Verify that there was an action token added in the node which was targetted by the link assertThat(cacheDc0Node0Statistics.getSingleStatistics(Constants.STAT_CACHE_NUMBER_OF_ENTRIES_IN_MEMORY), greaterThan(originalNumberOfEntries)); disableDcOnLoadBalancer(DC.FIRST); enableDcOnLoadBalancer(DC.SECOND); // Make sure that after going to the link, the invalidated action token has been retrieved from Infinispan server cluster in the other DC // NOTE: Using STAT_CACHE_NUMBER_OF_ENTRIES_IN_MEMORY as it doesn't contain the items from cacheLoader (remoteCache) until they are really loaded into the cache memory. That's the // statistic, which is actually increased on dc1-node0 once the used actionToken is loaded to the cache (memory) from remoteCache assertSingleStatistics(cacheDc1Node0Statistics, Constants.STAT_CACHE_NUMBER_OF_ENTRIES_IN_MEMORY, () -> driver.navigate().to(link), Matchers::greaterThan ); errorPage.assertCurrent(); log.debug("--DC: END sendResetPasswordEmailSuccessWorksInCrossDc"); }
Example 17
Source File: AbstractClientRegistrationTest.java From keycloak with Apache License 2.0 | 4 votes |
@Override public void addTestRealms(List<RealmRepresentation> testRealms) { RealmRepresentation rep = new RealmRepresentation(); rep.setEnabled(true); rep.setId(REALM_NAME); 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); UserRepresentation appUser = new UserRepresentation(); appUser.setEnabled(true); appUser.setUsername("test-user"); appUser.setEmail("test-user@localhost"); appUser.setCredentials(credentials); rep.getUsers().add(appUser); testRealms.add(rep); }
Example 18
Source File: FlowOverrideTest.java From keycloak with Apache License 2.0 | 4 votes |
@Test public void testDirectGrantHttpChallengeUserDisabled() { setupBruteForce(); Client httpClient = javax.ws.rs.client.ClientBuilder.newClient(); String grantUri = oauth.getResourceOwnerPasswordCredentialGrantUrl(); WebTarget grantTarget = httpClient.target(grantUri); Form form = new Form(); form.param(OAuth2Constants.GRANT_TYPE, OAuth2Constants.PASSWORD); form.param(OAuth2Constants.CLIENT_ID, TEST_APP_HTTP_CHALLENGE); UserRepresentation user = adminClient.realm("test").users().search("test-user@localhost").get(0); user.setEnabled(false); adminClient.realm("test").users().get(user.getId()).update(user); // user disabled Response response = grantTarget.request() .header(HttpHeaders.AUTHORIZATION, BasicAuthHelper.createHeader("test-user@localhost", "password")) .post(Entity.form(form)); assertEquals(401, response.getStatus()); assertEquals("Unauthorized", response.getStatusInfo().getReasonPhrase()); response.close(); user.setEnabled(true); adminClient.realm("test").users().get(user.getId()).update(user); // lock the user account grantTarget.request() .header(HttpHeaders.AUTHORIZATION, BasicAuthHelper.createHeader("test-user@localhost", "wrongpassword")) .post(Entity.form(form)); grantTarget.request() .header(HttpHeaders.AUTHORIZATION, BasicAuthHelper.createHeader("test-user@localhost", "wrongpassword")) .post(Entity.form(form)); // user is temporarily disabled response = grantTarget.request() .header(HttpHeaders.AUTHORIZATION, BasicAuthHelper.createHeader("test-user@localhost", "password")) .post(Entity.form(form)); assertEquals(401, response.getStatus()); assertEquals("Unauthorized", response.getStatusInfo().getReasonPhrase()); response.close(); clearBruteForce(); httpClient.close(); events.clear(); }
Example 19
Source File: UserTest.java From keycloak with Apache License 2.0 | 4 votes |
@Test @AuthServerContainerExclude(AuthServer.REMOTE) public void sendResetPasswordEmailWithRedirect() throws IOException { UserRepresentation userRep = new UserRepresentation(); userRep.setEnabled(true); userRep.setUsername("user1"); userRep.setEmail("[email protected]"); String id = createUser(userRep); UserResource user = realm.users().get(id); ClientRepresentation client = new ClientRepresentation(); client.setClientId("myclient"); client.setRedirectUris(new LinkedList<>()); client.getRedirectUris().add("http://myclient.com/*"); client.setName("myclient"); client.setEnabled(true); Response response = realm.clients().create(client); String createdId = ApiUtil.getCreatedId(response); assertAdminEvents.assertEvent(realmId, OperationType.CREATE, AdminEventPaths.clientResourcePath(createdId), client, ResourceType.CLIENT); List<String> actions = new LinkedList<>(); actions.add(UserModel.RequiredAction.UPDATE_PASSWORD.name()); try { // test that an invalid redirect uri is rejected. user.executeActionsEmail("myclient", "http://unregistered-uri.com/", actions); fail("Expected failure"); } catch (ClientErrorException e) { assertEquals(400, e.getResponse().getStatus()); ErrorRepresentation error = e.getResponse().readEntity(ErrorRepresentation.class); Assert.assertEquals("Invalid redirect uri.", error.getErrorMessage()); } user.executeActionsEmail("myclient", "http://myclient.com/home.html", actions); assertAdminEvents.assertEvent(realmId, OperationType.ACTION, AdminEventPaths.userResourcePath(id) + "/execute-actions-email", ResourceType.USER); Assert.assertEquals(1, greenMail.getReceivedMessages().length); MimeMessage message = greenMail.getReceivedMessages()[0]; String link = MailUtils.getPasswordResetEmailLink(message); driver.navigate().to(link); proceedPage.assertCurrent(); Assert.assertThat(proceedPage.getInfo(), Matchers.containsString("Update Password")); proceedPage.clickProceedLink(); passwordUpdatePage.assertCurrent(); passwordUpdatePage.changePassword("new-pass", "new-pass"); assertEquals("Your account has been updated.", driver.findElement(By.id("kc-page-title")).getText()); String pageSource = driver.getPageSource(); // check to make sure the back link is set. Assert.assertTrue(pageSource.contains("http://myclient.com/home.html")); driver.navigate().to(link); assertEquals("We are sorry...", PageUtils.getPageTitle(driver)); }
Example 20
Source File: UserTest.java From keycloak with Apache License 2.0 | 4 votes |
@Test @AuthServerContainerExclude(AuthServer.REMOTE) public void sendResetPasswordEmailWithCustomLifespan() throws IOException { UserRepresentation userRep = new UserRepresentation(); userRep.setEnabled(true); userRep.setUsername("user1"); userRep.setEmail("[email protected]"); String id = createUser(userRep); UserResource user = realm.users().get(id); List<String> actions = new LinkedList<>(); actions.add(UserModel.RequiredAction.UPDATE_PASSWORD.name()); final int lifespan = (int) TimeUnit.HOURS.toSeconds(5); user.executeActionsEmail(actions, lifespan); assertAdminEvents.assertEvent(realmId, OperationType.ACTION, AdminEventPaths.userResourcePath(id) + "/execute-actions-email", ResourceType.USER); Assert.assertEquals(1, greenMail.getReceivedMessages().length); MimeMessage message = greenMail.getReceivedMessages()[0]; MailUtils.EmailBody body = MailUtils.getBody(message); assertTrue(body.getText().contains("Update Password")); assertTrue(body.getText().contains("your Admin-client-test account")); assertTrue(body.getText().contains("This link will expire within 5 hours")); assertTrue(body.getHtml().contains("Update Password")); assertTrue(body.getHtml().contains("your Admin-client-test account")); assertTrue(body.getHtml().contains("This link will expire within 5 hours")); String link = MailUtils.getPasswordResetEmailLink(body); String token = link.substring(link.indexOf("key=") + "key=".length()); try { final AccessToken accessToken = TokenVerifier.create(token, AccessToken.class).getToken(); assertEquals(lifespan, accessToken.getExpiration() - accessToken.getIssuedAt()); } catch (VerificationException e) { throw new IOException(e); } driver.navigate().to(link); proceedPage.assertCurrent(); Assert.assertThat(proceedPage.getInfo(), Matchers.containsString("Update Password")); proceedPage.clickProceedLink(); passwordUpdatePage.assertCurrent(); passwordUpdatePage.changePassword("new-pass", "new-pass"); assertEquals("Your account has been updated.", PageUtils.getPageTitle(driver)); driver.navigate().to(link); assertEquals("We are sorry...", PageUtils.getPageTitle(driver)); }