当前位置: 首页>>代码示例>>Java>>正文


Java CredentialRepresentation.setValue方法代码示例

本文整理汇总了Java中org.keycloak.representations.idm.CredentialRepresentation.setValue方法的典型用法代码示例。如果您正苦于以下问题:Java CredentialRepresentation.setValue方法的具体用法?Java CredentialRepresentation.setValue怎么用?Java CredentialRepresentation.setValue使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在org.keycloak.representations.idm.CredentialRepresentation的用法示例。


在下文中一共展示了CredentialRepresentation.setValue方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: setUserPassword

import org.keycloak.representations.idm.CredentialRepresentation; //导入方法依赖的package包/类
public void setUserPassword(String realmId, String username, String newPassword) {
    List<UserRepresentation> retrieveUserList = client.realm(realmId).users().search(username,
            null,
            null,
            null,
            0, 1);
    if (!retrieveUserList.isEmpty()) {
        UserResource retrievedUser = client.realm(realmId).users().get(retrieveUserList.get(0).getId());
        CredentialRepresentation credential = new CredentialRepresentation();
        credential.setType(CredentialRepresentation.PASSWORD);
        credential.setValue(newPassword);
        credential.setTemporary(false);
        retrievedUser.resetPassword(credential);
        // Remove the UPDATE_PASSWORD required action
        UserRepresentation userRepresentation = retrievedUser.toRepresentation();
        userRepresentation.getRequiredActions().remove("UPDATE_PASSWORD");
        retrievedUser.update(userRepresentation);
    } else {
        throw new RuntimeException("Requested user not found");
    }
}
 
开发者ID:apache,项目名称:airavata,代码行数:22,代码来源:KeycloakIdentityServerClient.java

示例2: doPasswordUpdate

import org.keycloak.representations.idm.CredentialRepresentation; //导入方法依赖的package包/类
/**
  * This method will do the user password update.
  * @param userId String
  * @param password String
  * @return boolean true/false
  */
 @Override
 public boolean doPasswordUpdate(String userId, String password) {
 boolean response = false;
try {  
   UserResource resource =
       keycloak.realm(KeyCloakConnectionProvider.SSO_REALM).users().get(userId);
   CredentialRepresentation newCredential = new CredentialRepresentation();
   newCredential.setValue(password);
   newCredential.setType(CredentialRepresentation.PASSWORD);
   newCredential.setTemporary(true);
   resource.resetPassword(newCredential);
   response = true;
   } catch (Exception ex) {
    ProjectLogger.log(ex.getMessage(),ex);
   }
return response;
 }
 
开发者ID:project-sunbird,项目名称:sunbird-utils,代码行数:24,代码来源:KeyCloakServiceImpl.java

示例3: createUser

import org.keycloak.representations.idm.CredentialRepresentation; //导入方法依赖的package包/类
@Override
public String createUser(String username, String password, String firstname, String lastname, String email, List<String> rolenames) {
	if (username.equals("user")) {
		throw new UnsupportedOperationException("Dont't do that! (Sso rest api doesn't create user with username 'user' properly)");
	}

	CredentialRepresentation cr = new CredentialRepresentation();
	cr.setType(CredentialRepresentation.PASSWORD);
	cr.setValue(password);
	cr.setTemporary(false);

	UserRepresentation ur = new UserRepresentation();
	ur.setUsername(username);
	ur.setCredentials(Arrays.asList(cr));
	ur.setFirstName(firstname);
	ur.setLastName(lastname);
	ur.setEmail(email);
	ur.setEnabled(true);

	Response response = client.realm(realmName).users().create(ur);
	response.close();

	String userId = getUserId(username);
	client.realm(realmName).users().get(userId).resetPassword(cr);

	if (rolenames != null && rolenames.size() > 0) {
		addRealmRolesToUser(userId, rolenames);
	}

	return userId;
}
 
开发者ID:xtf-cz,项目名称:xtf,代码行数:32,代码来源:SsoRestApi.java

示例4: createUser

import org.keycloak.representations.idm.CredentialRepresentation; //导入方法依赖的package包/类
public void createUser(String realm, String userName, String password, long timeout, TimeUnit timeUnit) throws Exception {

        int maxRetries = 10;
        try (CloseableKeycloak keycloak = new CloseableKeycloak(endpoint, credentials, trustStore)) {
            RealmResource realmResource = waitForRealm(keycloak.get(), realm, timeout, timeUnit);

            for (int retries = 0; retries < maxRetries; retries++) {
                try {
                    if (realmResource.users().search(userName).isEmpty()) {
                        UserRepresentation userRep = new UserRepresentation();
                        userRep.setUsername(userName);
                        CredentialRepresentation cred = new CredentialRepresentation();
                        cred.setType(CredentialRepresentation.PASSWORD);
                        cred.setValue(password);
                        cred.setTemporary(false);
                        userRep.setCredentials(Arrays.asList(cred));
                        userRep.setEnabled(true);
                        Response response = keycloak.get().realm(realm).users().create(userRep);
                        if (response.getStatus() != 201) {
                            throw new RuntimeException("Unable to create user: " + response.getStatus());
                        }
                    } else {
                        Logging.log.info("User " + userName + " already created, skipping");
                    }
                    break;
                } catch (Exception e) {
                    Logging.log.info("Exception querying keycloak ({}), retrying", e.getMessage());
                    Thread.sleep(2000);
                }
            }
        }
    }
 
