配置项:
@Value("${keycloak.auth-server-url}")
private String url;
@Value("${kc.master.realm.user.name}")
private String adminUserName;
@Value("${kc.master.realm.user.password}")
private String adminPassword;
@Value("${kc.master.realm.client.id}")
private String clientId;
@Value("${target.realm}")
private String TARGET_REALM;
private static final String MASTER_REALM = "master";
获取用户信息中的自定义属性
/**
* 获取用户的属性值
*
* @param userId
* @return
*/
public Map<String, String> getUserAttribute(String userId) {
Keycloak kcMaster = Keycloak.getInstance(url, MASTER_REALM, adminUserName, adminPassword, clientId);
RealmResource realmResource = kcMaster.realm(TARGET_REALM);
UsersResource userResource = realmResource.users();
Map<String, String> attributeMap = new HashMap<>();
List<UserRepresentation> userList = userResource.list();
for (UserRepresentation user : userList) {
Map<String, List<String>> userAttributesList = user.getAttributes();
if (userId != null && userId.equals(user.getId())) {
for (String key : userAttributesList.keySet()) {
String attribute = null;
if (userAttributesList != null && userAttributesList.get(key) != null && userAttributesList.get(key).size() > 0) {
attribute = userAttributesList.get(key).get(0);
}
attributeMap.put(key, attribute);
}
}
}
return attributeMap;
}
创建用户
/**
* 创建用户
*
* @param account
* @param password
* @param userName
* @param medicalInstitution
* @param telephone
* @param email
* @param code
* @param userLevel
*/
public void createUser(String account, String password, String userName, String medicalInstitution, String telephone, String email, String code, String userLevel) throws UserManagementException {
Keycloak kcMaster = Keycloak.getInstance(url, MASTER_REALM, adminUserName, adminPassword, clientId);
RealmResource realmResource = kcMaster.realm(TARGET_REALM);
UsersResource userResource = realmResource.users();
//编辑用户信息
UserRepresentation user = new UserRepresentation();
user.setEnabled(true);
user.setUsername(account);
user.setFirstName(userName);
// user.setLastName(lastName);
user.setEmail(email);
Map<String, List<String>> attributeMap = new HashMap<>();