开发者ID:EnMasseProject,项目名称:enmasse,代码行数:33,代码来源:KeycloakClient.java

示例5: main

import org.keycloak.representations.idm.CredentialRepresentation; //导入方法依赖的package包/类
public static void main(String[] args) {

        String serverUrl = "http://login.acme.local:8081/auth";
        String realmName = "demo";
        String username = "idm-admin";
        String password = "test";
        String clientId = "admin-client";
        String clientSecret = "3c343ed1-2979-4e84-aa12-e3f9dbe39e76";

        Keycloak keycloak = Keycloak.getInstance(serverUrl, realmName, username, password, clientId, clientSecret);

        UserRepresentation user = new UserRepresentation();
        user.setUsername("user1");
        user.setFirstName("First1");
        user.setLastName("Lastname1");
        user.setEmail("[email protected]");
        user.setEnabled(true);

        Response createUserResponse = keycloak.realm(realmName).users().create(user);
        createUserResponse.close();

        String userId = getCreatedId(createUserResponse);
        System.out.printf("User created with id: %s%n", userId);

        CredentialRepresentation passwordCred = new CredentialRepresentation();
        passwordCred.setTemporary(false);
        passwordCred.setValue("test");
        passwordCred.setType(CredentialRepresentation.PASSWORD);

        keycloak.realm(realmName).users().get(userId).resetPassword(passwordCred);
        System.out.printf("Password for user with id: %s reseted%n", userId);


        RoleRepresentation userRealmRole = keycloak.realm(realmName).roles().get("user").toRepresentation();
        keycloak.realm(realmName).users().get(userId).roles().realmLevel().add(Arrays.asList(userRealmRole));
        System.out.printf("Granted user realm role to user with id: %s%n", userId);
    }
 
开发者ID:jugsaar,项目名称:visit-yajug-20161023-keycloak,代码行数:38,代码来源:KeycloakClientExample.java

示例6: createUser

import org.keycloak.representations.idm.CredentialRepresentation; //导入方法依赖的package包/类
/**
 * Creates a user in keycloak.
 * 
 * @param userMrn       MRN of the user
 * @param firstName     first name of user
 * @param lastName      last name of user
 * @param password      password of the user
 * @param email         email of the user
 * @param orgMrn        MRN of the org
 * @throws IOException
 */
public void createUser(String userMrn, String password, String firstName, String lastName, String email, String orgMrn, String permissions, boolean enabled) throws IOException, DuplicatedKeycloakEntry {
    log.debug("creating user: " + userMrn);

    UserRepresentation user = new UserRepresentation();
    user.setUsername(email);
    user.setEnabled(enabled);
    if (email != null && !email.trim().isEmpty()) {
        user.setEmail(email);
        user.setEmailVerified(true);
    }
    if (firstName != null && !firstName.trim().isEmpty()) {
        user.setFirstName(firstName);
    }
    if (lastName != null && !lastName.trim().isEmpty()) {
        user.setLastName(lastName);
    }
    // Set attributes
    Map<String, List<String>> attr = new HashMap<>();
    attr.put("org", Collections.singletonList(orgMrn));
    attr.put("mrn", Collections.singletonList(userMrn));
    if (permissions != null && !permissions.trim().isEmpty()) {
        attr.put("permissions", Collections.singletonList(permissions));
    }
    user.setAttributes(attr);
    Response ret = getProjectUserRealm().users().create(user);
    String errMsg = ret.readEntity(String.class);
    if (ret.getStatus() != 201) {
        if (ret.getStatus() == 409) {
            log.debug("creating user failed due to duplicated user" + errMsg);
            throw new DuplicatedKeycloakEntry("User with mrn: " +userMrn + " already exists.", errMsg);
        } else {
            log.debug("creating user failed, status: " + ret.getStatus() + ", " + errMsg);
            throw new IOException("User creating failed: " + errMsg);
        }
    }
    log.debug("created user, status: " + ret.getStatus() + ", " + errMsg);
    ret.close();
    
    // Set credentials
    CredentialRepresentation cred = new CredentialRepresentation();
    cred.setType(CredentialRepresentation.PASSWORD);
    cred.setValue(password);
    // Make sure the user updates the password on first login
    cred.setTemporary(true);
    // Find the user by searching for the username
    user = getProjectUserRealm().users().search(email, null, null, null, -1, -1).get(0);
    user.setCredentials(Collections.singletonList(cred));
    log.debug("setting password for user: " + user.getId());
    getProjectUserRealm().users().get(user.getId()).resetPassword(cred);
    log.debug("created user");
}
 
开发者ID:MaritimeConnectivityPlatform,项目名称:IdentityRegistry,代码行数:63,代码来源:KeycloakAdminUtil.java

示例7: migrateUserStore

import org.keycloak.representations.idm.CredentialRepresentation; //导入方法依赖的package包/类
void migrateUserStore(List<UserProfileDAO> userProfiles, String targetRealm, String tempPassword, Map<String,String> roleConversionMap){

        Map<String, RoleRepresentation> allRealmRoles = getRealmRoleNameMap(targetRealm);

        for(UserProfileDAO userProfile : userProfiles){
            UserRepresentation user = new UserRepresentation();
            user.setUsername(userProfile.getUserName());
            user.setFirstName(userProfile.getFirstName());
            user.setLastName(userProfile.getLastName());
            user.setEmail(userProfile.getEmail());
            user.setEmailVerified(true);
            user.setEnabled(true);
            List<String> requiredActionList = new ArrayList<>();
            requiredActionList.add("UPDATE_PASSWORD");
            user.setRequiredActions(requiredActionList);
            Response httpResponse = this.client.realm(targetRealm).users().create(user);
            System.out.println(httpResponse.getStatus());
            if(httpResponse.getStatus() == 201){ //HTTP code for record creation: HTTP 201
                List<UserRepresentation> retrieveCreatedUserList = this.client.realm(targetRealm).users().search(user.getUsername(),
                        user.getFirstName(),
                        user.getLastName(),
                        user.getEmail(),
                        0,1);
                UserResource retirievedUser = this.client.realm(targetRealm).users().get(retrieveCreatedUserList.get(0).getId());

                // Add user to realm roles
                List<RoleRepresentation> userRealmRoles = userProfile.getRoles().stream()
                        .filter(r -> roleConversionMap.containsKey(r))
                        // Convert from IS role name to Keycloak role name
                        .map(r -> roleConversionMap.get(r))
                        // Convert from Keycloak role name to RoleRepresentation
                        .map(r -> allRealmRoles.get(r))
                        .collect(Collectors.toList());
                retirievedUser.roles().realmLevel().add(userRealmRoles);

                CredentialRepresentation credential = new CredentialRepresentation();
                credential.setType(CredentialRepresentation.PASSWORD);
                credential.setValue(tempPassword);
                credential.setTemporary(true);
                retirievedUser.resetPassword(credential);
                System.out.println("User profile for user " + userProfile.getUserName() + " successfully migrated");
            } else {
                String response = httpResponse.readEntity(String.class);
                System.err.println("Failed to add user [" + userProfile.getUserName() + "] to Keycloak");
                System.err.println("Response: " + response);
            }
            if (httpResponse != null) {
                httpResponse.close();
            }
        }
    }
 
开发者ID:apache,项目名称:airavata,代码行数:52,代码来源:KeycloakIdentityServerClient.java

示例8: main

import org.keycloak.representations.idm.CredentialRepresentation; //导入方法依赖的package包/类
public static void main(String[] args) throws Exception {
	// new JHades().overlappingJarsReport();

	Keycloak kc = KeycloakBuilder.builder() //
			.serverUrl("https://localhost:8443/auth") //
			.realm("master")//
			.username("admin") //
			.password("admin") //
			.clientId("admin-cli") //
			.resteasyClient(new ResteasyClientBuilder().connectionPoolSize(10).build()) //
			.build();

	CredentialRepresentation credential = new CredentialRepresentation();
	credential.setType(CredentialRepresentation.PASSWORD);
	credential.setValue("test123");
	credential.setTemporary(false);

	UserRepresentation user = new UserRepresentation();
	user.setUsername("testuser2");
	user.setFirstName("Test2");
	user.setLastName("User2");
	user.setEmail("[email protected]");
	user.setCredentials(Arrays.asList(credential));
	user.setEnabled(true);
	user.setRealmRoles(Arrays.asList("admin"));

	// Create testuser
	Response result = kc.realm("ait-platform").users().create(user);
	if (result.getStatus() != 201) {
		System.err.println("Couldn't create user.");
		System.exit(0);
	}
	System.out.println("Testuser created.... verify in keycloak!");

	System.out.println("Press any key...");
	System.in.read();

	// Delete testuser
	String locationHeader = result.getHeaderString("Location");
	String userId = locationHeader.replaceAll(".*/(.*)$", "$1");
	UserResource user1 = kc.realm("ait-platform").users().get(userId);
	System.out.println(user1.toRepresentation());
}
 
开发者ID:allianzit,项目名称:ait-platform,代码行数:44,代码来源:KeycloakAdminClientExample.java


注:本文中的org.keycloak.representations.idm.CredentialRepresentation.setValue方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。